From 3b48740fcfb0a19e8a8af04cd673de4c32e9e950 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 24 Jul 2026 12:35:41 +0000 Subject: [PATCH 1/2] Wire MCP doc/repo retrieval into the Ask Freya assistant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Give the assistant live access to the Frigg docs and repo via the new Freya MCP client (@freyaframework/mcp-client), in proxy mode so each server costs a flat two tools per turn. - entry.mjs: compose RoadmapTools with an McpClientToolExecutor behind one CompositeToolExecutor. MCP servers are built from env and offered only when keyed, so the widget degrades gracefully: - frigg-docs → Context7 (semantic docs), CONTEXT7_API_KEY - frigg-repo → GitHub MCP (branch-accurate next file/code), GITHUB_MCP_TOKEN Uses a dedicated GITHUB_MCP_TOKEN (no ambient GITHUB_TOKEN fallback) to avoid half-activating the GitHub server with a wrong-scoped token. - lib/freya-runtime.mjs: regenerated bundle now includes the MCP client + SDK (self-contained; ~1.25 MB; no stdio/cross-spawn pulled in). - assistant.mjs: system prompt tells the agent to use the *_list_tools / *_call_tool sources for deep/technical/source questions when present. - context7.json: pins Context7 indexing to the next branch + docs/. Verified against the real bundle: non-MCP paths unchanged; with CONTEXT7_API_KEY set, frigg-docs proxy tools are offered alongside the roadmap tools (proxy discovery makes no network call); frigg-repo stays dormant until GITHUB_MCP_TOKEN is set. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_018ixfrejnfZWd8TPZamZYdv --- context7.json | 13 + website/friggframework-api/assistant.mjs | 7 + .../friggframework-api/lib/freya-runtime.mjs | 29742 +++++++++++++++- website/tools/freya-vendor/entry.mjs | 83 +- 4 files changed, 29793 insertions(+), 52 deletions(-) create mode 100644 context7.json diff --git a/context7.json b/context7.json new file mode 100644 index 000000000..e425670a0 --- /dev/null +++ b/context7.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://context7.com/schema/context7.json", + "projectTitle": "Frigg Framework", + "description": "Open-source, serverless-native framework for building direct/native integrations, maintained by Left Hook.", + "branch": "next", + "folders": ["docs"], + "excludeFolders": ["website", "node_modules", "**/dist", "**/__tests__"], + "rules": [ + "Frigg is serverless-native (AWS Lambda) and cloud-agnostic; adopters own their stack.", + "Integrations extend IntegrationBase; API modules are installed with `frigg install `.", + "The authoritative API-module catalog and roadmap live at /roadmap/ on friggframework.org." + ] +} diff --git a/website/friggframework-api/assistant.mjs b/website/friggframework-api/assistant.mjs index 52d9a337e..81fa8a27c 100644 --- a/website/friggframework-api/assistant.mjs +++ b/website/friggframework-api/assistant.mjs @@ -199,6 +199,13 @@ Rules: ANY question about specific ADRs, API modules, catalog counts, or what's built vs. planned, call the tool and answer from what it returns — do not guess or recite from memory. Everything else is grounded in the reference below. +- You may also have live documentation/source tools whose names end in + "_list_tools" and "_call_tool" (e.g. frigg-docs for the Frigg docs, frigg-repo + for the repository on the next branch). When present, use them for deep, + technical, or how-does-the-code-work questions the reference doesn't cover: + call the "_list_tools" one to see what a source offers, then "_call_tool" to + fetch, and answer from the result rather than guessing. If they're absent, just + rely on the reference and point to the docs. - If something isn't covered by a tool or the reference, say so plainly and point to the docs (https://docs.friggframework.org), the GitHub repo, or /roadmap/ rather than inventing specifics. diff --git a/website/friggframework-api/lib/freya-runtime.mjs b/website/friggframework-api/lib/freya-runtime.mjs index 22a447ec7..8c5c975e7 100644 --- a/website/friggframework-api/lib/freya-runtime.mjs +++ b/website/friggframework-api/lib/freya-runtime.mjs @@ -1,11 +1,29361 @@ // GENERATED — vendored Freya runtime. Do not edit by hand. // Regenerate via website/tools/freya-vendor/build.mjs. +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/chunk-Br0eD_fh.mjs +var __create, __defProp2, __getOwnPropDesc, __getOwnPropNames2, __getProtoOf, __hasOwnProp, __commonJSMin, __exportAll, __copyProps, __toESM; +var init_chunk_Br0eD_fh = __esm({ + "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/chunk-Br0eD_fh.mjs"() { + __create = Object.create; + __defProp2 = Object.defineProperty; + __getOwnPropDesc = Object.getOwnPropertyDescriptor; + __getOwnPropNames2 = Object.getOwnPropertyNames; + __getProtoOf = Object.getPrototypeOf; + __hasOwnProp = Object.prototype.hasOwnProperty; + __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); + __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp2(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp2(target, Symbol.toStringTag, { value: "Module" }); + } + return target; + }; + __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames2(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp2(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; + }; + __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { + value: mod, + enumerable: true + }) : target, mod)); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, params) { + function init(inst, def) { + if (!inst._zod) { + Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _, + traits: /* @__PURE__ */ new Set() + }, + enumerable: false + }); + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + const proto = _.prototype; + const keys = Object.keys(proto); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a2; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a2 = inst._zod).deferred ?? (_a2.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + 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 _; +} +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} +var NEVER, $ZodAsyncError, $ZodEncodeError, globalConfig; +var init_core = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"() { + NEVER = Object.freeze({ + status: "aborted" + }); + $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } + }; + $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } + }; + globalConfig = {}; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + base64ToUint8Array: () => base64ToUint8Array, + base64urlToUint8Array: () => base64urlToUint8Array, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + cloneDef: () => cloneDef, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex2, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType, + getSizableOrigin: () => getSizableOrigin, + hexToUint8Array: () => hexToUint8Array, + isObject: () => isObject, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + mergeDefs: () => mergeDefs, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + objectClone: () => objectClone, + omit: () => omit, + optionalKeys: () => optionalKeys, + parsedType: () => parsedType, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + safeExtend: () => safeExtend, + shallowClone: () => shallowClone, + slugify: () => slugify, + stringifyPrimitive: () => stringifyPrimitive, + uint8ArrayToBase64: () => uint8ArrayToBase64, + uint8ArrayToBase64url: () => uint8ArrayToBase64url, + uint8ArrayToHex: () => uint8ArrayToHex, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +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(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; +} +function nullish(input) { + return input === null || input === void 0; +} +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 valDecCount = (val.toString().split(".")[1] || "").length; + const stepString = step.toString(); + let stepDecCount = (stepString.split(".")[1] || "").length; + if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { + const match = stepString.match(/\d?e-(\d?)/); + if (match?.[1]) { + stepDecCount = Number.parseInt(match[1]); + } + } + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function defineLazy(object2, key, getter) { + let value = void 0; + Object.defineProperty(object2, key, { + get() { + if (value === EVALUATING) { + return void 0; + } + if (value === void 0) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object2, key, { + value: v + // configurable: true, + }); + }, + 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 esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +function isPlainObject(o) { + if (isObject(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + if (typeof ctor !== "function") + return true; + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + 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]; + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +function escapeRegex2(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +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 !== void 0) { + if (params?.error !== void 0) + 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 === "optional" && shape[k]._zod.optout === "optional"; + }); +} +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 (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); + 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 in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); + 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) { + const existingShape = schema._zod.def.shape; + for (const key in shape) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { + 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); + 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); + return _shape; + } + }); + return clone(schema, def); +} +function merge(a, b) { + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: [] + // delete existing checks + }); + return clone(a, def); +} +function partial(Class2, schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".partial() 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 in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + assignProp(this, "shape", shape); + return shape; + }, + checks: [] + }); + return clone(schema, def); +} +function required(Class2, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + assignProp(this, "shape", shape); + return shape; + } + }); + return clone(schema, def); +} +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; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a2; + (_a2 = iss).path ?? (_a2.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message2) { + return typeof message2 === "string" ? message2 : message2?.message; +} +function finalizeIssue(iss, ctx, config2) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message2 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + full.message = message2; + } + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +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 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 Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); +} +function base64ToUint8Array(base643) { + const binaryString = atob(base643); + 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(base64url3) { + const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - base643.length % 4) % 4); + return base64ToUint8Array(base643 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex3) { + const cleanHex = hex3.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(""); +} +var EVALUATING, captureStackTrace, allowsEval, getParsedType, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; +var init_util = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"() { + EVALUATING = /* @__PURE__ */ Symbol("evaluating"); + captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { + }; + allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; + } + }); + 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"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } + }; + propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); + primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); + NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] + }; + BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] + }; + Class = class { + constructor(..._args) { + } + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js +function flattenError(error2, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error2.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error2, mapper = (issue2) => issue2.message) { + const fieldErrors = { _errors: [] }; + const processError = (error3) => { + for (const issue2 of error3.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues })); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue2.path.length) { + const el = issue2.path[i]; + const terminal = i === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(error2); + return fieldErrors; +} +var initializer, $ZodError, $ZodRealError; +var init_errors = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js"() { + init_core(); + init_util(); + initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); + }; + $ZodError = $constructor("$ZodError", initializer); + $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js +var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, _decode, _encodeAsync, _decodeAsync, _safeEncode, _safeDecode, _safeEncodeAsync, _safeDecodeAsync; +var init_parse = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"() { + init_core(); + init_errors(); + init_util(); + _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_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, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; + }; + parse = /* @__PURE__ */ _parse($ZodRealError); + _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_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, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; + }; + parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); + _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, config()))) + } : { success: true, data: result.value }; + }; + safeParse = /* @__PURE__ */ _safeParse($ZodRealError); + _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_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, config()))) + } : { success: true, data: result.value }; + }; + safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); + _encode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parse(_Err)(schema, value, ctx); + }; + _decode = (_Err) => (schema, value, _ctx) => { + return _parse(_Err)(schema, value, _ctx); + }; + _encodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parseAsync(_Err)(schema, value, ctx); + }; + _decodeAsync = (_Err) => async (schema, value, _ctx) => { + return _parseAsync(_Err)(schema, value, _ctx); + }; + _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); + }; + _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); + }; + _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); + }; + _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js +var regexes_exports = {}; +__export(regexes_exports, { + base64: () => base64, + base64url: () => base64url, + bigint: () => bigint, + boolean: () => boolean, + browserEmail: () => browserEmail, + cidrv4: () => cidrv4, + cidrv6: () => cidrv6, + cuid: () => cuid, + cuid2: () => cuid2, + date: () => date, + datetime: () => datetime, + domain: () => domain, + duration: () => duration, + e164: () => e164, + email: () => email, + emoji: () => emoji, + extendedDuration: () => extendedDuration, + guid: () => guid, + hex: () => hex, + hostname: () => hostname, + html5Email: () => html5Email, + idnEmail: () => idnEmail, + integer: () => integer, + ipv4: () => ipv4, + ipv6: () => ipv6, + ksuid: () => ksuid, + lowercase: () => lowercase, + mac: () => mac, + md5_base64: () => md5_base64, + md5_base64url: () => md5_base64url, + md5_hex: () => md5_hex, + nanoid: () => nanoid, + null: () => _null, + number: () => number, + rfc5322Email: () => rfc5322Email, + sha1_base64: () => sha1_base64, + sha1_base64url: () => sha1_base64url, + sha1_hex: () => sha1_hex, + sha256_base64: () => sha256_base64, + sha256_base64url: () => sha256_base64url, + sha256_hex: () => sha256_hex, + sha384_base64: () => sha384_base64, + sha384_base64url: () => sha384_base64url, + sha384_hex: () => sha384_hex, + sha512_base64: () => sha512_base64, + sha512_base64url: () => sha512_base64url, + sha512_hex: () => sha512_hex, + string: () => string, + time: () => time, + ulid: () => ulid, + undefined: () => _undefined, + unicodeEmail: () => unicodeEmail, + uppercase: () => uppercase, + uuid: () => uuid, + uuid4: () => uuid4, + uuid6: () => uuid6, + uuid7: () => uuid7, + xid: () => xid +}); +function emoji() { + return new RegExp(_emoji, "u"); +} +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}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const time3 = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const timeRegex = `${time3}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; +var init_regexes = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"() { + init_util(); + cuid = /^[cC][^\s-]{8,}$/; + cuid2 = /^[0-9a-z]+$/; + ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; + xid = /^[0-9a-vA-V]{20}$/; + ksuid = /^[A-Za-z0-9]{27}$/; + nanoid = /^[a-zA-Z0-9_-]{21}$/; + duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; + 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)?)??$/; + 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})$/; + uuid = (version2) => { + if (!version2) + 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}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); + }; + uuid4 = /* @__PURE__ */ uuid(4); + uuid6 = /* @__PURE__ */ uuid(6); + uuid7 = /* @__PURE__ */ uuid(7); + email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + 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])?)*$/; + 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,}))$/; + unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; + idnEmail = unicodeEmail; + 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])?)*$/; + _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + 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])$/; + 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}|:))$/; + mac = (delimiter) => { + const escapedDelim = escapeRegex2(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); + }; + 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])$/; + cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; + base64url = /^[A-Za-z0-9_-]*$/; + 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])?)*\.?$/; + domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + e164 = /^\+[1-9]\d{6,14}$/; + 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])))`; + date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); + string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); + }; + bigint = /^-?\d+n?$/; + integer = /^-?\d+$/; + number = /^-?\d+(?:\.\d+)?$/; + boolean = /^(?:true|false)$/i; + _null = /^null$/i; + _undefined = /^undefined$/i; + lowercase = /^[^A-Z]*$/; + uppercase = /^[^a-z]*$/; + hex = /^[0-9a-fA-F]*$/; + md5_hex = /^[0-9a-fA-F]{32}$/; + md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); + md5_base64url = /* @__PURE__ */ fixedBase64url(22); + sha1_hex = /^[0-9a-fA-F]{40}$/; + sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); + sha1_base64url = /* @__PURE__ */ fixedBase64url(27); + sha256_hex = /^[0-9a-fA-F]{64}$/; + sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); + sha256_base64url = /* @__PURE__ */ fixedBase64url(43); + sha384_hex = /^[0-9a-fA-F]{96}$/; + sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); + sha384_base64url = /* @__PURE__ */ fixedBase64url(64); + sha512_hex = /^[0-9a-fA-F]{128}$/; + sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); + sha512_base64url = /* @__PURE__ */ fixedBase64url(86); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues(property, result.issues)); + } +} +var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite; +var init_checks = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js"() { + init_core(); + init_regexes(); + init_util(); + $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { + var _a2; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a2 = inst._zod).onattach ?? (_a2.onattach = []); + }); + numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" + }; + $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._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, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._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, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a2; + (_a2 = inst2._zod.bag).multipleOf ?? (_a2.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" ? 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 + }); + }; + }); + $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + 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((inst2) => { + const bag = inst2._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)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + 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 { + 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 + }); + } + }; + }); + $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._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, + 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 + }); + } + }; + }); + $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { + var _a2; + $ZodCheck.init(inst, def); + (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._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: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { + var _a2; + $ZodCheck.init(inst, def); + (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._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: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a2; + $ZodCheck.init(inst, def); + (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._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: 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 + }); + }; + }); + $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a2; + $ZodCheck.init(inst, def); + (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + 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 + }); + }; + }); + $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a2; + $ZodCheck.init(inst, def); + (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + 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 + }); + }; + }); + $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a2; + $ZodCheck.init(inst, def); + (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + 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 + }); + }; + }); + $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a2, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a2 = inst._zod).check ?? (_a2.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 = () => { + }); + }); + $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 + }); + }; + }); + $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); + }); + $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); + }); + $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex2(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 + }); + }; + }); + $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex2(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 + }); + }; + }); + $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex2(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 = /* @__PURE__ */ $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((result2) => handleCheckPropertyResult(result2, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; + }); + $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst2) => { + inst2._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 + }); + }; + }); + $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; + }); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js +var Doc; +var init_doc = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js"() { + Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; + } + 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 args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F(...args, lines.join("\n")); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js +var version; +var init_versions = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js"() { + version = { + major: 4, + minor: 3, + patch: 6 + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js +function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; + } catch { + return false; + } +} +function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); + return isValidBase64(padded); +} +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + 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; + } +} +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handlePropertyResult(result, final, key, input, isOptionalOut) { + if (result.issues.length) { + if (isOptionalOut && !(key in input)) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (result.value === void 0) { + if (key in input) { + final.value[key] = void 0; + } + } else { + final.value[key] = result.value; + } +} +function normalizeDef(def) { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + 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 isOptionalOut = _catchall.optout === "optional"; + for (const key in input) { + if (keySet.has(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((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalOut); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +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, config()))) + }); + return final; +} +function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r) => r.issues.length === 0); + if (successes.length === 1) { + final.value = successes[0].value; + return final; + } + if (successes.length === 0) { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + } else { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false + }); + } + return final; +} +function mergeValues(a, 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 }; + for (const key of sharedKeys) { + const sharedValue = 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 = 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) { + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + for (const iss of left.issues) { + if (iss.code === "unrecognized_keys") { + unrecIssue ?? (unrecIssue = iss); + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).l = true; + } + } else { + result.issues.push(iss); + } + } + for (const iss of right.issues) { + if (iss.code === "unrecognized_keys") { + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).r = true; + } + } else { + result.issues.push(iss); + } + } + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length && unrecIssue) { + result.issues.push({ ...unrecIssue, keys: bothKeys }); + } + if (aborted(result)) + return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +function handleOptionalResult(result, input) { + if (result.issues.length && input === void 0) { + return { issues: [], value: void 0 }; + } + return result; +} +function handleDefaultResult(payload, def) { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return payload; +} +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + } + return payload; +} +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + 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) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +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(issue(_iss)); + } +} +var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom; +var init_schemas = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js"() { + init_checks(); + init_core(); + init_doc(); + init_parse(); + init_regexes(); + init_util(); + init_versions(); + init_util(); + $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a2; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a2 = inst._zod).deferred ?? (_a2.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + 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; + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, 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") { + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary2) => { + return handleCanaryResult(canary2, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + defineLazy(inst, "~standard", () => ({ + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); + } + }, + vendor: "zod", + version: 1 + })); + }); + $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_2) { + } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); + }); + $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); + }); + $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 === void 0) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); + }); + $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); + }); + $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const trimmed = payload.value.trim(); + const url2 = new URL(trimmed); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url2.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) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (def.normalize) { + payload.value = url2.href; + } else { + payload.value = trimmed; + } + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); + }); + $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); + }); + $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); + }); + $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); + }); + $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); + }); + $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); + }); + $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); + }); + $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; + }); + $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; + }); + $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); + }); + $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const parts = payload.value.split("/"); + try { + if (parts.length !== 2) + throw new Error(); + const [address, prefix] = parts; + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = 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 + }); + }; + }); + $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = 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 + }); + }; + }); + $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); + }); + $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 + }); + }; + }); + $ZodCustomStringFormat = /* @__PURE__ */ $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 + }); + }; + }); + $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) ? "Infinity" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload; + }; + }); + $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); + }); + $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = 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; + }; + }); + $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = 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; + }; + }); + $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); + }); + $ZodSymbol = /* @__PURE__ */ $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; + }; + }); + $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = /* @__PURE__ */ new Set([void 0]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + 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; + }; + }); + $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ 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; + }; + }); + $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $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; + }; + }); + $ZodVoid = /* @__PURE__ */ $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; + }; + }); + $ZodDate = /* @__PURE__ */ $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; + }; + }); + $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + 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 = 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((result2) => handleArrayResult(result2, payload, i))); + } else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; + }); + $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh + }); + return newSh; + } + }); + } + const _normalized = cached(() => normalizeDef(def)); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const isObject3 = isObject; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject3(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const isOptionalOut = el._zod.optout === "optional"; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalOut); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; + }); + $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def)); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {};`); + for (const key of normalized.keys) { + const id = ids[key]; + const k = esc(key); + const schema = shape[key]; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(key)};`); + if (isOptionalOut) { + doc.write(` + if (${id}.issues.length) { + if (${k} in input) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } else { + doc.write(` + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject3 = isObject; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject3(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + 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); + }; + }); + $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return void 0; + }); + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx) => { + if (single) { + 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((results2) => { + return handleUnionResults(results2, payload, inst, ctx); + }); + }; + }); + $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx) => { + if (single) { + 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((results2) => { + return handleExclusiveUnionResults(results2, payload, inst, ctx); + }); + }; + }); + $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = /* @__PURE__ */ new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def.options; + const map2 = /* @__PURE__ */ 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 (map2.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map2.set(v, o); + } + } + return map2; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!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); + } + if (def.unionFallback) { + return _super(payload, ctx); + } + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + input, + path: [def.discriminator], + inst + }); + return payload; + }; + }); + $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(([left2, right2]) => { + return handleIntersectionResults(payload, left2, right2); + }); + } + return handleIntersectionResults(payload, left, right); + }; + }); + $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + 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 = []; + const proms = []; + const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, + input, + inst, + origin: "array" + }); + return payload; + } + } + let i = -1; + for (const item of items) { + i++; + if (i >= input.length) { + if (i >= optStart) + continue; + } + const result = item._zod.run({ + value: input[i], + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + if (def.rest) { + 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((result2) => handleTupleResult(result2, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + 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) { + payload.value = {}; + const recordKeys = /* @__PURE__ */ 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); + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[key] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + 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"); + } + 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") { + payload.value[key] = input[key]; + } else { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + } + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; + }); + $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + 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 = /* @__PURE__ */ 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, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult(keyResult2, valueResult2, 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; + }; + }); + $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + 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 = /* @__PURE__ */ 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((result2) => handleSetResult(result2, payload))); + } else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex2(o) : o.toString()).join("|")})$`); + 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; + }; + }); + $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + if (def.values.length === 0) { + throw new Error("Cannot create literal schema with no valid values"); + } + const values = new Set(def.values); + inst._zod.values = values; + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex2(o) : o ? escapeRegex2(o.toString()) : String(o)).join("|")})$`); + 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; + }; + }); + $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + 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((output2) => { + payload.value = output2; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; + }); + $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) + return result.then((r) => handleOptionalResult(r, payload.value)); + return handleOptionalResult(result, payload.value); + } + if (payload.value === void 0) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { + $ZodOptional.init(inst, def); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def.defaultValue; + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def)); + } + return handleDefaultResult(result, def); + }; + }); + $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); + }; + }); + $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; + }); + $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + 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((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }; + }); + $ZodNaN = /* @__PURE__ */ $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; + }; + }); + $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => 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((right2) => handlePipeResult(right2, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; + }); + $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => 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((left2) => handleCodecAResult(left2, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handleCodecAResult(right2, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; + }); + $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); + defineLazy(inst._zod, "optout", () => 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); + }; + }); + $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + if (!part._zod.pattern) { + 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 || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex2(`${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; + }; + }); + $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + inst._def = def; + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + return 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; + }; + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return 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; + }; + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst + }); + return payload; + } + 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; + }); + $ZodPromise = /* @__PURE__ */ $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)); + }; + }); + $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "innerType", () => def.getter()); + defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); + defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); + defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); + defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; + }); + $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((r2) => handleRefineResult(r2, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; + }); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js +var init_ar = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js +var init_az = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js +var init_be = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js +var init_bg = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js +var init_ca = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js +var init_cs = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js +var init_da = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js +var init_de = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js +function en_default() { + return { + localeError: error() + }; +} +var error; +var init_en = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"() { + init_util(); + 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", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + 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] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } + }; + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js +var init_eo = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js +var init_es = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js +var init_fa = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js +var init_fi = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js +var init_fr = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js +var init_fr_CA = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js +var init_he = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js +var init_hu = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js +var init_hy = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js +var init_id = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js +var init_is = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js +var init_it = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js +var init_ja = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js +var init_ka = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js +var init_km = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js +var init_kh = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"() { + init_km(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js +var init_ko = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js +var init_lt = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js +var init_mk = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js +var init_ms = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js +var init_nl = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js +var init_no = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js +var init_ota = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js +var init_ps = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js +var init_pl = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js +var init_pt = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js +var init_ru = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js +var init_sl = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js +var init_sv = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js +var init_ta = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js +var init_th = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js +var init_tr = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js +var init_uk = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js +var init_ua = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"() { + init_uk(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js +var init_ur = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js +var init_uz = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js +var init_vi = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js +var init_zh_CN = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js +var init_zh_TW = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js +var init_yo = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"() { + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js +var init_locales = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"() { + init_ar(); + init_az(); + init_be(); + init_bg(); + init_ca(); + init_cs(); + init_da(); + init_de(); + init_en(); + init_eo(); + init_es(); + init_fa(); + init_fi(); + init_fr(); + init_fr_CA(); + init_he(); + init_hu(); + init_hy(); + init_id(); + init_is(); + init_it(); + init_ja(); + init_ka(); + init_kh(); + init_km(); + init_ko(); + init_lt(); + init_mk(); + init_ms(); + init_nl(); + init_no(); + init_ota(); + init_ps(); + init_pl(); + init_pt(); + init_ru(); + init_sl(); + init_sv(); + init_ta(); + init_th(); + init_tr(); + init_ua(); + init_uk(); + init_ur(); + init_uz(); + init_vi(); + init_zh_CN(); + init_zh_TW(); + init_yo(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js +function registry() { + return new $ZodRegistry(); +} +var _a, $ZodRegistry, globalRegistry; +var init_registries = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"() { + $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta3 = _meta[0]; + this._map.set(schema, meta3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.set(meta3.id, schema); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta3 = this._map.get(schema); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.delete(meta3.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : void 0; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } + }; + (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); + globalRegistry = globalThis.__zod_globalRegistry; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js +// @__NO_SIDE_EFFECTS__ +function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class2, params) { + return new Class2({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class2, params) { + return new Class2({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class2, params) { + return new Class2({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class2, params) { + return new Class2({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class2, params) { + return new Class2({ + type: "bigint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class2, params) { + return new Class2({ + type: "bigint", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class2, params) { + return new Class2({ + type: "symbol", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _undefined2(Class2, params) { + return new Class2({ + type: "undefined", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class2) { + return new Class2({ + type: "any" + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class2, params) { + return new Class2({ + type: "void", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class2, params) { + return new Class2({ + type: "date", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class2, params) { + return new Class2({ + type: "date", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class2, params) { + return new Class2({ + type: "nan", + ...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 /* @__PURE__ */ _gt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return /* @__PURE__ */ _lt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return /* @__PURE__ */ _lte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return /* @__PURE__ */ _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 $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...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 $ZodCheckProperty({ + check: "property", + property, + schema, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); +} +// @__NO_SIDE_EFFECTS__ +function _trim() { + return /* @__PURE__ */ _overwrite((input) => input.trim()); +} +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +} +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +} +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class2, params) { + return new Class2({ + type: "file", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class2, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _refine(Class2, fn, _params) { + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn) { + const ch = /* @__PURE__ */ _check((payload) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(issue(_issue)); + } + }; + return fn(payload.value, payload); + }); + 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 = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function 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 = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = 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 ?? $ZodCodec; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec2 = 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: codec2, + continue: false + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } else { + return falsyArray[0] || "false"; + } + }), + error: params.error + }); + return codec2; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class2, format, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def = { + ...normalizeParams(_params), + 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 Class2(def); + return inst; +} +var init_api = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"() { + init_checks(); + init_registries(); + init_schemas(); + init_util(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js +function initializeContext(params) { + 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: /* @__PURE__ */ new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? void 0 + }; +} +function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a2; + const def = schema._zod.def; + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + ctx.seen.set(schema, result); + 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) { + if (!result.ref) + result.ref = parent; + process2(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta3 = ctx.metadataRegistry.get(schema); + if (meta3) + Object.assign(result.schema, meta3); + if (ctx.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && result.schema._prefault) + (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault); + delete result.schema._prefault; + const _result = ctx.seen.get(schema); + return _result.schema; +} +function extractDefs(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = /* @__PURE__ */ 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]); + } + } + const makeURI = (entry) => { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema2 = seen.schema; + for (const key in schema2) { + delete schema2[key]; + } + schema2.$ref = ref; + }; + 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("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + continue; + } + } + } +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) + return; + const schema2 = seen.def ?? seen.schema; + const _cached = { ...schema2 }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema2.allOf = schema2.allOf ?? []; + schema2.allOf.push(refSchema); + } else { + Object.assign(schema2, refSchema); + } + Object.assign(schema2, _cached); + const isParentRef = zodSchema._zod.parent === ref; + if (isParentRef) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema2[key]; + } + } + } + if (refSchema.$ref && refSeen.def) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { + delete schema2[key]; + } + } + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema2.$ref = parentSeen.schema.$ref; + if (parentSeen.def) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema2[key]; + } + } + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema2, + path: seen.path ?? [] + }); + }; + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + 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") { + } else { + } + 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); + } + Object.assign(result, root.def ?? root.schema); + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + if (ctx.external) { + } else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + 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: /* @__PURE__ */ 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") { + 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") { + 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; +} +var createToJSONSchemaMethod, createStandardJSONSchemaMethod; +var init_to_json_schema = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"() { + init_registries(); + createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + process2(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); + }; + createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); + process2(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js +function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry2 = input; + const ctx2 = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + for (const entry of registry2._idmap.entries()) { + const [_, schema] = entry; + process2(schema, ctx2); + } + const schemas = {}; + const external = { + registry: registry2, + uri: params?.uri, + defs + }; + ctx2.external = external; + for (const entry of registry2._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx2, schema); + schemas[key] = finalize(ctx2, schema); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const ctx = initializeContext({ ...params, processors: allProcessors }); + process2(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} +var formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors; +var init_json_schema_processors = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"() { + init_to_json_schema(); + init_util(); + formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set + }; + stringProcessor = (schema, ctx, _json, _params) => { + const json2 = _json; + json2.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") + json2.minLength = minimum; + if (typeof maximum === "number") + json2.maxLength = maximum; + if (format) { + json2.format = formatMap[format] ?? format; + if (json2.format === "") + delete json2.format; + if (format === "time") { + delete json2.format; + } + } + if (contentEncoding) + json2.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json2.pattern = regexes[0].source; + else if (regexes.length > 1) { + json2.allOf = [ + ...regexes.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } + }; + numberProcessor = (schema, ctx, _json, _params) => { + const json2 = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json2.type = "integer"; + else + json2.type = "number"; + if (typeof exclusiveMinimum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.minimum = exclusiveMinimum; + json2.exclusiveMinimum = true; + } else { + json2.exclusiveMinimum = exclusiveMinimum; + } + } + if (typeof minimum === "number") { + json2.minimum = minimum; + if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { + if (exclusiveMinimum >= minimum) + delete json2.minimum; + else + delete json2.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.maximum = exclusiveMaximum; + json2.exclusiveMaximum = true; + } else { + json2.exclusiveMaximum = exclusiveMaximum; + } + } + if (typeof maximum === "number") { + json2.maximum = maximum; + if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { + if (exclusiveMaximum <= maximum) + delete json2.maximum; + else + delete json2.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json2.multipleOf = multipleOf; + }; + booleanProcessor = (_schema, _ctx, json2, _params) => { + json2.type = "boolean"; + }; + bigintProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + }; + symbolProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + }; + nullProcessor = (_schema, ctx, json2, _params) => { + if (ctx.target === "openapi-3.0") { + json2.type = "string"; + json2.nullable = true; + json2.enum = [null]; + } else { + json2.type = "null"; + } + }; + undefinedProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } + }; + voidProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + }; + neverProcessor = (_schema, _ctx, json2, _params) => { + json2.not = {}; + }; + anyProcessor = (_schema, _ctx, _json, _params) => { + }; + unknownProcessor = (_schema, _ctx, _json, _params) => { + }; + dateProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + }; + enumProcessor = (schema, _ctx, json2, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + if (values.every((v) => typeof v === "number")) + json2.type = "number"; + if (values.every((v) => typeof v === "string")) + json2.type = "string"; + json2.enum = values; + }; + literalProcessor = (schema, ctx, json2, _params) => { + const def = schema._zod.def; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (ctx.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json2.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.enum = [val]; + } else { + json2.const = val; + } + } else { + if (vals.every((v) => typeof v === "number")) + json2.type = "number"; + if (vals.every((v) => typeof v === "string")) + json2.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json2.type = "boolean"; + if (vals.every((v) => v === null)) + json2.type = "null"; + json2.enum = vals; + } + }; + nanProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + }; + templateLiteralProcessor = (schema, _ctx, json2, _params) => { + const _json = json2; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; + }; + fileProcessor = (schema, _ctx, json2, _params) => { + const _json = json2; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== void 0) + file2.minLength = minimum; + if (maximum !== void 0) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(_json, file2); + } else { + Object.assign(_json, file2); + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); + } + } else { + Object.assign(_json, file2); + } + }; + successProcessor = (_schema, _ctx, json2, _params) => { + json2.type = "boolean"; + }; + customProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + }; + functionProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Function types cannot be represented in JSON Schema"); + } + }; + transformProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + }; + mapProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + }; + setProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + }; + arrayProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + json2.type = "array"; + json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); + }; + objectProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def = schema._zod.def; + json2.type = "object"; + json2.properties = {}; + const shape = def.shape; + for (const key in shape) { + json2.properties[key] = process2(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (ctx.io === "input") { + return v.optin === void 0; + } else { + return v.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json2.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json2.additionalProperties = false; + } else if (!def.catchall) { + if (ctx.io === "output") + json2.additionalProperties = false; + } else if (def.catchall) { + json2.additionalProperties = process2(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + }; + unionProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => process2(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] + })); + if (isExclusive) { + json2.oneOf = options; + } else { + json2.anyOf = options; + } + }; + intersectionProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + const a = process2(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b = process2(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] + ]; + json2.allOf = allOf; + }; + tupleProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def = schema._zod.def; + json2.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) => process2(x, ctx, { + ...params, + path: [...params.path, prefixPath, i] + })); + const rest = def.rest ? process2(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] + }) : null; + if (ctx.target === "draft-2020-12") { + json2.prefixItems = prefixItems; + if (rest) { + json2.items = rest; + } + } else if (ctx.target === "openapi-3.0") { + json2.items = { + anyOf: prefixItems + }; + if (rest) { + json2.items.anyOf.push(rest); + } + json2.minItems = prefixItems.length; + if (!rest) { + json2.maxItems = prefixItems.length; + } + } else { + json2.items = prefixItems; + if (rest) { + json2.additionalItems = rest; + } + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + }; + recordProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def = schema._zod.def; + json2.type = "object"; + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"] + }); + json2.patternProperties = {}; + for (const pattern of patterns) { + json2.patternProperties[pattern.source] = valueSchema; + } + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json2.propertyNames = process2(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + } + json2.additionalProperties = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json2.required = validKeyValues; + } + } + }; + nullableProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + const inner = process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json2.nullable = true; + } else { + json2.anyOf = [inner, { type: "null" }]; + } + }; + nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + }; + defaultProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json2.default = JSON.parse(JSON.stringify(def.defaultValue)); + }; + prefaultProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io === "input") + json2._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + }; + catchProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json2.default = catchValue; + }; + pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; + }; + readonlyProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json2.readOnly = true; + }; + promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + }; + optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + }; + lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; + }; + 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 + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js +var init_json_schema_generator = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"() { + init_json_schema_processors(); + init_to_json_schema(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js +var init_json_schema = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"() { + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js +var init_core2 = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"() { + init_core(); + init_parse(); + init_errors(); + init_schemas(); + init_checks(); + init_versions(); + init_util(); + init_regexes(); + init_locales(); + init_registries(); + init_doc(); + init_api(); + init_to_json_schema(); + init_json_schema_processors(); + init_json_schema_generator(); + init_json_schema(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js +var checks_exports2 = {}; +__export(checks_exports2, { + endsWith: () => _endsWith, + gt: () => _gt, + gte: () => _gte, + includes: () => _includes, + length: () => _length, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + negative: () => _negative, + nonnegative: () => _nonnegative, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + overwrite: () => _overwrite, + positive: () => _positive, + property: () => _property, + regex: () => _regex, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + trim: () => _trim, + uppercase: () => _uppercase +}); +var init_checks2 = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"() { + init_core2(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date2, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date2(params) { + return _isoDate(ZodISODate, params); +} +function time2(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} +var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration; +var init_iso = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"() { + init_core2(); + init_schemas2(); + ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); + }); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js +var initializer2, ZodError, ZodRealError; +var init_errors2 = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"() { + init_core2(); + init_core2(); + init_util(); + initializer2 = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => { + inst.issues.push(issue2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + addIssues: { + value: (issues2) => { + inst.issues.push(...issues2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } + }); + }; + ZodError = $constructor("ZodError", initializer2); + ZodRealError = $constructor("ZodError", initializer2, { + Parent: Error + }); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js +var parse2, parseAsync2, safeParse2, safeParseAsync2, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync; +var init_parse2 = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"() { + init_core2(); + init_errors2(); + parse2 = /* @__PURE__ */ _parse(ZodRealError); + parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); + safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); + safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); + encode = /* @__PURE__ */ _encode(ZodRealError); + decode = /* @__PURE__ */ _decode(ZodRealError); + encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); + decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); + safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); + safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); + safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); + safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js +var schemas_exports2 = {}; +__export(schemas_exports2, { + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodIntersection: () => ZodIntersection, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + codec: () => codec, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + enum: () => _enum, + exactOptional: () => exactOptional, + file: () => file, + float32: () => float32, + float64: () => float64, + function: () => _function, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + ipv4: () => ipv42, + ipv6: () => ipv62, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + literal: () => literal, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + mac: () => mac2, + map: () => map, + meta: () => meta2, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + never: () => never, + nonoptional: () => nonoptional, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + partialRecord: () => partialRecord, + pipe: () => pipe, + prefault: () => prefault, + preprocess: () => preprocess, + promise: () => promise, + readonly: () => readonly, + record: () => record, + refine: () => refine, + set: () => set, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + transform: () => transform, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + url: () => url, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); +function string2(params) { + return _string(ZodString, params); +} +function email2(params) { + return _email(ZodEmail, params); +} +function guid2(params) { + return _guid(ZodGUID, params); +} +function uuid2(params) { + return _uuid(ZodUUID, params); +} +function uuidv4(params) { + return _uuidv4(ZodUUID, params); +} +function uuidv6(params) { + return _uuidv6(ZodUUID, params); +} +function uuidv7(params) { + return _uuidv7(ZodUUID, params); +} +function url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return _url(ZodURL, { + protocol: /^https?$/, + hostname: regexes_exports.domain, + ...util_exports.normalizeParams(params) + }); +} +function emoji2(params) { + return _emoji2(ZodEmoji, params); +} +function nanoid2(params) { + return _nanoid(ZodNanoID, params); +} +function cuid3(params) { + return _cuid(ZodCUID, params); +} +function cuid22(params) { + return _cuid2(ZodCUID2, params); +} +function ulid2(params) { + return _ulid(ZodULID, params); +} +function xid2(params) { + return _xid(ZodXID, params); +} +function ksuid2(params) { + return _ksuid(ZodKSUID, params); +} +function ipv42(params) { + return _ipv4(ZodIPv4, params); +} +function mac2(params) { + return _mac(ZodMAC, params); +} +function ipv62(params) { + return _ipv6(ZodIPv6, params); +} +function cidrv42(params) { + return _cidrv4(ZodCIDRv4, params); +} +function cidrv62(params) { + return _cidrv6(ZodCIDRv6, params); +} +function base642(params) { + return _base64(ZodBase64, params); +} +function base64url2(params) { + return _base64url(ZodBase64URL, params); +} +function e1642(params) { + return _e164(ZodE164, params); +} +function jwt(params) { + return _jwt(ZodJWT, params); +} +function stringFormat(format, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function hostname2(_params) { + return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); +} +function hex2(_params) { + return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); +} +function hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = regexes_exports[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return _stringFormat(ZodCustomStringFormat, format, regex, params); +} +function number2(params) { + return _number(ZodNumber, params); +} +function int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return _float32(ZodNumberFormat, params); +} +function float64(params) { + return _float64(ZodNumberFormat, params); +} +function int32(params) { + return _int32(ZodNumberFormat, params); +} +function uint32(params) { + return _uint32(ZodNumberFormat, params); +} +function boolean2(params) { + return _boolean(ZodBoolean, params); +} +function bigint2(params) { + return _bigint(ZodBigInt, params); +} +function int64(params) { + return _int64(ZodBigIntFormat, params); +} +function uint64(params) { + return _uint64(ZodBigIntFormat, params); +} +function symbol(params) { + return _symbol(ZodSymbol, params); +} +function _undefined3(params) { + return _undefined2(ZodUndefined, params); +} +function _null3(params) { + return _null2(ZodNull, params); +} +function any() { + return _any(ZodAny); +} +function unknown() { + return _unknown(ZodUnknown); +} +function never(params) { + return _never(ZodNever, params); +} +function _void2(params) { + return _void(ZodVoid, params); +} +function date3(params) { + return _date(ZodDate, params); +} +function array(element, params) { + return _array(ZodArray, element, params); +} +function keyof(schema) { + const shape = schema._zod.def.shape; + return _enum(Object.keys(shape)); +} +function object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...util_exports.normalizeParams(params) + }; + return new ZodObject(def); +} +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util_exports.normalizeParams(params) + }); +} +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); +} +function union(options, params) { + return new ZodUnion({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); +} +function xor(options, params) { + return new ZodXor({ + type: "union", + options, + inclusive: false, + ...util_exports.normalizeParams(params) + }); +} +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); +} +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left, + right + }); +} +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items, + rest, + ...util_exports.normalizeParams(params) + }); +} +function record(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function partialRecord(keyType, valueType, params) { + const k = clone(keyType); + k._zod.values = void 0; + return new ZodRecord({ + type: "record", + keyType: k, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType, + mode: "loose", + ...util_exports.normalizeParams(params) + }); +} +function map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function set(valueType, params) { + return new ZodSet({ + type: "set", + valueType, + ...util_exports.normalizeParams(params) + }); +} +function _enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); +} +function file(params) { + return _file(ZodFile, params); +} +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType + }); +} +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType + }); +} +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType + }); +} +function nullish2(innerType) { + return optional(nullable(innerType)); +} +function _default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); +} +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType + }); +} +function _catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +function nan(params) { + return _nan(ZodNaN, params); +} +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); +} +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out, + transform: params.decode, + reverseTransform: params.encode + }); +} +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType + }); +} +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util_exports.normalizeParams(params) + }); +} +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter + }); +} +function promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType + }); +} +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), + output: params?.output ?? unknown() + }); +} +function check(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +function superRefine(fn) { + return _superRefine(fn); +} +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util_exports.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + 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; +} +function json(params) { + const jsonSchema = lazy(() => { + return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); + }); + return jsonSchema; +} +function preprocess(fn, schema) { + return pipe(transform(fn), schema); +} +var ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodXor, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodCodec, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodFunction, ZodCustom, describe2, meta2, stringbool; +var init_schemas2 = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"() { + init_core2(); + init_core2(); + init_json_schema_processors(); + init_to_json_schema(); + init_checks2(); + init_iso(); + init_parse2(); + ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + Object.assign(inst["~standard"], { + jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output") + } + }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); + inst.def = def; + inst.type = def.type; + Object.defineProperty(inst, "_def", { value: def }); + inst.check = (...checks) => { + return inst.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { + parent: true + }); + }; + inst.with = inst.check; + inst.clone = (def2, params) => clone(inst, def2, params); + inst.brand = () => inst; + inst.register = ((reg, meta3) => { + reg.add(inst, meta3); + return inst; + }); + inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse2(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.encode = (data, params) => encode(inst, data, params); + inst.decode = (data, params) => decode(inst, data, params); + inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params); + inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params); + inst.safeEncode = (data, params) => safeEncode(inst, data, params); + inst.safeDecode = (data, params) => safeDecode(inst, data, params); + inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params); + inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params); + inst.refine = (check3, params) => inst.check(refine(check3, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite(fn)); + inst.optional = () => optional(inst); + inst.exactOptional = () => exactOptional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union([inst, arg]); + inst.and = (arg) => intersection(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx)); + inst.default = (def2) => _default(inst, def2); + inst.prefault = (def2) => prefault(inst, def2); + inst.catch = (params) => _catch(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry.get(inst); + } + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }; + inst.isOptional = () => inst.safeParse(void 0).success; + inst.isNullable = () => inst.safeParse(null).success; + inst.apply = (fn) => fn(inst); + return inst; + }); + _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args) => inst.check(_regex(...args)); + inst.includes = (...args) => inst.check(_includes(...args)); + inst.startsWith = (...args) => inst.check(_startsWith(...args)); + inst.endsWith = (...args) => inst.check(_endsWith(...args)); + inst.min = (...args) => inst.check(_minLength(...args)); + inst.max = (...args) => inst.check(_maxLength(...args)); + inst.length = (...args) => inst.check(_length(...args)); + inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase(params)); + inst.uppercase = (params) => inst.check(_uppercase(params)); + inst.trim = () => inst.check(_trim()); + inst.normalize = (...args) => inst.check(_normalize(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase()); + inst.toUpperCase = () => inst.check(_toUpperCase()); + inst.slugify = () => inst.check(_slugify()); + }); + ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime2(params)); + inst.date = (params) => inst.check(date2(params)); + inst.time = (params) => inst.check(time2(params)); + inst.duration = (params) => inst.check(duration2(params)); + }); + ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); + }); + ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { + $ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(_gt(0, params)); + inst.nonnegative = (params) => inst.check(_gte(0, params)); + inst.negative = (params) => inst.check(_lt(0, params)); + inst.nonpositive = (params) => inst.check(_lte(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + inst.step = (value, params) => inst.check(_multipleOf(value, params)); + inst.finite = () => inst; + 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; + }); + ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); + }); + ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); + }); + ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; + }); + ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); + }); + ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { + $ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); + }); + ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { + $ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); + }); + ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); + }); + ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); + }); + ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); + }); + ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); + }); + ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { + $ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); + }); + ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_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; + }); + ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(_length(len, params)); + inst.unwrap = () => inst.element; + }); + ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); + util_exports.defineLazy(inst, "shape", () => { + return def.shape; + }); + inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); + inst.extend = (incoming) => { + return util_exports.extend(inst, incoming); + }; + inst.safeExtend = (incoming) => { + return util_exports.safeExtend(inst, incoming); + }; + inst.merge = (other) => util_exports.merge(inst, other); + inst.pick = (mask) => util_exports.pick(inst, mask); + inst.omit = (mask) => util_exports.omit(inst, mask); + inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); + inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); + }); + ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); + inst.options = def.options; + }); + ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + $ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); + inst.options = def.options; + }); + ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); + }); + ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); + }); + ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); + }); + ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + $ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); + }); + ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + $ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); + }); + ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, 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: [], + ...util_exports.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: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + }); + ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, 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]; + } + }); + }); + ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { + $ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); + inst.min = (size, params) => inst.check(_minSize(size, params)); + inst.max = (size, params) => inst.check(_maxSize(size, params)); + inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); + }); + ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + payload.issues.push(util_exports.issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + payload.value = output; + return payload; + }; + }); + ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; + }); + ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { + $ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; + }); + ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { + $ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); + }); + ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); + inst.in = def.in; + inst.out = def.out; + }); + ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + $ZodCodec.init(inst, def); + }); + ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); + }); + ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.getter(); + }); + ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { + $ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { + $ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); + }); + ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); + }); + describe2 = describe; + meta2 = meta; + stringbool = (...args) => _stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString + }, ...args); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js +var ZodIssueCode, ZodFirstPartyTypeKind; +var init_compat = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"() { + init_core2(); + init_core2(); + 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" + }; + /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { + })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js +var z; +var init_from_json_schema = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"() { + init_registries(); + init_checks2(); + init_iso(); + init_schemas2(); + z = { + ...schemas_exports2, + ...checks_exports2, + iso: iso_exports + }; + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js +var coerce_exports = {}; +__export(coerce_exports, { + bigint: () => bigint3, + boolean: () => boolean3, + date: () => date4, + number: () => number3, + string: () => string3 +}); +function string3(params) { + return _coercedString(ZodString, params); +} +function number3(params) { + return _coercedNumber(ZodNumber, params); +} +function boolean3(params) { + return _coercedBoolean(ZodBoolean, params); +} +function bigint3(params) { + return _coercedBigint(ZodBigInt, params); +} +function date4(params) { + return _coercedDate(ZodDate, params); +} +var init_coerce = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"() { + init_core2(); + init_schemas2(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js +var init_external = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"() { + init_core2(); + init_schemas2(); + init_checks2(); + init_errors2(); + init_parse2(); + init_compat(); + init_core2(); + init_en(); + init_core2(); + init_json_schema_processors(); + init_from_json_schema(); + init_locales(); + init_iso(); + init_iso(); + init_coerce(); + config(en_default()); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js +var init_classic = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js"() { + init_external(); + init_external(); + } +}); + +// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/index.js +var init_v4 = __esm({ + "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/index.js"() { + init_classic(); + init_classic(); + } +}); + +// ../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs +var LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, PROTOCOL_VERSION_META_KEY, CLIENT_INFO_META_KEY, SERVER_INFO_META_KEY, CLIENT_CAPABILITIES_META_KEY, SUBSCRIPTION_ID_META_KEY, LOG_LEVEL_META_KEY, TRACEPARENT_META_KEY, TRACESTATE_META_KEY, BAGGAGE_META_KEY, JSONRPC_VERSION, PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR, JSONValueSchema, JSONObjectSchema, JSONArraySchema, ProgressTokenSchema, CursorSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultMetaObjectSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, DiscoverRequestSchema, DiscoverResultSchema, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, SubscriptionFilterSchema, SubscriptionsListenRequestParamsSchema, SubscriptionsListenRequestSchema, SubscriptionsAcknowledgedNotificationParamsSchema, SubscriptionsAcknowledgedNotificationSchema, SubscriptionsListenResultMetaSchema, SubscriptionsListenResultSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, TaskCreationParamsSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, SafeUrlSchema, OAuthProtectedResourceMetadataSchema, OAuthMetadataSchema, OpenIdProviderMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, OAuthTokensSchema, IdJagTokenExchangeResponseSchema, OAuthErrorResponseSchema, OptionalSafeUrlSchema, OAuthClientMetadataSchema, OAuthClientInformationSchema, OAuthClientInformationFullSchema, OAuthClientRegistrationErrorSchema, OAuthTokenRevocationRequestSchema; +var init_auth_CUe6YdwF = __esm({ + "../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs"() { + init_v4(); + LATEST_PROTOCOL_VERSION = "2025-11-25"; + DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; + SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" + ]; + RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; + PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; + CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; + SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; + CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; + SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; + LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; + TRACEPARENT_META_KEY = "traceparent"; + TRACESTATE_META_KEY = "tracestate"; + BAGGAGE_META_KEY = "baggage"; + JSONRPC_VERSION = "2.0"; + PARSE_ERROR = -32700; + INVALID_REQUEST = -32600; + METHOD_NOT_FOUND = -32601; + INVALID_PARAMS = -32602; + INTERNAL_ERROR = -32603; + JSONValueSchema = lazy(() => union([ + string2(), + number2(), + boolean2(), + _null3(), + record(string2(), JSONValueSchema), + array(JSONValueSchema) + ])); + JSONObjectSchema = record(string2(), JSONValueSchema); + JSONArraySchema = array(JSONValueSchema); + ProgressTokenSchema = union([string2(), number2().int()]); + CursorSchema = string2(); + TaskMetadataSchema = object({ ttl: number2().optional() }); + RelatedTaskMetadataSchema = object({ taskId: string2() }); + RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() + }); + BaseRequestParamsSchema = object({ _meta: RequestMetaSchema.optional() }); + TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); + RequestSchema = object({ + method: string2(), + params: BaseRequestParamsSchema.loose().optional() + }); + NotificationsParamsSchema = object({ _meta: RequestMetaSchema.optional() }); + NotificationSchema = object({ + method: string2(), + params: NotificationsParamsSchema.loose().optional() + }); + ResultMetaObjectSchema = looseObject({ get [SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); + } }); + ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); + RequestIdSchema = union([string2(), number2().int()]); + JSONRPCRequestSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape + }).strict(); + JSONRPCNotificationSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape + }).strict(); + JSONRPCResultResponseSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema + }).strict(); + JSONRPCErrorResponseSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: object({ + code: number2().int(), + message: string2(), + data: unknown().optional() + }) + }).strict(); + JSONRPCMessageSchema = union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema + ]); + JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); + EmptyResultSchema = ResultSchema.strict(); + CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: string2().optional() + }); + CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema + }); + IconSchema = object({ + src: string2(), + mimeType: string2().optional(), + sizes: array(string2()).optional(), + theme: _enum(["light", "dark"]).optional() + }); + IconsSchema = object({ icons: array(IconSchema).optional() }); + BaseMetadataSchema = object({ + name: string2(), + title: string2().optional() + }); + ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: string2(), + websiteUrl: string2().optional(), + description: string2().optional() + }); + FormElicitationCapabilitySchema = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema); + ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() + }), JSONObjectSchema.optional())); + ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() + }); + ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() + }); + ClientCapabilitiesSchema = object({ + experimental: record(string2(), JSONObjectSchema).optional(), + sampling: object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: object({ listChanged: boolean2().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: record(string2(), JSONObjectSchema).optional() + }); + InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: string2(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema + }); + InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema + }); + ServerCapabilitiesSchema = object({ + experimental: record(string2(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: object({ listChanged: boolean2().optional() }).optional(), + resources: object({ + subscribe: boolean2().optional(), + listChanged: boolean2().optional() + }).optional(), + tools: object({ listChanged: boolean2().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: record(string2(), JSONObjectSchema).optional() + }); + InitializeResultSchema = ResultSchema.extend({ + protocolVersion: string2(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: string2().optional() + }); + InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() + }); + DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() + }); + DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: array(string2()), + capabilities: ServerCapabilitiesSchema, + instructions: string2().optional() + }); + PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() + }); + ProgressSchema = object({ + progress: number2(), + total: optional(number2()), + message: optional(string2()) + }); + ProgressNotificationParamsSchema = object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema + }); + ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema + }); + PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); + PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); + PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); + ResourceContentsSchema = object({ + uri: string2(), + mimeType: optional(string2()), + _meta: record(string2(), unknown()).optional() + }); + TextResourceContentsSchema = ResourceContentsSchema.extend({ text: string2() }); + Base64Schema = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: Base64Schema }); + RoleSchema = _enum(["user", "assistant"]); + AnnotationsSchema = object({ + audience: array(RoleSchema).optional(), + priority: number2().min(0).max(1).optional(), + lastModified: iso_exports.datetime({ offset: true }).optional() + }); + ResourceSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: string2(), + description: optional(string2()), + mimeType: optional(string2()), + size: optional(number2()), + annotations: AnnotationsSchema.optional(), + _meta: optional(looseObject({})) + }); + ResourceTemplateSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: string2(), + description: optional(string2()), + mimeType: optional(string2()), + annotations: AnnotationsSchema.optional(), + _meta: optional(looseObject({})) + }); + ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); + ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); + ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); + ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); + ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: string2() }); + ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; + ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema + }); + ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); + ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() + }); + SubscribeRequestParamsSchema = ResourceRequestParamsSchema; + SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema + }); + UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; + UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema + }); + SubscriptionFilterSchema = object({ + toolsListChanged: boolean2().optional(), + promptsListChanged: boolean2().optional(), + resourcesListChanged: boolean2().optional(), + resourceSubscriptions: array(string2()).optional() + }); + SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); + SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema + }); + SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); + SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema + }); + SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); + SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); + ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: string2() }); + ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema + }); + PromptArgumentSchema = object({ + name: string2(), + description: optional(string2()), + required: optional(boolean2()) + }); + PromptSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: optional(string2()), + arguments: optional(array(PromptArgumentSchema)), + _meta: optional(looseObject({})) + }); + ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); + ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); + GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: string2(), + arguments: record(string2(), string2()).optional() + }); + GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema + }); + TextContentSchema = object({ + type: literal("text"), + text: string2(), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() + }); + ImageContentSchema = object({ + type: literal("image"), + data: Base64Schema, + mimeType: string2(), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() + }); + AudioContentSchema = object({ + type: literal("audio"), + data: Base64Schema, + mimeType: string2(), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() + }); + ToolUseContentSchema = object({ + type: literal("tool_use"), + name: string2(), + id: string2(), + input: record(string2(), unknown()), + _meta: record(string2(), unknown()).optional() + }); + EmbeddedResourceSchema = object({ + type: literal("resource"), + resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() + }); + ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); + ContentBlockSchema = union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema + ]); + PromptMessageSchema = object({ + role: RoleSchema, + content: ContentBlockSchema + }); + GetPromptResultSchema = ResultSchema.extend({ + description: string2().optional(), + messages: array(PromptMessageSchema) + }); + PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() + }); + ToolAnnotationsSchema = object({ + title: string2().optional(), + readOnlyHint: boolean2().optional(), + destructiveHint: boolean2().optional(), + idempotentHint: boolean2().optional(), + openWorldHint: boolean2().optional() + }); + ToolExecutionSchema = object({ taskSupport: _enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + ToolSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: string2().optional(), + inputSchema: object({ + type: literal("object"), + properties: record(string2(), JSONValueSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: string2().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: record(string2(), unknown()).optional() + }); + ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); + ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); + CallToolResultSchema = ResultSchema.extend({ + content: array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: boolean2().optional() + }); + CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); + CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + name: string2(), + arguments: record(string2(), unknown()).optional() + }); + CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema + }); + ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() + }); + ListChangedOptionsBaseSchema = object({ + autoRefresh: boolean2().default(true), + debounceMs: number2().int().nonnegative().default(300) + }); + LoggingLevelSchema = _enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); + SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema + }); + LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: string2().optional(), + data: unknown() + }); + LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema + }); + ModelHintSchema = object({ name: string2().optional() }); + ModelPreferencesSchema = object({ + hints: array(ModelHintSchema).optional(), + costPriority: number2().min(0).max(1).optional(), + speedPriority: number2().min(0).max(1).optional(), + intelligencePriority: number2().min(0).max(1).optional() + }); + ToolChoiceSchema = object({ mode: _enum([ + "auto", + "required", + "none" + ]).optional() }); + ToolResultContentSchema = object({ + type: literal("tool_result"), + toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: boolean2().optional(), + _meta: record(string2(), unknown()).optional() + }); + SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema + ]); + SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema + ]); + SamplingMessageSchema = object({ + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), + _meta: record(string2(), unknown()).optional() + }); + CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: string2().optional(), + includeContext: _enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: number2().optional(), + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + metadata: JSONObjectSchema.optional(), + tools: array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() + }); + CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema + }); + CreateMessageResultSchema = ResultSchema.extend({ + model: string2(), + stopReason: optional(_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(string2())), + role: RoleSchema, + content: SamplingContentSchema + }); + CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: string2(), + stopReason: optional(_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(string2())), + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) + }); + BooleanSchemaSchema = object({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() + }); + StringSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: string2().optional() + }); + NumberSchemaSchema = object({ + type: _enum(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() + }); + UntitledSingleSelectEnumSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() + }); + TitledSingleSelectEnumSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object({ + const: string2(), + title: string2() + })), + default: string2().optional() + }); + LegacyTitledEnumSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() + }); + SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); + UntitledMultiSelectEnumSchemaSchema = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() + }); + TitledMultiSelectEnumSchemaSchema = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ anyOf: array(object({ + const: string2(), + title: string2() + })) }), + default: array(string2()).optional() + }); + MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); + EnumSchemaSchema = union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema + ]); + PrimitiveSchemaDefinitionSchema = union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema + ]); + ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: string2(), + requestedSchema: object({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema), + required: array(string2()).optional() + }).catchall(unknown()) + }); + ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: string2(), + elicitationId: string2(), + url: string2().url() + }); + ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); + ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema + }); + ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: string2() }); + ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema + }); + ElicitResultSchema = ResultSchema.extend({ + action: _enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([ + string2(), + number2(), + boolean2(), + array(string2()) + ])).optional()) + }); + ResourceTemplateReferenceSchema = object({ + type: literal("ref/resource"), + uri: string2() + }); + PromptReferenceSchema = object({ + type: literal("ref/prompt"), + name: string2() + }); + CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: object({ + name: string2(), + value: string2() + }), + context: object({ arguments: record(string2(), string2()).optional() }).optional() + }); + CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema + }); + CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: array(string2()).max(100), + total: optional(number2().int()), + hasMore: optional(boolean2()) + }) }); + RootSchema = object({ + uri: string2().startsWith("file://"), + name: string2().optional(), + _meta: record(string2(), unknown()).optional() + }); + ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() + }); + ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); + RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() + }); + TaskCreationParamsSchema = looseObject({ + ttl: number2().optional(), + pollInterval: number2().optional() + }); + TaskStatusSchema = _enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + TaskSchema = object({ + taskId: string2(), + status: TaskStatusSchema, + ttl: union([number2(), _null3()]), + createdAt: string2(), + lastUpdatedAt: string2(), + pollInterval: optional(number2()), + statusMessage: optional(string2()) + }); + CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); + TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); + TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema + }); + GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: string2() }) + }); + GetTaskResultSchema = ResultSchema.merge(TaskSchema); + GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: string2() }) + }); + GetTaskPayloadResultSchema = ResultSchema.loose(); + ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); + ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); + CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: string2() }) + }); + CancelTaskResultSchema = ResultSchema.merge(TaskSchema); + ClientRequestSchema = union([ + PingRequestSchema, + InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema + ]); + ClientNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema + ]); + ClientResultSchema = union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema + ]); + ServerRequestSchema = union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema + ]); + ServerNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema + ]); + ServerResultSchema = union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema + ]); + SafeUrlSchema = url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } + }).refine((url2) => { + const u = new URL(url2); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; + }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); + OAuthProtectedResourceMetadataSchema = looseObject({ + resource: string2().url(), + authorization_servers: array(SafeUrlSchema).optional(), + jwks_uri: string2().url().optional(), + scopes_supported: array(string2()).optional(), + bearer_methods_supported: array(string2()).optional(), + resource_signing_alg_values_supported: array(string2()).optional(), + resource_name: string2().optional(), + resource_documentation: string2().optional(), + resource_policy_uri: string2().url().optional(), + resource_tos_uri: string2().url().optional(), + tls_client_certificate_bound_access_tokens: boolean2().optional(), + authorization_details_types_supported: array(string2()).optional(), + dpop_signing_alg_values_supported: array(string2()).optional(), + dpop_bound_access_tokens_required: boolean2().optional() + }); + OAuthMetadataSchema = looseObject({ + issuer: string2(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string2()).optional(), + response_types_supported: array(string2()), + response_modes_supported: array(string2()).optional(), + grant_types_supported: array(string2()).optional(), + token_endpoint_auth_methods_supported: array(string2()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: array(string2()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + introspection_endpoint: string2().optional(), + introspection_endpoint_auth_methods_supported: array(string2()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + code_challenge_methods_supported: array(string2()).optional(), + client_id_metadata_document_supported: boolean2().optional(), + authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0) + }); + OpenIdProviderMetadataSchema = looseObject({ + issuer: string2(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string2()).optional(), + response_types_supported: array(string2()), + response_modes_supported: array(string2()).optional(), + grant_types_supported: array(string2()).optional(), + acr_values_supported: array(string2()).optional(), + subject_types_supported: array(string2()), + id_token_signing_alg_values_supported: array(string2()), + id_token_encryption_alg_values_supported: array(string2()).optional(), + id_token_encryption_enc_values_supported: array(string2()).optional(), + userinfo_signing_alg_values_supported: array(string2()).optional(), + userinfo_encryption_alg_values_supported: array(string2()).optional(), + userinfo_encryption_enc_values_supported: array(string2()).optional(), + request_object_signing_alg_values_supported: array(string2()).optional(), + request_object_encryption_alg_values_supported: array(string2()).optional(), + request_object_encryption_enc_values_supported: array(string2()).optional(), + token_endpoint_auth_methods_supported: array(string2()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + display_values_supported: array(string2()).optional(), + claim_types_supported: array(string2()).optional(), + claims_supported: array(string2()).optional(), + service_documentation: string2().optional(), + claims_locales_supported: array(string2()).optional(), + ui_locales_supported: array(string2()).optional(), + claims_parameter_supported: boolean2().optional(), + request_parameter_supported: boolean2().optional(), + request_uri_parameter_supported: boolean2().optional(), + require_request_uri_registration: boolean2().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: boolean2().optional(), + authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0) + }); + OpenIdProviderDiscoveryMetadataSchema = object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape + }); + OAuthTokensSchema = object({ + access_token: string2(), + id_token: string2().optional(), + token_type: string2(), + expires_in: coerce_exports.number().optional(), + scope: string2().optional(), + refresh_token: string2().optional() + }).strip(); + IdJagTokenExchangeResponseSchema = object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: string2(), + token_type: string2().optional(), + expires_in: number2().optional(), + scope: string2().optional() + }).strip(); + OAuthErrorResponseSchema = object({ + error: string2(), + error_description: string2().optional(), + error_uri: string2().optional() + }); + OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); + OAuthClientMetadataSchema = object({ + redirect_uris: array(SafeUrlSchema), + token_endpoint_auth_method: string2().optional(), + grant_types: array(string2()).optional(), + response_types: array(string2()).optional(), + application_type: string2().optional(), + client_name: string2().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: string2().optional(), + contacts: array(string2()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: string2().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: string2().optional(), + software_version: string2().optional(), + software_statement: string2().optional() + }).strip(); + OAuthClientInformationSchema = object({ + client_id: string2(), + client_secret: string2().optional(), + client_id_issued_at: number2().optional(), + client_secret_expires_at: number2().optional() + }).strip(); + OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); + OAuthClientRegistrationErrorSchema = object({ + error: string2(), + error_description: string2().optional() + }).strip(); + OAuthTokenRevocationRequestSchema = object({ + token: string2(), + token_type_hint: string2().optional() + }).strip(); + } +}); + +// ../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/internal.mjs +var init_internal = __esm({ + "../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/internal.mjs"() { + init_auth_CUe6YdwF(); + } +}); + +// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/src-CgOncMok.mjs +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 + }); +} +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); +} +function resourceUrlFromServerUrl(url2) { + const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href); + resourceURL.hash = ""; + return resourceURL; +} +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); +} +function isModernProtocolVersion(version2) { + return version2 >= FIRST_MODERN_PROTOCOL_VERSION; +} +function legacyProtocolVersions(versions) { + return versions.filter((version2) => !isModernProtocolVersion(version2)); +} +function modernProtocolVersions(versions) { + return versions.filter((version2) => isModernProtocolVersion(version2)); +} +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) + }] + }; +} +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: [] + }; +} +function build$1() { + const JSONValueSchema$1 = lazy(() => union([ + string2(), + number2(), + boolean2(), + _null3(), + record(string2(), JSONValueSchema$1), + array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = record(string2(), JSONValueSchema$1); + const ProgressTokenSchema$1 = union([string2(), number2().int()]); + const CursorSchema$1 = string2(); + const TaskMetadataSchema$1 = object({ ttl: number2().optional() }); + const RelatedTaskMetadataSchema$1 = object({ taskId: string2() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = object({ + method: string2(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = object({ + method: string2(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + const RequestIdSchema$1 = union([string2(), number2().int()]); + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: string2().optional() + }); + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const IconSchema$1 = object({ + src: string2(), + mimeType: string2().optional(), + sizes: array(string2()).optional(), + theme: _enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = object({ icons: array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = object({ + name: string2(), + title: string2().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: string2(), + websiteUrl: string2().optional(), + description: string2().optional() + }); + const FormElicitationCapabilitySchema2 = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema2 = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(object({ + form: FormElicitationCapabilitySchema2.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + 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() + }); + 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 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + sampling: object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema2.optional(), + roots: object({ listChanged: boolean2().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: string2(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + const ServerCapabilitiesSchema$1 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: object({ listChanged: boolean2().optional() }).optional(), + resources: object({ + subscribe: boolean2().optional(), + listChanged: boolean2().optional() + }).optional(), + tools: object({ listChanged: boolean2().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: string2(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: string2().optional() + }); + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = object({ + progress: number2(), + total: optional(number2()), + message: optional(string2()) + }); + const ProgressNotificationParamsSchema$1 = object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + 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() }); + const ResourceContentsSchema$1 = object({ + uri: string2(), + mimeType: optional(string2()), + _meta: record(string2(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: string2() }); + const Base64Schema2 = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema2 }); + const RoleSchema$1 = _enum(["user", "assistant"]); + const AnnotationsSchema$1 = object({ + audience: array(RoleSchema$1).optional(), + priority: number2().min(0).max(1).optional(), + lastModified: iso_exports.datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: string2(), + description: optional(string2()), + mimeType: optional(string2()), + size: optional(number2()), + annotations: AnnotationsSchema$1.optional(), + _meta: optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: string2(), + description: optional(string2()), + mimeType: optional(string2()), + annotations: AnnotationsSchema$1.optional(), + _meta: optional(looseObject({})) + }); + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: array(ResourceSchema$1) }); + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: string2() }); + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: string2() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = object({ + name: string2(), + description: optional(string2()), + required: optional(boolean2()) + }); + const PromptSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: optional(string2()), + arguments: optional(array(PromptArgumentSchema$1)), + _meta: optional(looseObject({})) + }); + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: array(PromptSchema$1) }); + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: string2(), + arguments: record(string2(), string2()).optional() + }); + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + const TextContentSchema$1 = object({ + type: literal("text"), + text: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ImageContentSchema$1 = object({ + type: literal("image"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const AudioContentSchema$1 = object({ + type: literal("audio"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ToolUseContentSchema$1 = object({ + type: literal("tool_use"), + name: string2(), + id: string2(), + input: record(string2(), unknown()), + _meta: record(string2(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = object({ + type: literal("resource"), + resource: union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: string2().optional(), + messages: array(PromptMessageSchema$1) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ToolAnnotationsSchema$1 = object({ + title: string2().optional(), + readOnlyHint: boolean2().optional(), + destructiveHint: boolean2().optional(), + idempotentHint: boolean2().optional(), + openWorldHint: boolean2().optional() + }); + const ToolExecutionSchema$1 = object({ taskSupport: _enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + const ToolSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: string2().optional(), + inputSchema: object({ + type: literal("object"), + properties: record(string2(), JSONValueSchema$1).optional(), + required: array(string2()).optional() + }).catchall(unknown()), + outputSchema: object({ + type: literal("object"), + properties: record(string2(), JSONValueSchema$1).optional(), + required: array(string2()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: array(ToolSchema$1) }); + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: array(ContentBlockSchema$1), + structuredContent: record(string2(), unknown()).optional(), + isError: boolean2().optional() + }); + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: string2(), + arguments: record(string2(), unknown()).optional() + }); + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const LoggingLevelSchema$1 = _enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: string2().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ModelHintSchema$1 = object({ name: string2().optional() }); + const ModelPreferencesSchema$1 = object({ + hints: array(ModelHintSchema$1).optional(), + costPriority: number2().min(0).max(1).optional(), + speedPriority: number2().min(0).max(1).optional(), + intelligencePriority: number2().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = object({ mode: _enum([ + "auto", + "required", + "none" + ]).optional() }); + const ToolResultContentSchema$1 = object({ + type: literal("tool_result"), + toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema$1), + structuredContent: object({}).loose().optional(), + isError: boolean2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + const SamplingMessageSchema$1 = object({ + role: RoleSchema$1, + content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]), + _meta: record(string2(), unknown()).optional() + }); + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: string2().optional(), + includeContext: _enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: number2().optional(), + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: string2(), + stopReason: optional(_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(string2())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: string2(), + stopReason: optional(_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(string2())), + role: RoleSchema$1, + content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]) + }); + const BooleanSchemaSchema$1 = object({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() + }); + const StringSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: string2().optional() + }); + const NumberSchemaSchema$1 = object({ + type: _enum(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object({ + const: string2(), + title: string2() + })), + default: string2().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() + }); + const SingleSelectEnumSchemaSchema$1 = union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ anyOf: array(object({ + const: string2(), + title: string2() + })) }), + default: array(string2()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: string2(), + requestedSchema: object({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema$1), + required: array(string2()).optional() + }).catchall(unknown()) + }); + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: string2(), + elicitationId: string2(), + url: string2().url() + }); + const ElicitRequestParamsSchema$1 = union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: string2() }); + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: _enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([ + string2(), + number2(), + boolean2(), + array(string2()) + ])).optional()) + }); + const ResourceTemplateReferenceSchema$1 = object({ + type: literal("ref/resource"), + uri: string2() + }); + const PromptReferenceSchema$1 = object({ + type: literal("ref/prompt"), + name: string2() + }); + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: object({ + name: string2(), + value: string2() + }), + context: object({ arguments: record(string2(), string2()).optional() }).optional() + }); + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: array(string2()).max(100), + total: optional(number2().int()), + hasMore: optional(boolean2()) + }) }); + const RootSchema$1 = object({ + uri: string2().startsWith("file://"), + name: string2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: array(RootSchema$1) }); + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TaskCreationParamsSchema$1 = looseObject({ + ttl: number2().optional(), + pollInterval: number2().optional() + }); + const TaskStatusSchema$1 = _enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + const TaskSchema$1 = object({ + taskId: string2(), + status: TaskStatusSchema$1, + ttl: union([number2(), _null3()]), + createdAt: string2(), + lastUpdatedAt: string2(), + pollInterval: optional(number2()), + statusMessage: optional(string2()) + }); + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) + }); + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) + }); + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: array(TaskSchema$1) }); + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) + }); + 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: 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: union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: 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}' \u2014 another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +function buildSchemas2025() { + return memo$1 ??= build$1(); +} +function isNonObjectJsonSchemaRoot(json2) { + return json2["type"] !== "object"; +} +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (natural["$id"] !== void 0) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + 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 && node["$id"] !== void 0) return node; + const out = {}; + 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 (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); + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} +function registryMaps() { + if (maps$1) return maps$1; + const s3 = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s3.PingRequestSchema, + initialize: s3.InitializeRequestSchema, + "completion/complete": s3.CompleteRequestSchema, + "logging/setLevel": s3.SetLevelRequestSchema, + "prompts/get": s3.GetPromptRequestSchema, + "prompts/list": s3.ListPromptsRequestSchema, + "resources/list": s3.ListResourcesRequestSchema, + "resources/templates/list": s3.ListResourceTemplatesRequestSchema, + "resources/read": s3.ReadResourceRequestSchema, + "resources/subscribe": s3.SubscribeRequestSchema, + "resources/unsubscribe": s3.UnsubscribeRequestSchema, + "tools/call": s3.CallToolRequestSchema, + "tools/list": s3.ListToolsRequestSchema, + "tasks/get": s3.GetTaskRequestSchema, + "tasks/result": s3.GetTaskPayloadRequestSchema, + "tasks/list": s3.ListTasksRequestSchema, + "tasks/cancel": s3.CancelTaskRequestSchema, + "sampling/createMessage": s3.CreateMessageRequestSchema, + "elicitation/create": s3.ElicitRequestSchema, + "roots/list": s3.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s3.CancelledNotificationSchema, + "notifications/progress": s3.ProgressNotificationSchema, + "notifications/initialized": s3.InitializedNotificationSchema, + "notifications/roots/list_changed": s3.RootsListChangedNotificationSchema, + "notifications/tasks/status": s3.TaskStatusNotificationSchema, + "notifications/message": s3.LoggingMessageNotificationSchema, + "notifications/resources/updated": s3.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s3.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s3.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s3.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s3.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s3.EmptyResultSchema, + initialize: s3.InitializeResultSchema, + "completion/complete": s3.CompleteResultSchema, + "logging/setLevel": s3.EmptyResultSchema, + "prompts/get": s3.GetPromptResultSchema, + "prompts/list": s3.ListPromptsResultSchema, + "resources/list": s3.ListResourcesResultSchema, + "resources/templates/list": s3.ListResourceTemplatesResultSchema, + "resources/read": s3.ReadResourceResultSchema, + "resources/subscribe": s3.EmptyResultSchema, + "resources/unsubscribe": s3.EmptyResultSchema, + "tools/call": s3.CallToolResultWireSchema, + "tools/list": s3.ListToolsResultSchema, + "sampling/createMessage": s3.CreateMessageResultWithToolsSchema, + "elicitation/create": s3.ElicitResultSchema, + "roots/list": s3.ListRootsResultSchema + } + }; + return maps$1; +} +function warmRegistryMaps2025() { + registryMaps(); +} +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +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; +} +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +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) + }; +} +function toolNeedsLegacyWrap(t) { + return isPlainObject$4(t) && isPlainObject$4(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +function toNeutralResult(value) { + return value; +} +function build() { + const JSONValueSchema$1 = lazy(() => union([ + string2(), + number2(), + boolean2(), + _null3(), + record(string2(), JSONValueSchema$1), + array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = record(string2(), JSONValueSchema$1); + const ProgressTokenSchema$1 = union([string2(), number2().int()]); + const CursorSchema$1 = string2(); + const RequestIdSchema$1 = union([string2(), number2().int()]); + const RoleSchema$1 = _enum(["user", "assistant"]); + const LoggingLevelSchema$1 = _enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + const Base64Schema2 = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const TaskMetadataSchema$1 = object({ ttl: number2().optional() }); + const RelatedTaskMetadataSchema$1 = object({ taskId: string2() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = object({ + method: string2(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = object({ + src: string2(), + mimeType: string2().optional(), + sizes: array(string2()).optional(), + theme: _enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = object({ icons: array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = object({ + name: string2(), + title: string2().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: string2(), + websiteUrl: string2().optional(), + description: string2().optional() + }); + const FormElicitationCapabilitySchema2 = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema2 = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(object({ + form: FormElicitationCapabilitySchema2.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + 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() + }); + 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 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + sampling: object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema2.optional(), + roots: object({ listChanged: boolean2().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: object({ listChanged: boolean2().optional() }).optional(), + resources: object({ + subscribe: boolean2().optional(), + listChanged: boolean2().optional() + }).optional(), + tools: object({ listChanged: boolean2().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = object({ + progress: number2(), + total: optional(number2()), + message: optional(string2()) + }); + const ProgressNotificationParamsSchema$1 = 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: string2().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = object({ + uri: string2(), + mimeType: optional(string2()), + _meta: record(string2(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: string2() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema2 }); + const AnnotationsSchema$1 = object({ + audience: array(RoleSchema$1).optional(), + priority: number2().min(0).max(1).optional(), + lastModified: iso_exports.datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: string2(), + description: optional(string2()), + mimeType: optional(string2()), + size: optional(number2()), + annotations: AnnotationsSchema$1.optional(), + _meta: optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: string2(), + description: optional(string2()), + mimeType: optional(string2()), + annotations: AnnotationsSchema$1.optional(), + _meta: 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: string2() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = object({ + name: string2(), + description: optional(string2()), + required: optional(boolean2()) + }); + const PromptSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: optional(string2()), + arguments: optional(array(PromptArgumentSchema$1)), + _meta: optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = object({ + type: literal("text"), + text: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ImageContentSchema$1 = object({ + type: literal("image"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const AudioContentSchema$1 = object({ + type: literal("audio"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ToolUseContentSchema$1 = object({ + type: literal("tool_use"), + name: string2(), + id: string2(), + input: record(string2(), unknown()), + _meta: record(string2(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = object({ + type: literal("resource"), + resource: union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = object({ + title: string2().optional(), + readOnlyHint: boolean2().optional(), + destructiveHint: boolean2().optional(), + idempotentHint: boolean2().optional(), + openWorldHint: boolean2().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = object({ name: string2().optional() }); + const ModelPreferencesSchema$1 = object({ + hints: array(ModelHintSchema$1).optional(), + costPriority: number2().min(0).max(1).optional(), + speedPriority: number2().min(0).max(1).optional(), + intelligencePriority: number2().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = object({ mode: _enum([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = object({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() + }); + const StringSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: string2().optional() + }); + const NumberSchemaSchema$1 = object({ + type: _enum(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object({ + const: string2(), + title: string2() + })), + default: string2().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() + }); + const SingleSelectEnumSchemaSchema$1 = union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ anyOf: array(object({ + const: string2(), + title: string2() + })) }), + default: array(string2()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: string2(), + requestedSchema: object({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema$1), + required: array(string2()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = object({ + type: literal("ref/resource"), + uri: string2() + }); + const PromptReferenceSchema$1 = object({ + type: literal("ref/prompt"), + name: string2() + }); + const RootSchema$1 = object({ + uri: string2().startsWith("file://"), + name: string2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [PROTOCOL_VERSION_META_KEY]: string2(), + [CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + const ToolSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: string2().optional(), + inputSchema: looseObject({ + $schema: string2().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: string2().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ToolResultContentSchema$1 = object({ + type: literal("tool_result"), + toolUseId: string2(), + content: array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: boolean2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const SamplingMessageContentBlockSchema$1 = union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + const SamplingMessageSchema$1 = object({ + role: RoleSchema$1, + content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]), + _meta: record(string2(), unknown()).optional() + }); + const ResultTypeSchema = string2(); + const ResultMetaSchema = looseObject({ [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: array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: boolean2().optional() + }); + const ListToolsResultSchema$1 = wireResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + tools: array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + prompts: array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult({ + description: string2().optional(), + messages: array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + resources: array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + resourceTemplates: array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult({ completion: object({ + values: array(string2()).max(100), + total: number2().int().optional(), + hasMore: boolean2().optional() + }).loose() }); + const CacheableResultSchema = wireResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult({ + ttlMs: number2().int().min(0).catch(0), + cacheScope: _enum(["public", "private"]).catch("private"), + supportedVersions: array(string2()), + capabilities: ServerCapabilities2026Schema, + instructions: string2().optional() + }); + const CreateMessageRequestParamsSchema$1 = object({ + messages: array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: string2().optional(), + includeContext: _enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: number2().optional(), + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + const CreateMessageRequestSchema$1 = object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + const ListRootsRequestSchema$1 = object({ + method: literal("roots/list"), + params: object({ _meta: record(string2(), unknown()).optional() }).optional() + }); + const CreateMessageResultSchema$1 = object({ + ...SamplingMessageSchema$1.shape, + model: string2(), + stopReason: string2().optional() + }); + const ListRootsResultSchema$1 = object({ roots: array(RootSchema$1) }); + const ElicitResultSchema$1 = object({ + action: _enum([ + "accept", + "decline", + "cancel" + ]), + content: record(string2(), union([ + string2(), + number2(), + boolean2(), + array(string2()) + ])).optional() + }); + const ElicitRequestURLParamsSchema$1 = object({ + mode: literal("url"), + message: string2(), + url: string2().url() + }); + const ElicitRequestParamsSchema$1 = union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + const ElicitRequestSchema$1 = object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + const InputRequestSchema = union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + const InputResponseSchema = union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + const InputRequestsSchema = record(string2(), InputRequestSchema); + const InputResponsesSchema = record(string2(), InputResponseSchema); + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: string2().optional() + }); + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: string2().optional() + }; + const InputResponseRequestParamsSchema = object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return object({ + method: literal(method), + params: object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return object({ + method: literal(method), + params: object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: string2(), + arguments: record(string2(), 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: string2(), + arguments: record(string2(), string2()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: string2(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: object({ + name: string2(), + value: string2() + }), + context: object({ arguments: record(string2(), string2()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + const SubscriptionFilterSchema$1 = object({ + toolsListChanged: boolean2().optional(), + promptsListChanged: boolean2().optional(), + resourcesListChanged: boolean2().optional(), + resourceSubscriptions: array(string2()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: string2(), + arguments: record(string2(), string2()).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: string2() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: boolean2().optional() + }), + "tools/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + tools: array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: string2().optional(), + messages: array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + prompts: array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + resources: array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + resourceTemplates: array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum(["public", "private"]), + contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: object({ + values: array(string2()).max(100), + total: number2().int().optional(), + hasMore: boolean2().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: number2().int().min(0).catch(0), + cacheScope: _enum(["public", "private"]).catch("private"), + supportedVersions: array(string2()), + capabilities: ServerCapabilities2026Schema, + instructions: string2().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + const SubscriptionsAcknowledgedNotificationSchema$1 = object({ + method: literal("notifications/subscriptions/acknowledged"), + params: object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + const CancelledNotificationParamsSchema$1 = object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: string2().optional() + }); + const CancelledNotificationSchema$1 = 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) => object({ + jsonrpc: literal("2.0"), + id: union([string2(), number2().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(union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +function buildSchemas2026() { + return memo ??= build(); +} +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +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 ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +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$3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta3 = result["_meta"]; + if (meta3 === void 0) return { + ...result, + _meta: { [SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$3(meta3)) return result; + if (meta3[SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta3, + [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; +} +function inputSchemaMaps() { + if (maps) return maps; + const s3 = buildSchemas2026(); + maps = { + request: { + "elicitation/create": object({ + method: literal("elicitation/create"), + params: s3.ElicitRequestParamsSchema + }), + "sampling/createMessage": object({ + method: literal("sampling/createMessage"), + params: s3.CreateMessageRequestParamsSchema + }), + "roots/list": object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s3.ElicitResultSchema, + "sampling/createMessage": s3.CreateMessageResultSchema, + "roots/list": s3.ListRootsResultSchema + } + }; + return maps; +} +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; +} +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +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; +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +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) + }; +} +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$2(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { + if (!isPlainObject$2(tool) || !("execution" in tool)) return tool; + const rest = { ...tool }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$2(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy().capabilities = rest; + } + return next; +} +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s3 = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s3.CallToolResultSchema, + "tools/list": s3.ListToolsResultSchema, + "prompts/get": s3.GetPromptResultSchema, + "prompts/list": s3.ListPromptsResultSchema, + "resources/list": s3.ListResourcesResultSchema, + "resources/templates/list": s3.ListResourceTemplatesResultSchema, + "resources/read": s3.ReadResourceResultSchema, + "completion/complete": s3.CompleteResultSchema, + "server/discover": s3.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +function warmWireResultSchemas2026() { + getWireResultSchemas(); +} +function codecForVersion(version2) { + return version2 !== void 0 && isModernProtocolVersion(version2) ? rev2026Codec : rev2025Codec; +} +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec2) => codec2.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec2) => codec2.hasNotificationMethod(method)); +} +function parseJSONRPCMessage(value) { + return JSONRPCMessageSchema.parse(value); +} +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}`); +} +function 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 + }; +} +function pathName(path) { + return path.length === 0 ? "" : path.join("."); +} +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 needsBase64(s3) { + if (s3.length === 0) return true; + if (s3.startsWith(BASE64_SENTINEL_PREFIX) && s3.endsWith(BASE64_SENTINEL_SUFFIX)) return true; + if (s3 !== s3.trim()) return true; + for (let i = 0; i < s3.length; i++) { + const c = s3.codePointAt(i); + if (c === 9 || c >= 32 && c <= 126) continue; + return true; + } + return false; +} +function utf8ToBase64(s3) { + const bytes = new TextEncoder().encode(s3); + let bin = ""; + for (const b of bytes) bin += String.fromCodePoint(b); + return btoa(bin); +} +function encodeMcpParamValue(value) { + return needsBase64(value) ? `${BASE64_SENTINEL_PREFIX}${utf8ToBase64(value)}${BASE64_SENTINEL_SUFFIX}` : value; +} +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; +} +function buildMcpParamHeaders(declarations, args) { + const out = {}; + for (const decl of declarations) { + const raw = valueAtPath(args, decl.path); + if (raw === void 0 || raw === null) continue; + const stringValue = mcpParamPrimitiveToString(raw); + if (stringValue === void 0) continue; + out[`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`] = encodeMcpParamValue(stringValue); + } + return out; +} +function parseSchema(schema, data) { + return safeParse2(schema, data); +} +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} +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"; +} +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 + }; +} +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(issue2) { + if (!issue2.path?.length) return issue2.message; + return `${issue2.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue2.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; +} +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_exports.datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [email2()]; + break; + case "uri": + referenceSchemas = [url()]; + break; + case "date": + referenceSchemas = [iso_exports.date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error2) { + const detail = error2 instanceof Error ? error2.message : String(error2); + throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +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; +} +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 ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +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); + }); +} +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 ProtocolError(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 ProtocolError(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 ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} +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 } + }; +} +function withInputRequired(schema) { + return { "~standard": { + version: 1, + vendor: "modelcontextprotocol", + validate: (value, options) => { + if (isInputRequiredResult(value)) return { value }; + return schema["~standard"].validate(value, options); + } + } }; +} +function resolveInputRequiredDriverConfig(options) { + return { + autoFulfill: options?.autoFulfill ?? DEFAULT_INPUT_REQUIRED_AUTO_FULFILL, + maxRounds: options?.maxRounds ?? DEFAULT_INPUT_REQUIRED_MAX_ROUNDS + }; +} +function buildInputRequiredRetryParams(originalParams, responses, requestState) { + const hasResponses = responses !== void 0 && Object.keys(responses).length > 0; + if (!hasResponses && requestState === void 0) return originalParams; + return { + ...originalParams, + ...hasResponses && { inputResponses: responses }, + ...requestState !== void 0 && { requestState } + }; +} +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +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) + }; +} +async function runInputRequiredDriver(args) { + const { config: config2, method, originalParams, requestOptions, hooks, signal } = args; + const startedAt = args.flowStartedAt ?? Date.now(); + let payload = args.firstPayload; + let round = 0; + while (true) { + round += 1; + if (round > config2.maxRounds) throw new SdkError(SdkErrorCode.InputRequiredRoundsExceeded, inputRequiredRoundsExceededMessage(method, config2.maxRounds), { + rounds: config2.maxRounds, + lastResult: { + inputRequests: payload.inputRequests, + ...payload.requestState !== void 0 && { requestState: payload.requestState } + } + }); + requestOptions.onprogress?.({ + progress: round, + message: `Fulfilling input required by '${method}' (round ${round})` + }); + const entries = Object.entries(payload.inputRequests ?? {}); + let responses; + if (entries.length > 0) { + const round$1 = linkedRoundAbort(signal); + try { + const fulfilled = await Promise.all(entries.map(async ([key, entry]) => { + try { + return [key, await hooks.dispatchInputRequest(key, entry, round$1.signal)]; + } catch (error2) { + round$1.abort(error2); + throw error2; + } + })); + responses = Object.fromEntries(fulfilled); + } finally { + round$1.dispose(); + } + } else await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, signal); + const legOptions = { ...requestOptions.timeout !== void 0 && { timeout: requestOptions.timeout } }; + if (requestOptions.maxTotalTimeout !== void 0) { + const totalElapsed = Date.now() - startedAt; + const remaining = requestOptions.maxTotalTimeout - totalElapsed; + if (remaining <= 0) throw new SdkError(SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: requestOptions.maxTotalTimeout, + totalElapsed + }); + legOptions.maxTotalTimeout = remaining; + } + const result = await hooks.retry(buildInputRequiredRetryParams(originalParams, responses, payload.requestState), legOptions); + if (isInputRequiredResult(result)) { + payload = { + inputRequests: result.inputRequests ?? {}, + ...result.requestState !== void 0 && { requestState: result.requestState } + }; + continue; + } + return result; + } +} +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": + return codecForVersion(void 0); + case "server/discover": + return codecForVersion(MODERN_WIRE_REVISION); + default: + return; + } +} +function liftWireOnlyMaterial(message2, kind) { + const params = message2.params; + if (!isPlainObject$1(params)) return { + message: message2, + lifted: {} + }; + const meta3 = params._meta; + const envelopeKeys = isPlainObject$1(meta3) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta3) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message: message2, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta3)) { + const envelope = {}; + const nextMeta = { ...meta3 }; + for (const key of envelopeKeys) { + envelope[key] = meta3[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: { + ...message2, + params: nextParams + }, + lifted + }; +} +function codecResultValidator(codec2, method) { + const probe = codec2.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 = codec2.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +function requestStateAccessor(value) { + return () => value; +} +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; +} +function isPlainObject2(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!isPlainObject2(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!isPlainObject2(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +function relatedMessagingUnavailable(member) { + throw new SdkError(SdkErrorCode.SendFailed, `ctx.mcpReq.${member} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`); +} +function synthesizeInputRequestContext(key, method, params, signal, sessionId) { + return { + sessionId, + mcpReq: { + id: key, + method, + _meta: params?.["_meta"], + requestState: requestStateAccessor(void 0), + signal, + send: (() => relatedMessagingUnavailable("send")), + notify: () => relatedMessagingUnavailable("notify") + } + }; +} +async function dispatchInputRequest(host, codec2, key, entry, signal) { + if (!isPlainObject2(entry) || typeof entry["method"] !== "string") throw new SdkError(SdkErrorCode.InvalidResult, `Invalid input request '${key}': each inputRequests entry must be an embedded request object with a method`, { key }); + const method = entry["method"]; + if (!codec2.hasInputRequestMethod(method)) throw new SdkError(SdkErrorCode.InvalidResult, `Invalid input request '${key}': '${method}' is not an embedded request the ${codec2.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`, { + key, + method + }); + const handler = host.getRequestHandler(method); + if (handler === void 0) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Cannot fulfil input request '${key}': no handler is registered for '${method}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`, { + key, + method + }); + const params = isPlainObject2(entry["params"]) ? entry["params"] : void 0; + return await handler({ + jsonrpc: "2.0", + id: key, + method, + ...params !== void 0 && { params } + }, host.buildContext(synthesizeInputRequestContext(key, method, params, signal, host.sessionId))); +} +function buildRetryLegRequestOptions(options, legOptions) { + return { + ...options?.signal !== void 0 && { signal: options.signal }, + ...options?.onprogress !== void 0 && { onprogress: options.onprogress }, + ...options?.resetTimeoutOnProgress !== void 0 && { resetTimeoutOnProgress: options.resetTimeoutOnProgress }, + ...options?.headers !== void 0 && { headers: options.headers }, + ...legOptions.timeout !== void 0 && { timeout: legOptions.timeout }, + ...legOptions.maxTotalTimeout !== void 0 && { maxTotalTimeout: legOptions.maxTotalTimeout }, + allowInputRequired: true + }; +} +function runInputRequiredFlow(host, config2, decoded, flow) { + const { codec: codec2, request, options, flowStartedAt } = flow; + const firstPayload = { + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; + const hooks = { + dispatchInputRequest: (key, entry, signal) => dispatchInputRequest(host, codec2, key, entry, signal), + retry: (params, legOptions) => flow.retry(params, buildRetryLegRequestOptions(options, legOptions)) + }; + return runInputRequiredDriver({ + config: config2, + method: request.method, + originalParams: request.params, + firstPayload, + flowStartedAt, + signal: options?.signal, + requestOptions: { + ...options?.timeout !== void 0 && { timeout: options.timeout }, + ...options?.maxTotalTimeout !== void 0 && { maxTotalTimeout: options.maxTotalTimeout }, + ...options?.onprogress !== void 0 && { onprogress: options.onprogress } + }, + hooks + }); +} +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} +function 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; + } +} +function isJsonContentType(header) { + if (header === "application/json") return true; + return mediaTypeEssence(header) === "application/json"; +} +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; +} +function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message2) { + return JSON.stringify(message2) + "\n"; +} +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 }; +} +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url2, init) => { + return baseFetch(url2, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} +function preloadSchemas() { + buildSchemas2025(); + buildSchemas2026(); + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} +function fromJsonSchema(schema, validator) { + const check3 = validator.getValidator(schema); + return { "~standard": { + version: 1, + vendor: "mcp", + jsonSchema: { + input: () => schema, + output: () => schema + }, + validate: (data) => { + const result = check3(data); + return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; + } + } }; +} +var BRANDS, OAuthErrorCode, OAuthError, SdkErrorCode, SdkError, SdkHttpError, FIRST_MODERN_PROTOCOL_VERSION, SUPPORTED_MODERN_PROTOCOL_VERSIONS, TOOL_RESULT_FOREIGN_FAMILY_KEYS, memo$1, REF_REWRITE_DATA_POSITION_KEYS, REF_REWRITE_NAME_MAP_KEYS, requestMethodKeys$1, notificationMethodKeys$1, resultMethodKeys, maps$1, rev2025RequestMethods, rev2025NotificationMethods, NOT_IN_ERA$1, rev2025Codec, memo, CACHEABLE_RESULT_METHODS, RESULT_CACHE_HINT_FALLBACK, ProtocolErrorCode, ProtocolError, ResourceNotFoundError, UrlElicitationRequiredError, UnsupportedProtocolVersionError, MissingRequiredClientCapabilityError, DEFAULT_CACHE_TTL_MS, DEFAULT_CACHE_SCOPE, EXTENDED_RESULT_TYPE_METHODS, INPUT_REQUEST_METHODS_2026, maps, requestMethodKeys, notificationMethodKeys, rev2026RequestMethods, rev2026NotificationMethods, NOT_IN_ERA, REQUIRED_ENVELOPE_KEYS, rev2026Codec, wireResultSchemasMemo, MODERN_WIRE_REVISION, ALL_CODECS, schemas_exports3, isJSONRPCRequest, isJSONRPCNotification, isJSONRPCResultResponse, isJSONRPCErrorResponse, isJSONRPCResponse, isCallToolResult, isInputRequiredResult, isTaskAugmentedRequestParams, isInitializeRequest, isInitializedNotification, MCP_PARAM_HEADER_PREFIX, X_MCP_HEADER_KEY, RFC9110_TOKEN, PERMITTED_X_MCP_HEADER_TYPES, NON_REACHABLE_SUBSCHEMA_KEYWORDS, OBJECT_VALUED_SUBSCHEMA_KEYWORDS, BASE64_SENTINEL_PREFIX, BASE64_SENTINEL_SUFFIX, HEADER_MISMATCH_ERROR_CODE, INBOUND_VALIDATION_LADDER, LADDER_ERROR_HTTP_STATUS, warnedZodFallback, JSON_SCHEMA_CONVERSION_TARGET, DATETIME_FRACTION_DIGITS, ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS, ROOT_KEYS, PROPERTY_KEYS_BY_TYPE, SUPPORTED_STRING_FORMATS, inputRequired, DEFAULT_INPUT_REQUIRED_AUTO_FULFILL, DEFAULT_INPUT_REQUIRED_MAX_ROUNDS, REQUEST_STATE_ONLY_LEG_PACING_MS, SPEC_SCHEMA_KEYS, authSchemas, _specTypeSchemas, _isSpecType, specTypeSchemas, isSpecType, DEFAULT_REQUEST_TIMEOUT_MSEC, RESERVED_ENVELOPE_META_KEYS, RETRY_PARAMS_KEYS, NO_REQUEST_STATE, writeNegotiatedProtocolVersion, Protocol, require_content_type, import_content_type, STDIO_DEFAULT_MAX_BUFFER_SIZE, ReadBuffer, MAX_TEMPLATE_LENGTH, MAX_VARIABLE_LENGTH, MAX_TEMPLATE_EXPRESSIONS, MAX_REGEX_LENGTH, UriTemplate, InMemoryTransport; +var init_src_CgOncMok = __esm({ + "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/src-CgOncMok.mjs"() { + init_chunk_Br0eD_fh(); + init_internal(); + init_v4(); + BRANDS = /* @__PURE__ */ Symbol.for("mcp.sdk.errorBrands"); + OAuthErrorCode = /* @__PURE__ */ (function(OAuthErrorCode$1) { + OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; + OAuthErrorCode$1["InvalidClient"] = "invalid_client"; + OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; + OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; + OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; + OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; + OAuthErrorCode$1["AccessDenied"] = "access_denied"; + OAuthErrorCode$1["ServerError"] = "server_error"; + OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; + OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; + OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; + OAuthErrorCode$1["InvalidToken"] = "invalid_token"; + OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; + OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; + OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; + OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; + OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; + OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; + return OAuthErrorCode$1; + })({}); + OAuthError = class OAuthError2 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, message2, errorUri) { + super(message2); + 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 OAuthError2(response.error, response.error_description ?? response.error, response.error_uri); + } + }; + SdkErrorCode = /* @__PURE__ */ (function(SdkErrorCode$1) { + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + 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; + })({}); + 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, message2, data) { + super(message2); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } + }; + SdkHttpError = class extends SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message2, data) { + super(code, message2, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } + }; + FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; + SUPPORTED_MODERN_PROTOCOL_VERSIONS = [FIRST_MODERN_PROTOCOL_VERSION]; + TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" + ]; + REF_REWRITE_DATA_POSITION_KEYS = /* @__PURE__ */ new Set([ + "const", + "enum", + "default", + "examples" + ]); + REF_REWRITE_NAME_MAP_KEYS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas" + ]); + 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 + }; + 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 + }; + 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 + }; + rev2025RequestMethods = Object.keys(requestMethodKeys$1); + rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); + NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" + }; + 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 s3 = buildSchemas2025(); + return triState$1(hasTools ? s3.CreateMessageResultWithToolsSchema : s3.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$4(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 + }; + CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" + ]; + RESULT_CACHE_HINT_FALLBACK = /* @__PURE__ */ Symbol("modelcontextprotocol.resultCacheHintFallback"); + 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"; + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; + })({}); + ProtocolError = class ProtocolError2 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, message2, data) { + super(message2); + 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, message2, data) { + if (code === ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message2); + } + if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message2); + } + if (code === ProtocolErrorCode.InvalidParams || code === ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message2); + } + if (code === ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message2); + } + return new ProtocolError2(code, message2, data); + } + }; + ResourceNotFoundError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message2 = `Resource not found: ${uri}`) { + super(ProtocolErrorCode.InvalidParams, message2, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } + }; + UrlElicitationRequiredError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message2 = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(ProtocolErrorCode.UrlElicitationRequired, message2, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } + }; + UnsupportedProtocolVersionError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message2 = `Unsupported protocol version: ${data.requested}`) { + super(ProtocolErrorCode.UnsupportedProtocolVersion, message2, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } + }; + MissingRequiredClientCapabilityError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message2 = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(ProtocolErrorCode.MissingRequiredClientCapability, message2, 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; + } + }; + DEFAULT_CACHE_TTL_MS = 0; + DEFAULT_CACHE_SCOPE = "private"; + EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" + ]; + INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" + ]; + 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 + }; + 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 + }; + rev2026RequestMethods = Object.keys(requestMethodKeys); + rev2026NotificationMethods = Object.keys(notificationMethodKeys); + NOT_IN_ERA = { + ok: false, + reason: "not-in-era" + }; + REQUIRED_ENVELOPE_KEYS = [PROTOCOL_VERSION_META_KEY, CLIENT_CAPABILITIES_META_KEY]; + 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 { + [PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [CLIENT_INFO_META_KEY]: material.clientInfo, + [CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta3) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta3)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3); + if (!parsed.success) for (const issue2 of parsed.error.issues) { + const path = issue2.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: issue2.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$2(raw)) return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$2(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new SdkError(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 SdkError(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 SdkError(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((issue2) => issue2.message).join("; ")}`; + } + }; + MODERN_WIRE_REVISION = "2026-07-28"; + ALL_CODECS = [rev2025Codec, rev2026Codec]; + schemas_exports3 = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => 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: () => InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => 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: () => 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 + }); + isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; + isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; + isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; + isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; + isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; + isCallToolResult = (value) => { + if (typeof value !== "object" || value === null || value.content === void 0) return false; + return CallToolResultSchema.safeParse(value).success; + }; + isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; + isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; + isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; + isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; + MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; + X_MCP_HEADER_KEY = "x-mcp-header"; + RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([ + "string", + "integer", + "boolean", + "number" + ]); + NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "$defs", + "definitions" + ]; + OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "patternProperties", + "dependentSchemas", + "$defs", + "definitions" + ]); + BASE64_SENTINEL_PREFIX = "=?base64?"; + BASE64_SENTINEL_SUFFIX = "?="; + HEADER_MISMATCH_ERROR_CODE = -32020; + 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: [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, 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: [ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." + }, + { + rung: "method-registry", + order: 5, + evaluatedAt: "dispatch", + codes: [ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." + }, + { + rung: "request-params", + order: 6, + evaluatedAt: "dispatch", + codes: [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 \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." + }, + { + rung: "param-header-validation", + order: 9, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." + } + ]; + LADDER_ERROR_HTTP_STATUS = { + [ProtocolErrorCode.ParseError]: 400, + [ProtocolErrorCode.InvalidRequest]: 400, + [ProtocolErrorCode.MethodNotFound]: 404, + [ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 + }; + warnedZodFallback = false; + JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; + DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; + ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" + ]); + ROOT_KEYS = /* @__PURE__ */ new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); + PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) + }; + SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); + inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error2) { + throw error2 instanceof ProtocolError ? new TypeError(error2.message, { cause: error2 }) : error2; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } + }); + DEFAULT_INPUT_REQUIRED_AUTO_FULFILL = true; + DEFAULT_INPUT_REQUIRED_MAX_ROUNDS = 10; + REQUEST_STATE_ONLY_LEG_PACING_MS = 250; + 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" + ]; + authSchemas = { + IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema, + OAuthClientInformationSchema, + OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema, + OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema, + OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema + }; + _specTypeSchemas = {}; + _isSpecType = {}; + for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports3[key]); + for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); + specTypeSchemas = Object.freeze(_specTypeSchemas); + isSpecType = Object.freeze(_isSpecType); + DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; + RESERVED_ENVELOPE_META_KEYS = [ + PROTOCOL_VERSION_META_KEY, + CLIENT_INFO_META_KEY, + CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY + ]; + RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; + NO_REQUEST_STATE = requestStateAccessor(void 0); + 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, version2) => { + instance._negotiatedProtocolVersion = version2; + }; + } + _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 ?? 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(message2) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message2; + const params = message2.params ?? {}; + return { + ...message2, + 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 SdkError(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 SdkError(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 = (error2) => { + _onerror?.(error2); + this._onerror(error2); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message2, extra) => { + _onmessage?.(message2, extra); + if (isJSONRPCResultResponse(message2) || isJSONRPCErrorResponse(message2)) this._onresponse(message2); + else if (isJSONRPCRequest(message2)) this._onrequest(message2, extra); + else if (isJSONRPCNotification(message2)) this._onnotification(message2, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message2)}`)); + }; + 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 error2 = new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error2); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error2); + } + } + _onerror(error2) { + this.onerror?.(error2); + } + /** + * 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 codec2 = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec2.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec2.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec2.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, codec2)).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error2}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec2 = 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, message2, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message: message2, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error2}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec2.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec2.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec2.hasRequestMethod(request.method)) { + sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec2.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(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 = codec2.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error2) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error2}`)); + sendErrorResponse(ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error2) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error2["code"]) ? error2["code"] : ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec2.encodeErrorCode(thrownCode), + message: error2.message ?? "Internal error", + ...error2["data"] !== void 0 && { data: error2["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error2}`))).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 (error2) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error2); + 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 (isJSONRPCResultResponse(response)) handler(response); + else handler(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 codec2 = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec2, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec2, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec2, 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(codec2, 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 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(codec2, method) { + if (isSpecRequestMethod(method) && !codec2.hasRequestMethod(method)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec2.era})`, { + method, + era: codec2.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 codec2 = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec2, request.method); + return this._requestWithSchemaViaCodec(codec2, 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(codec2, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error2) => { + reject(error2); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error2) { + earlyReject(error2); + return; + } + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = codec2.era === 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((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error2}`))); + else requestAbort.abort(); + reject(reason instanceof SdkError ? reason : new SdkError(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 = codec2.decodeResult(request.method, response.result); + } catch (error2) { + return reject(error2 instanceof Error ? error2 : new Error(String(error2))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec: codec2, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec2, 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 SdkError(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 SdkError(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((error2) => { + this._progressHandlers.delete(messageId); + reject(error2); + }); + }).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(codec2, notification, options) { + if (!this._transport) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec2.hasNotificationMethod(notification.method)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec2.era})`, { + method: notification.method, + era: codec2.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((error2) => this._onerror(error2)); + }); + 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 ProtocolError(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 ProtocolError(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, codec2) => { + const outcome = codec2.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new ProtocolError(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 ProtocolError(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); + } + }; + require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse3; + function parse3(string4) { + if (!string4) throw new TypeError("argument string is required"); + var header = typeof string4 === "object" ? getcontenttype(string4) : string4; + 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; + } + 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; + } + function ContentType(type) { + this.parameters = /* @__PURE__ */ Object.create(null); + this.type = type; + } + })); + import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); + STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; + 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 (error2) { + if (error2 instanceof SyntaxError) continue; + throw error2; + } + } + return null; + } + clear() { + this._buffer = void 0; + } + }; + MAX_TEMPLATE_LENGTH = 1e6; + MAX_VARIABLE_LENGTH = 1e6; + MAX_TEMPLATE_EXPRESSIONS = 1e4; + MAX_REGEX_LENGTH = 1e6; + UriTemplate = class UriTemplate2 { + /** + * 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) { + UriTemplate2.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) UriTemplate2.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) { + UriTemplate2.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) UriTemplate2.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) { + UriTemplate2.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 += "$"; + UriTemplate2.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; + } + }; + InMemoryTransport = class InMemoryTransport2 { + _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 InMemoryTransport2(); + const serverTransport = new InMemoryTransport2(); + 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(message2, options) { + if (!this._otherTransport) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); + if (this._otherTransport.onmessage) this._otherTransport.onmessage(message2, { authInfo: options?.authInfo }); + else this._otherTransport._messageQueue.push({ + message: message2, + extra: { authInfo: options?.authInfo } + }); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/ajvProvider-Asx17_Co.mjs +function createDefaultAjvInstance() { + const ajv = new import__2020.Ajv2020({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + addFormats(ajv); + return ajv; +} +var require_code$1, require_scope, require_codegen, require_util, require_names, require_errors, require_boolSchema, require_rules, require_applicability, require_dataType, require_defaults, require_code, require_keyword, require_subschema, require_fast_deep_equal, require_json_schema_traverse, require_resolve, require_validate, require_validation_error, require_ref_error, require_compile, require_data, require_utils, require_schemes, require_fast_uri, require_uri, require_core$2, require_id, require_ref, require_core$1, require_limitNumber, require_multipleOf, require_ucs2length, require_limitLength, require_pattern, require_limitProperties, require_required, require_limitItems, require_equal, require_uniqueItems, require_const, require_enum, require_validation$1, require_additionalItems, require_items, require_prefixItems, require_items2020, require_contains, require_dependencies, require_propertyNames, require_additionalProperties, require_properties, require_patternProperties, require_not, require_anyOf, require_oneOf, require_allOf, require_if, require_thenElse, require_applicator$1, require_format$1, require_format, require_metadata, require_draft7, require_types, require_discriminator, require_json_schema_draft_07, require_ajv, require_dynamicAnchor, require_dynamicRef, require_recursiveAnchor, require_recursiveRef, require_dynamic, require_dependentRequired, require_dependentSchemas, require_limitContains, require_next, require_unevaluatedProperties, require_unevaluatedItems, require_unevaluated$1, require_draft2020, require_schema, require_applicator, require_unevaluated, require_content, require_core, require_format_annotation, require_meta_data, require_validation, require_json_schema_2020_12, require__2020, require_formats, require_limit, require_dist, import_ajv, import__2020, import_dist, DRAFT_2020_12_URIS, addFormats, AjvJsonSchemaValidator, Ajv; +var init_ajvProvider_Asx17_Co = __esm({ + "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/ajvProvider-Asx17_Co.mjs"() { + init_chunk_Br0eD_fh(); + 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(s3) { + super(); + if (!exports.IDENTIFIER.test(s3)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s3; + } + 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 _a2; + return (_a2 = this._str) !== null && _a2 !== void 0 ? _a2 : this._str = this._items.reduce((s3, c) => `${s3}${c}`, ""); + } + get names() { + var _a2; + return (_a2 = this._names) !== null && _a2 !== void 0 ? _a2 : 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; + })); + 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(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["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 _a2, _b; + if (((_b = (_a2 = this._parent) === null || _a2 === void 0 ? void 0 : _a2._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 _a2; + 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 = (_a2 = value.key) !== null && _a2 !== void 0 ? _a2 : 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 s3 = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s3.length; + s3[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; + })); + 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(error2) { + super(); + this.error = error2; + } + 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 If2 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 If2 ? e : e.nodes; + if (this.nodes.length) return this; + return new If2(not(cond), e instanceof If2 ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a2; + this.else = (_a2 = this.else) === null || _a2 === void 0 ? void 0 : _a2.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 _a2, _b; + super.optimizeNodes(); + (_a2 = this.catch) === null || _a2 === void 0 || _a2.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a2, _b; + super.optimizeNames(names, constants); + (_a2 = this.catch) === null || _a2 === void 0 || _a2.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(error2) { + super(); + this.error = error2; + } + 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 error2 = this.name("e"); + this._currNode = node.catch = new Catch(error2); + catchCode(error2); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error2) { + return this._leafNode(new Throw(error2)); + } + 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})`; + } + })); + 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 hash2 = {}; + for (const item of arr) hash2[item] = true; + return hash2; + } + 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: mergeValues2, 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) : mergeValues2(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(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["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; + })); + 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; + })); + 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, error2 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error2, 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, error2 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error2, 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 }) { + 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, error2, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error2, errorPaths); + } + function errorObject(cxt, error2, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error2, 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: message2 }, 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 message2 == "function" ? message2(cxt) : message2]); + 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]); + } + })); + 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); + } + })); + require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = /* @__PURE__ */ 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; + })); + 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 _a2; + return schema[rule.keyword] !== void 0 || ((_a2 = rule.definition.implements) === null || _a2 === void 0 ? void 0 : _a2.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + })); + 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(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["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 = /* @__PURE__ */ 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 + }; + } + })); + 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)}`); + } + })); + 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; + 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; + })); + 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 _a2; + 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((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : 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) { + 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; + })); + 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; + })); + 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; + }; + })); + 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"); + } + })); + 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 = /* @__PURE__ */ 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 = /* @__PURE__ */ 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; + })); + 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) { + 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 matches2 = RELATIVE_JSON_POINTER.exec($data); + if (!matches2) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches2[1]; + jsonPointer = matches2[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; + })); + 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; + })); + 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; + })); + 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 _a2; + 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 = (_a2 = env.baseId) !== null && _a2 !== void 0 ? _a2 : (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 _a2; + 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 = (_a2 = root.localRefs) === null || _a2 === void 0 ? void 0 : _a2[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, s22) { + return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.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 = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a2; + if (((_a2 = parsedRef.fragment) === null || _a2 === void 0 ? void 0 : _a2[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; + } + })); + 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 + }; + })); + require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + 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); + 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; + } + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex3 = stringArrayToHexStripped(buffer); + if (hex3 !== "") address.push(hex3); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + const address = []; + 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; + } + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv63 = getIPV6(host); + if (!ipv63.error) { + let newHost = ipv63.address; + let escapedHost = ipv63.address; + if (ipv63.zone) { + newHost += "%" + ipv63.zone; + escapedHost += "%25" + ipv63.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + 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(""); + } + function normalizeComponentEncoding(component, esc2) { + const func = esc2 !== 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; + } + 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 + }; + })); + 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" + ]; + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + 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; + } + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + 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; + } + 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; + } + 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; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches2 = urnComponent.path.match(URN_REG); + if (matches2) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches2[1].toLowerCase(); + urnComponent.nss = matches2[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; + } + 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; + } + 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; + } + 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); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + })); + require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse3(uri, options), options); + else if (typeof uri === "object") uri = parse3(serialize(uri, options), options); + return uri; + } + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse3(serialize(base, options), options); + relative = parse3(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; + } + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse3(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(parse3(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + 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 s3 = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s3 = removeDotSegments(s3); + if (authority === void 0 && s3[0] === "/" && s3[1] === "/") s3 = "/%2F" + s3.slice(2); + uriTokens.push(s3); + } + 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; + function parse3(uri, opts) { + const options = Object.assign({}, opts); + 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 matches2 = uri.match(URI_PARSE); + if (matches2) { + parsed.scheme = matches2[1]; + parsed.userinfo = matches2[3]; + parsed.host = matches2[4]; + parsed.port = parseInt(matches2[5], 10); + parsed.path = matches2[6] || ""; + parsed.query = matches2[7]; + parsed.fragment = matches2[8]; + if (isNaN(parsed.port)) parsed.port = matches2[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: parse3 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; + })); + 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; + })); + require_core$2 = /* @__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 = /* @__PURE__ */ 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 _a2, _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 s3 = o.strict; + const _optz = (_a2 = o.code) === null || _a2 === void 0 ? void 0 : _a2.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 : s3) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s3) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s3) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s3) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s3) !== 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 Ajv2 = 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: meta3, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta3 && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta: meta3, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : 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, meta3) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta3); + 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, meta3); + } + 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 message2 = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message2); + else throw new Error(message2); + } + 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, meta3, 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: meta3, + 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); + 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; + } + } + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + 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 _a2; + 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; + (_a2 = definition.implements) === null || _a2 === void 0 || _a2.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] }; + } + })); + 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; + })); + 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 _a2; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a2 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a2 === void 0 ? void 0 : _a2.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; + })); + require_core$1 = /* @__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; + })); + 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; + })); + 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; + })); + 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'; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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 { + 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; + })); + require_validation$1 = /* @__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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + 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; + })); + 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; + 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; + })); + 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; + })); + 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; + })); + require_applicator$1 = /* @__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; + })); + require_format$1 = /* @__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; + })); + require_format = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$1().default]; + exports.default = format; + })); + 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" + ]; + })); + require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$1(); + const validation_1 = require_validation$1(); + const applicator_1 = require_applicator$1(); + const format_1 = require_format(); + 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; + })); + require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + })); + 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: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` + }, + 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 tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag2} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag: tag2, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag: tag2, + 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 _a2; + 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 = (_a2 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a2 === void 0 ? void 0 : _a2[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: required2 }) { + return Array.isArray(required2) && required2.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; + })); + 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 + }; + })); + 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$2(); + 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 Ajv2 = 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 = Ajv2; + module.exports = exports = Ajv2; + module.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + 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; + } + }); + })); + 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: meta3 } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta: meta3 + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + })); + 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; + 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; + })); + 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; + })); + 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; + })); + require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$1(); + const validation_1 = require_validation$1(); + const applicator_1 = require_applicator$1(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format(); + 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; + })); + 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 + } + } + }; + })); + 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" } + } } + }; + })); + 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" } + } + }; + })); + 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" } + } + }; + })); + 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" + } + } + }; + })); + 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" } } + }; + })); + 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 + } + } + }; + })); + 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": [] + } + } + }; + })); + 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; + })); + 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$2(); + 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: meta3 } = this.opts; + if (!meta3) 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; + } + }); + })); + 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(date5, 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(year2) { + return year2 % 4 === 0 && (year2 % 100 !== 0 || year2 % 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 date5(str) { + const matches2 = DATE.exec(str); + if (!matches2) return false; + const year2 = +matches2[1]; + const month = +matches2[2]; + const day2 = +matches2[3]; + return month >= 1 && month <= 12 && day2 >= 1 && day2 <= (month === 2 && isLeapYear(year2) ? 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 time3(str) { + const matches2 = TIME.exec(str); + if (!matches2) return false; + const hr = +matches2[1]; + const min = +matches2[2]; + const sec = +matches2[3]; + const tz = matches2[4]; + const tzSign = matches2[5] === "-" ? -1 : 1; + const tzH = +(matches2[6] || 0); + const tzM = +(matches2[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, s22) { + if (!(s1 && s22)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).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 time3 = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date5(dateTime[0]) && time3(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_INT322 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT322 && 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; + } + } + })); + 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 error2 = { + 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: error2, + 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; + })); + 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)) { + addFormats2(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats2(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 addFormats2(ajv, list, fs, exportName) { + var _a2; + var _b; + (_a2 = (_b = ajv.opts.code).formats) !== null && _a2 !== 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; + })); + import_ajv = require_ajv(); + import__2020 = require__2020(); + import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); + DRAFT_2020_12_URIS = /* @__PURE__ */ new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); + addFormats = import_dist.default; + AjvJsonSchemaValidator = class { + _ajv; + /** True iff the constructor received a caller-supplied engine; the `$schema` check 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 a single `Ajv2020` instance with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call**, 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 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(); + } + getValidator(schema) { + if (!this._userAjv && "$schema" in schema && typeof schema.$schema === "string" && !DRAFT_2020_12_URIS.has(schema.$schema.replace(/#$/, ""))) { + const declared = schema.$schema.slice(0, 200); + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${declared}"). The default validator supports JSON Schema 2020-12 only; pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.`); + } + const engine = this.ajv; + 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) + }; + }; + } + }; + Ajv = import_ajv.Ajv; + } +}); + +// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/shimsNode.mjs +var CORS_IS_POSSIBLE; +var init_shimsNode = __esm({ + "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/shimsNode.mjs"() { + init_ajvProvider_Asx17_Co(); + CORS_IS_POSSIBLE = false; + } +}); + +// ../freya/node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js +async function getRandomValues(size) { + return (await crypto2).getRandomValues(new Uint8Array(size)); +} +async function random(size) { + const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; + const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length; + let result = ""; + while (result.length < size) { + const randomBytes = await getRandomValues(size - result.length); + for (const randomByte of randomBytes) { + if (randomByte < evenDistCutoff) { + result += mask[randomByte % mask.length]; + } + } + } + return result; +} +async function generateVerifier(length) { + return await random(length); +} +async function generateChallenge(code_verifier) { + const buffer = await (await crypto2).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); + return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, ""); +} +async function pkceChallenge(length) { + if (!length) + length = 43; + if (length < 43 || length > 128) { + throw `Expected a length between 43 and 128. Received ${length}.`; + } + const verifier = await generateVerifier(length); + const challenge = await generateChallenge(verifier); + return { + code_verifier: verifier, + code_challenge: challenge + }; +} +var crypto2; +var init_index_node = __esm({ + "../freya/node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js"() { + crypto2 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL + globalThis.crypto ?? // Node.js >18 + import("node:crypto").then((m) => m.webcrypto); + } +}); + +// ../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js +function noop(_arg) { +} +function createParser(callbacks) { + if (typeof callbacks == "function") + throw new TypeError( + "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" + ); + const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; + let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; + function feed(newChunk) { + const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); + for (const line of complete) + parseLine(line); + incompleteLine = incomplete, isFirstChunk = false; + } + function parseLine(line) { + if (line === "") { + dispatchEvent(); + return; + } + if (line.startsWith(":")) { + onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); + return; + } + const fieldSeparatorIndex = line.indexOf(":"); + if (fieldSeparatorIndex !== -1) { + const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); + processField(field, value, line); + return; + } + processField(line, "", line); + } + function processField(field, value, line) { + switch (field) { + case "event": + eventType = value; + break; + case "data": + data = `${data}${value} +`; + break; + case "id": + id = value.includes("\0") ? void 0 : value; + break; + case "retry": + /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( + new ParseError(`Invalid \`retry\` value: "${value}"`, { + type: "invalid-retry", + value, + line + }) + ); + break; + default: + onError( + new ParseError( + `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, + { type: "unknown-field", field, value, line } + ) + ); + break; + } + } + function dispatchEvent() { + data.length > 0 && onEvent({ + id, + event: eventType || void 0, + // If the data buffer's last character is a U+000A LINE FEED (LF) character, + // then remove the last character from the data buffer. + data: data.endsWith(` +`) ? data.slice(0, -1) : data + }), id = void 0, data = "", eventType = ""; + } + function reset(options = {}) { + incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = ""; + } + return { feed, reset }; +} +function splitLines(chunk) { + const lines = []; + let incompleteLine = "", searchIndex = 0; + for (; searchIndex < chunk.length; ) { + const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` +`, searchIndex); + let lineEnd = -1; + if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) { + incompleteLine = chunk.slice(searchIndex); + break; + } else { + const line = chunk.slice(searchIndex, lineEnd); + lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === ` +` && searchIndex++; + } + } + return [lines, incompleteLine]; +} +var ParseError; +var init_dist = __esm({ + "../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js"() { + ParseError = class extends Error { + constructor(message2, options) { + super(message2), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js +function syntaxError(message2) { + const DomException = globalThis.DOMException; + return typeof DomException == "function" ? new DomException(message2, "SyntaxError") : new SyntaxError(message2); +} +function flattenError2(err) { + return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError2).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError2(err.cause)}` : err.message : `${err}`; +} +function inspectableError(err) { + return { + type: err.type, + message: err.message, + code: err.code, + defaultPrevented: err.defaultPrevented, + cancelable: err.cancelable, + timeStamp: err.timeStamp + }; +} +function getBaseURL() { + const doc = "document" in globalThis ? globalThis.document : void 0; + return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0; +} +var ErrorEvent, __typeError, __accessCheck, __privateGet, __privateAdd, __privateSet, __privateMethod, _readyState, _url2, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect, EventSource; +var init_dist2 = __esm({ + "../freya/node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"() { + init_dist(); + ErrorEvent = class extends Event { + /** + * Constructs a new `ErrorEvent` instance. This is typically not called directly, + * but rather emitted by the `EventSource` object when an error occurs. + * + * @param type - The type of the event (should be "error") + * @param errorEventInitDict - Optional properties to include in the error event + */ + constructor(type, errorEventInitDict) { + var _a2, _b; + super(type), this.code = (_a2 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a2 : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0; + } + /** + * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Node.js when you `console.log` an instance of this class. + * + * @param _depth - The current depth + * @param options - The options passed to `util.inspect` + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @returns A string representation of the error + */ + [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) { + return inspect(inspectableError(this), options); + } + /** + * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Deno when you `console.log` an instance of this class. + * + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @param options - The options passed to `Deno.inspect` + * @returns A string representation of the error + */ + [/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) { + return inspect(inspectableError(this), options); + } + }; + __typeError = (msg) => { + throw TypeError(msg); + }; + __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); + __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); + __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); + __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); + __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); + EventSource = class extends EventTarget { + constructor(url2, eventSourceInitDict) { + var _a2, _b; + super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url2), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => { + var _a22; + __privateGet(this, _parser).reset(); + const { body, redirected, status, headers } = response; + if (status === 204) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close(); + return; + } + if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status); + return; + } + if (!(headers.get("content-type") || "").startsWith("text/event-stream")) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status); + return; + } + if (__privateGet(this, _readyState) === this.CLOSED) + return; + __privateSet(this, _readyState, this.OPEN); + const openEvent = new Event("open"); + if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close(); + return; + } + const decoder2 = new TextDecoder(), reader = body.getReader(); + let open = true; + do { + const { done, value } = await reader.read(); + value && __privateGet(this, _parser).feed(decoder2.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this)); + } while (open); + }), __privateAdd(this, _onFetchError, (err) => { + __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err)); + }), __privateAdd(this, _onEvent, (event) => { + typeof event.id == "string" && __privateSet(this, _lastEventId, event.id); + const messageEvent = new MessageEvent(event.event || "message", { + data: event.data, + origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url2).origin, + lastEventId: event.id || "" + }); + __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent); + }), __privateAdd(this, _onRetryChange, (value) => { + __privateSet(this, _reconnectInterval, value); + }), __privateAdd(this, _reconnect, () => { + __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this); + }); + try { + if (url2 instanceof URL) + __privateSet(this, _url2, url2); + else if (typeof url2 == "string") + __privateSet(this, _url2, new URL(url2, getBaseURL())); + else + throw new Error("Invalid URL"); + } catch { + throw syntaxError("An invalid or illegal string was specified"); + } + __privateSet(this, _parser, createParser({ + onEvent: __privateGet(this, _onEvent), + onRetry: __privateGet(this, _onRetryChange) + })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a2 : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this); + } + /** + * Returns the state of this EventSource object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + * + * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface, + * defined in the TypeScript `dom` library. + * + * @public + */ + get readyState() { + return __privateGet(this, _readyState); + } + /** + * Returns the URL providing the event stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + * + * @public + */ + get url() { + return __privateGet(this, _url2).href; + } + /** + * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials() { + return __privateGet(this, _withCredentials); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror() { + return __privateGet(this, _onError); + } + set onerror(value) { + __privateSet(this, _onError, value); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage() { + return __privateGet(this, _onMessage); + } + set onmessage(value) { + __privateSet(this, _onMessage, value); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen() { + return __privateGet(this, _onOpen); + } + set onopen(value) { + __privateSet(this, _onOpen, value); + } + addEventListener(type, listener, options) { + const listen = listener; + super.addEventListener(type, listen, options); + } + removeEventListener(type, listener, options) { + const listen = listener; + super.removeEventListener(type, listen, options); + } + /** + * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + * + * @public + */ + close() { + __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0)); + } + }; + _readyState = /* @__PURE__ */ new WeakMap(), _url2 = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /** + * Connect to the given URL and start receiving events + * + * @internal + */ + connect_fn = function() { + __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url2), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError)); + }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /** + * Get request options for the `fetch()` request + * + * @returns The request options + * @internal + */ + getRequestOptions_fn = function() { + var _a2; + const init = { + // [spec] Let `corsAttributeState` be `Anonymous`… + // [spec] …will have their mode set to "cors"… + mode: "cors", + redirect: "follow", + headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 }, + cache: "no-store", + signal: (_a2 = __privateGet(this, _controller)) == null ? void 0 : _a2.signal + }; + return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init; + }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /** + * Handles the process referred to in the EventSource specification as "failing a connection". + * + * @param error - The error causing the connection to fail + * @param code - The HTTP status code, if available + * @internal + */ + failConnection_fn = function(message2, code) { + var _a2; + __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED); + const errorEvent = new ErrorEvent("error", { code, message: message2 }); + (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent); + }, /** + * Schedules a reconnection attempt against the EventSource endpoint. + * + * @param message - The error causing the connection to fail + * @param code - The HTTP status code, if available + * @internal + */ + scheduleReconnect_fn = function(message2, code) { + var _a2; + if (__privateGet(this, _readyState) === this.CLOSED) + return; + __privateSet(this, _readyState, this.CONNECTING); + const errorEvent = new ErrorEvent("error", { code, message: message2 }); + (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval))); + }, _reconnect = /* @__PURE__ */ new WeakMap(), /** + * ReadyState representing an EventSource currently trying to connect + * + * @public + */ + EventSource.CONNECTING = 0, /** + * ReadyState representing an EventSource connection that is open (eg connected) + * + * @public + */ + EventSource.OPEN = 1, /** + * ReadyState representing an EventSource connection that is closed (eg disconnected) + * + * @public + */ + EventSource.CLOSED = 2; + } +}); + +// ../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js +var EventSourceParserStream; +var init_stream = __esm({ + "../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js"() { + init_dist(); + EventSourceParserStream = class extends TransformStream { + constructor({ onError, onRetry, onComment } = {}) { + let parser; + super({ + start(controller) { + parser = createParser({ + onEvent: (event) => { + controller.enqueue(event); + }, + onError(error2) { + onError === "terminate" ? controller.error(error2) : typeof onError == "function" && onError(error2); + }, + onRetry, + onComment + }); + }, + transform(chunk) { + parser.feed(chunk); + } + }); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js +function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + for (const buffer of buffers) { + buf.set(buffer, i); + i += buffer.length; + } + return buf; +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); +} +function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +function encode2(string4) { + const bytes = new Uint8Array(string4.length); + for (let i = 0; i < string4.length; i++) { + const code = string4.charCodeAt(i); + if (code > 127) { + throw new TypeError("non-ASCII string encountered in encode()"); + } + bytes[i] = code; + } + return bytes; +} +var encoder, decoder, MAX_INT32; +var init_buffer_utils = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"() { + encoder = new TextEncoder(); + decoder = new TextDecoder(); + MAX_INT32 = 2 ** 32; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js +function encodeBase64(input) { + if (Uint8Array.prototype.toBase64) { + return input.toBase64(); + } + const CHUNK_SIZE = 32768; + const arr = []; + for (let i = 0; i < input.length; i += CHUNK_SIZE) { + arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))); + } + return btoa(arr.join("")); +} +function decodeBase64(encoded) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(encoded); + } + const binary = atob(encoded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} +var init_base64 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"() { + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js +var base64url_exports = {}; +__export(base64url_exports, { + decode: () => decode2, + encode: () => encode3 +}); +function decode2(input) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { + alphabet: "base64url" + }); + } + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = decoder.decode(encoded); + } + encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); + try { + return decodeBase64(encoded); + } catch { + throw new TypeError("The input to be decoded is not correctly encoded."); + } +} +function encode3(input) { + let unencoded = input; + if (typeof unencoded === "string") { + unencoded = encoder.encode(unencoded); + } + if (Uint8Array.prototype.toBase64) { + return unencoded.toBase64({ alphabet: "base64url", omitPadding: true }); + } + return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +} +var init_base64url = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"() { + init_buffer_utils(); + init_base64(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js +function getHashLength(hash2) { + return parseInt(hash2.name.slice(4), 10); +} +function checkHashLength(algorithm, expected) { + const actual = getHashLength(algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, "algorithm.hash"); +} +function getNamedCurve(alg) { + switch (alg) { + case "ES256": + return "P-256"; + case "ES384": + return "P-384"; + case "ES512": + return "P-521"; + default: + throw new Error("unreachable"); + } +} +function checkUsage(key, usage) { + if (usage && !key.usages.includes(usage)) { + throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); + } +} +function checkSigCryptoKey(key, alg, usage) { + switch (alg) { + case "HS256": + case "HS384": + case "HS512": { + if (!isAlgorithm(key.algorithm, "HMAC")) + throw unusable("HMAC"); + checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); + break; + } + case "RS256": + case "RS384": + case "RS512": { + if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) + throw unusable("RSASSA-PKCS1-v1_5"); + checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); + break; + } + case "PS256": + case "PS384": + case "PS512": { + if (!isAlgorithm(key.algorithm, "RSA-PSS")) + throw unusable("RSA-PSS"); + checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); + break; + } + case "Ed25519": + case "EdDSA": { + if (!isAlgorithm(key.algorithm, "Ed25519")) + throw unusable("Ed25519"); + break; + } + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": { + if (!isAlgorithm(key.algorithm, alg)) + throw unusable(alg); + break; + } + case "ES256": + case "ES384": + case "ES512": { + if (!isAlgorithm(key.algorithm, "ECDSA")) + throw unusable("ECDSA"); + const expected = getNamedCurve(alg); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, "algorithm.namedCurve"); + break; + } + default: + throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); +} +function checkEncCryptoKey(key, alg, usage) { + switch (alg) { + case "A128GCM": + case "A192GCM": + case "A256GCM": { + if (!isAlgorithm(key.algorithm, "AES-GCM")) + throw unusable("AES-GCM"); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, "algorithm.length"); + break; + } + case "A128KW": + case "A192KW": + case "A256KW": { + if (!isAlgorithm(key.algorithm, "AES-KW")) + throw unusable("AES-KW"); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, "algorithm.length"); + break; + } + case "ECDH": { + switch (key.algorithm.name) { + case "ECDH": + case "X25519": + break; + default: + throw unusable("ECDH or X25519"); + } + break; + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": + if (!isAlgorithm(key.algorithm, "PBKDF2")) + throw unusable("PBKDF2"); + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + if (!isAlgorithm(key.algorithm, "RSA-OAEP")) + throw unusable("RSA-OAEP"); + checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1); + break; + } + default: + throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); +} +var unusable, isAlgorithm; +var init_crypto_key = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"() { + unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); + isAlgorithm = (algorithm, name) => algorithm.name === name; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js +function message(msg, actual, ...types) { + types = types.filter(Boolean); + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(", ")}, or ${last}.`; + } else if (types.length === 2) { + msg += `one of type ${types[0]} or ${types[1]}.`; + } else { + msg += `of type ${types[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } else if (typeof actual === "function" && actual.name) { + msg += ` Received function ${actual.name}`; + } else if (typeof actual === "object" && actual != null) { + if (actual.constructor?.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +var invalidKeyInput, withAlg; +var init_invalid_key_input = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"() { + invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); + withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js +var errors_exports2 = {}; +__export(errors_exports2, { + JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, + JOSEError: () => JOSEError, + JOSENotSupported: () => JOSENotSupported, + JWEDecryptionFailed: () => JWEDecryptionFailed, + JWEInvalid: () => JWEInvalid, + JWKInvalid: () => JWKInvalid, + JWKSInvalid: () => JWKSInvalid, + JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, + JWKSNoMatchingKey: () => JWKSNoMatchingKey, + JWKSTimeout: () => JWKSTimeout, + JWSInvalid: () => JWSInvalid, + JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, + JWTClaimValidationFailed: () => JWTClaimValidationFailed, + JWTExpired: () => JWTExpired, + JWTInvalid: () => JWTInvalid +}); +var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed; +var init_errors3 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"() { + JOSEError = class extends Error { + static code = "ERR_JOSE_GENERIC"; + code = "ERR_JOSE_GENERIC"; + constructor(message2, options) { + super(message2, options); + this.name = this.constructor.name; + Error.captureStackTrace?.(this, this.constructor); + } + }; + JWTClaimValidationFailed = class extends JOSEError { + static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + claim; + reason; + payload; + constructor(message2, payload, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } + }; + JWTExpired = class extends JOSEError { + static code = "ERR_JWT_EXPIRED"; + code = "ERR_JWT_EXPIRED"; + claim; + reason; + payload; + constructor(message2, payload, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } + }; + JOSEAlgNotAllowed = class extends JOSEError { + static code = "ERR_JOSE_ALG_NOT_ALLOWED"; + code = "ERR_JOSE_ALG_NOT_ALLOWED"; + }; + JOSENotSupported = class extends JOSEError { + static code = "ERR_JOSE_NOT_SUPPORTED"; + code = "ERR_JOSE_NOT_SUPPORTED"; + }; + JWEDecryptionFailed = class extends JOSEError { + static code = "ERR_JWE_DECRYPTION_FAILED"; + code = "ERR_JWE_DECRYPTION_FAILED"; + constructor(message2 = "decryption operation failed", options) { + super(message2, options); + } + }; + JWEInvalid = class extends JOSEError { + static code = "ERR_JWE_INVALID"; + code = "ERR_JWE_INVALID"; + }; + JWSInvalid = class extends JOSEError { + static code = "ERR_JWS_INVALID"; + code = "ERR_JWS_INVALID"; + }; + JWTInvalid = class extends JOSEError { + static code = "ERR_JWT_INVALID"; + code = "ERR_JWT_INVALID"; + }; + JWKInvalid = class extends JOSEError { + static code = "ERR_JWK_INVALID"; + code = "ERR_JWK_INVALID"; + }; + JWKSInvalid = class extends JOSEError { + static code = "ERR_JWKS_INVALID"; + code = "ERR_JWKS_INVALID"; + }; + JWKSNoMatchingKey = class extends JOSEError { + static code = "ERR_JWKS_NO_MATCHING_KEY"; + code = "ERR_JWKS_NO_MATCHING_KEY"; + constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { + super(message2, options); + } + }; + JWKSMultipleMatchingKeys = class extends JOSEError { + [Symbol.asyncIterator]; + static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { + super(message2, options); + } + }; + JWKSTimeout = class extends JOSEError { + static code = "ERR_JWKS_TIMEOUT"; + code = "ERR_JWKS_TIMEOUT"; + constructor(message2 = "request timed out", options) { + super(message2, options); + } + }; + JWSSignatureVerificationFailed = class extends JOSEError { + static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + constructor(message2 = "signature verification failed", options) { + super(message2, options); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js +function assertCryptoKey(key) { + if (!isCryptoKey(key)) { + throw new Error("CryptoKey instance expected"); + } +} +var isCryptoKey, isKeyObject, isKeyLike; +var init_is_key_like = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"() { + isCryptoKey = (key) => { + if (key?.[Symbol.toStringTag] === "CryptoKey") + return true; + try { + return key instanceof CryptoKey; + } catch { + return false; + } + }; + isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; + isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js +function cekLength(alg) { + switch (alg) { + case "A128GCM": + return 128; + case "A192GCM": + return 192; + case "A256GCM": + case "A128CBC-HS256": + return 256; + case "A192CBC-HS384": + return 384; + case "A256CBC-HS512": + return 512; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +function checkCekLength(cek, expected) { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } +} +function ivBitLength(alg) { + switch (alg) { + case "A128GCM": + case "A128GCMKW": + case "A192GCM": + case "A192GCMKW": + case "A256GCM": + case "A256GCMKW": + return 96; + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + return 128; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } +} +function checkIvLength(enc, iv) { + if (iv.length << 3 !== ivBitLength(enc)) { + throw new JWEInvalid("Invalid Initialization Vector length"); + } +} +async function cbcKeySetup(enc, cek, usage) { + if (!(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "Uint8Array")); + } + const keySize = parseInt(enc.slice(1, 4), 10); + const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]); + const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: "HMAC" + }, false, ["sign"]); + return { encKey, macKey, keySize }; +} +async function cbcHmacTag(macKey, macData, keySize) { + return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); +} +async function cbcEncrypt(enc, plaintext, cek, iv, aad) { + const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "encrypt"); + const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ + iv, + name: "AES-CBC" + }, encKey, plaintext)); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const tag2 = await cbcHmacTag(macKey, macData, keySize); + return { ciphertext, tag: tag2, iv }; +} +async function timingSafeEqual(a, b) { + if (!(a instanceof Uint8Array)) { + throw new TypeError("First argument must be a buffer"); + } + if (!(b instanceof Uint8Array)) { + throw new TypeError("Second argument must be a buffer"); + } + const algorithm = { name: "HMAC", hash: "SHA-256" }; + const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]); + const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a)); + const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b)); + let out = 0; + let i = -1; + while (++i < 32) { + out |= aHmac[i] ^ bHmac[i]; + } + return out === 0; +} +async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) { + const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "decrypt"); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const expectedTag = await cbcHmacTag(macKey, macData, keySize); + let macCheckPassed; + try { + macCheckPassed = await timingSafeEqual(tag2, expectedTag); + } catch { + } + if (!macCheckPassed) { + throw new JWEDecryptionFailed(); + } + let plaintext; + try { + plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); + } catch { + } + if (!plaintext) { + throw new JWEDecryptionFailed(); + } + return plaintext; +} +async function gcmEncrypt(enc, plaintext, cek, iv, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); + } else { + checkEncCryptoKey(cek, enc, "encrypt"); + encKey = cek; + } + const encrypted = new Uint8Array(await crypto.subtle.encrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, plaintext)); + const tag2 = encrypted.slice(-16); + const ciphertext = encrypted.slice(0, -16); + return { ciphertext, tag: tag2, iv }; +} +async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); + } else { + checkEncCryptoKey(cek, enc, "decrypt"); + encKey = cek; + } + try { + return new Uint8Array(await crypto.subtle.decrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, concat(ciphertext, tag2))); + } catch { + throw new JWEDecryptionFailed(); + } +} +async function encrypt(enc, plaintext, cek, iv, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + } + if (iv) { + checkIvLength(enc, iv); + } else { + iv = generateIv(enc); + } + switch (enc) { + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc.slice(-3), 10)); + } + return cbcEncrypt(enc, plaintext, cek, iv, aad); + case "A128GCM": + case "A192GCM": + case "A256GCM": + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); + } + return gcmEncrypt(enc, plaintext, cek, iv, aad); + default: + throw new JOSENotSupported(unsupportedEnc); + } +} +async function decrypt(enc, cek, ciphertext, iv, tag2, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + } + if (!iv) { + throw new JWEInvalid("JWE Initialization Vector missing"); + } + if (!tag2) { + throw new JWEInvalid("JWE Authentication Tag missing"); + } + checkIvLength(enc, iv); + switch (enc) { + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(-3), 10)); + return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad); + case "A128GCM": + case "A192GCM": + case "A256GCM": + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); + return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad); + default: + throw new JOSENotSupported(unsupportedEnc); + } +} +var generateCek, generateIv, unsupportedEnc; +var init_content_encryption = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js"() { + init_buffer_utils(); + init_crypto_key(); + init_invalid_key_input(); + init_errors3(); + init_is_key_like(); + generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3)); + generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3)); + unsupportedEnc = "Unsupported JWE Content Encryption Algorithm"; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js +function assertNotSet(value, name) { + if (value) { + throw new TypeError(`${name} can only be called once`); + } +} +function decodeBase64url(value, label, ErrorClass) { + try { + return decode2(value); + } catch { + throw new ErrorClass(`Failed to base64url decode the ${label}`); + } +} +async function digest(algorithm, data) { + const subtleDigest = `SHA-${algorithm.slice(-3)}`; + return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); +} +var unprotected; +var init_helpers = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"() { + init_base64url(); + unprotected = /* @__PURE__ */ Symbol(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js +function isObject2(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { + return false; + } + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; +} +function isDisjoint(...headers) { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +} +var isObjectLike, isJWK, isPrivateJWK, isPublicJWK, isSecretJWK; +var init_type_checks = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"() { + isObjectLike = (value) => typeof value === "object" && value !== null; + isJWK = (key) => isObject2(key) && typeof key.kty === "string"; + isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); + isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; + isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js +function checkKeySize(key, alg) { + if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg}`); + } +} +function getCryptoKey(key, alg, usage) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]); + } + checkEncCryptoKey(key, alg, usage); + return key; +} +async function wrap(alg, key, cek) { + const cryptoKey = await getCryptoKey(key, alg, "wrapKey"); + checkKeySize(cryptoKey, alg); + const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); + return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); +} +async function unwrap(alg, key, encryptedKey) { + const cryptoKey = await getCryptoKey(key, alg, "unwrapKey"); + checkKeySize(cryptoKey, alg); + const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); + return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); +} +var init_aeskw = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js"() { + init_crypto_key(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js +function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +async function concatKdf(Z, L, OtherInfo) { + const dkLen = L >> 3; + const hashLen = 32; + const reps = Math.ceil(dkLen / hashLen); + const dk = new Uint8Array(reps * hashLen); + for (let i = 1; i <= reps; i++) { + const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length); + hashInput.set(uint32be(i), 0); + hashInput.set(Z, 4); + hashInput.set(OtherInfo, 4 + Z.length); + const hashResult = await digest("sha256", hashInput); + dk.set(hashResult, (i - 1) * hashLen); + } + return dk.slice(0, dkLen); +} +async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { + checkEncCryptoKey(publicKey, "ECDH"); + checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); + const algorithmID = lengthAndInput(encode2(algorithm)); + const partyUInfo = lengthAndInput(apu); + const partyVInfo = lengthAndInput(apv); + const suppPubInfo = uint32be(keyLength); + const suppPrivInfo = new Uint8Array(); + const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); + const Z = new Uint8Array(await crypto.subtle.deriveBits({ + name: publicKey.algorithm.name, + public: publicKey + }, privateKey, getEcdhBitLength(publicKey))); + return concatKdf(Z, keyLength, otherInfo); +} +function getEcdhBitLength(publicKey) { + if (publicKey.algorithm.name === "X25519") { + return 256; + } + return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3; +} +function allowed(key) { + switch (key.algorithm.namedCurve) { + case "P-256": + case "P-384": + case "P-521": + return true; + default: + return key.algorithm.name === "X25519"; + } +} +var init_ecdhes = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js"() { + init_buffer_utils(); + init_crypto_key(); + init_helpers(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js +function getCryptoKey2(key, alg) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey("raw", key, "PBKDF2", false, [ + "deriveBits" + ]); + } + checkEncCryptoKey(key, alg, "deriveBits"); + return key; +} +async function deriveKey2(p2s, alg, p2c, key) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); + } + const salt = concatSalt(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10); + const subtleAlg = { + hash: `SHA-${alg.slice(8, 11)}`, + iterations: p2c, + name: "PBKDF2", + salt + }; + const cryptoKey = await getCryptoKey2(key, alg); + return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); +} +async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) { + const derived = await deriveKey2(p2s, alg, p2c, key); + const encryptedKey = await wrap(alg.slice(-6), derived, cek); + return { encryptedKey, p2c, p2s: encode3(p2s) }; +} +async function unwrap2(alg, key, encryptedKey, p2c, p2s) { + const derived = await deriveKey2(p2s, alg, p2c, key); + return unwrap(alg.slice(-6), derived, encryptedKey); +} +var concatSalt; +var init_pbes2kw = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js"() { + init_base64url(); + init_aeskw(); + init_crypto_key(); + init_buffer_utils(); + init_errors3(); + concatSalt = (alg, p2sInput) => concat(encode2(alg), Uint8Array.of(0), p2sInput); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js +function checkKeyLength(alg, key) { + if (alg.startsWith("RS") || alg.startsWith("PS")) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength !== "number" || modulusLength < 2048) { + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + } + } +} +function subtleAlgorithm(alg, algorithm) { + const hash2 = `SHA-${alg.slice(-3)}`; + switch (alg) { + case "HS256": + case "HS384": + case "HS512": + return { hash: hash2, name: "HMAC" }; + case "PS256": + case "PS384": + case "PS512": + return { hash: hash2, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 }; + case "RS256": + case "RS384": + case "RS512": + return { hash: hash2, name: "RSASSA-PKCS1-v1_5" }; + case "ES256": + case "ES384": + case "ES512": + return { hash: hash2, name: "ECDSA", namedCurve: algorithm.namedCurve }; + case "Ed25519": + case "EdDSA": + return { name: "Ed25519" }; + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + return { name: alg }; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} +async function getSigKey(alg, key, usage) { + if (key instanceof Uint8Array) { + if (!alg.startsWith("HS")) { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); + } + checkSigCryptoKey(key, alg, usage); + return key; +} +async function sign(alg, key, data) { + const cryptoKey = await getSigKey(alg, key, "sign"); + checkKeyLength(alg, cryptoKey); + const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); + return new Uint8Array(signature); +} +async function verify(alg, key, signature, data) { + const cryptoKey = await getSigKey(alg, key, "verify"); + checkKeyLength(alg, cryptoKey); + const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); + try { + return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); + } catch { + return false; + } +} +var init_signing = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"() { + init_errors3(); + init_crypto_key(); + init_invalid_key_input(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js +async function encrypt2(alg, key, cek) { + checkEncCryptoKey(key, alg, "encrypt"); + checkKeyLength(alg, key); + return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg), key, cek)); +} +async function decrypt2(alg, key, encryptedKey) { + checkEncCryptoKey(key, alg, "decrypt"); + checkKeyLength(alg, key); + return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg), key, encryptedKey)); +} +var subtleAlgorithm2; +var init_rsaes = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js"() { + init_crypto_key(); + init_signing(); + init_errors3(); + subtleAlgorithm2 = (alg) => { + switch (alg) { + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + return "RSA-OAEP"; + default: + throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js +function subtleMapping(jwk) { + let algorithm; + let keyUsages; + switch (jwk.kty) { + case "AKP": { + switch (jwk.alg) { + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + algorithm = { name: jwk.alg }; + keyUsages = jwk.priv ? ["sign"] : ["verify"]; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "RSA": { + switch (jwk.alg) { + case "PS256": + case "PS384": + case "PS512": + algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RS256": + case "RS384": + case "RS512": + algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + algorithm = { + name: "RSA-OAEP", + hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` + }; + keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "EC": { + switch (jwk.alg) { + case "ES256": + case "ES384": + case "ES512": + algorithm = { + name: "ECDSA", + namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg] + }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm = { name: "ECDH", namedCurve: jwk.crv }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "OKP": { + switch (jwk.alg) { + case "Ed25519": + case "EdDSA": + algorithm = { name: "Ed25519" }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm = { name: jwk.crv }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); + } + return { algorithm, keyUsages }; +} +async function jwkToKey(jwk) { + if (!jwk.alg) { + throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); + } + const { algorithm, keyUsages } = subtleMapping(jwk); + const keyData = { ...jwk }; + if (keyData.kty !== "AKP") { + delete keyData.alg; + } + delete keyData.use; + return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); +} +var unsupportedAlg; +var init_jwk_to_key = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"() { + init_errors3(); + unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value'; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js +async function normalizeKey(key, alg) { + if (key instanceof Uint8Array) { + return key; + } + if (isCryptoKey(key)) { + return key; + } + if (isKeyObject(key)) { + if (key.type === "secret") { + return key.export(); + } + if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") { + try { + return handleKeyObject(key, alg); + } catch (err) { + if (err instanceof TypeError) { + throw err; + } + } + } + let jwk = key.export({ format: "jwk" }); + return handleJWK(key, jwk, alg); + } + if (isJWK(key)) { + if (key.k) { + return decode2(key.k); + } + return handleJWK(key, key, alg, true); + } + throw new Error("unreachable"); +} +var unusableForAlg, cache, handleJWK, handleKeyObject; +var init_normalize_key = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"() { + init_type_checks(); + init_base64url(); + init_jwk_to_key(); + init_is_key_like(); + unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; + handleJWK = async (key, jwk, alg, freeze = false) => { + cache ||= /* @__PURE__ */ new WeakMap(); + let cached2 = cache.get(key); + if (cached2?.[alg]) { + return cached2[alg]; + } + const cryptoKey = await jwkToKey({ ...jwk, alg }); + if (freeze) + Object.freeze(key); + if (!cached2) { + cache.set(key, { [alg]: cryptoKey }); + } else { + cached2[alg] = cryptoKey; + } + return cryptoKey; + }; + handleKeyObject = (keyObject, alg) => { + cache ||= /* @__PURE__ */ new WeakMap(); + let cached2 = cache.get(keyObject); + if (cached2?.[alg]) { + return cached2[alg]; + } + const isPublic = keyObject.type === "public"; + const extractable = isPublic ? true : false; + let cryptoKey; + if (keyObject.asymmetricKeyType === "x25519") { + switch (alg) { + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + break; + default: + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); + } + if (keyObject.asymmetricKeyType === "ed25519") { + if (alg !== "EdDSA" && alg !== "Ed25519") { + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? "verify" : "sign" + ]); + } + switch (keyObject.asymmetricKeyType) { + case "ml-dsa-44": + case "ml-dsa-65": + case "ml-dsa-87": { + if (alg !== keyObject.asymmetricKeyType.toUpperCase()) { + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? "verify" : "sign" + ]); + } + } + if (keyObject.asymmetricKeyType === "rsa") { + let hash2; + switch (alg) { + case "RSA-OAEP": + hash2 = "SHA-1"; + break; + case "RS256": + case "PS256": + case "RSA-OAEP-256": + hash2 = "SHA-256"; + break; + case "RS384": + case "PS384": + case "RSA-OAEP-384": + hash2 = "SHA-384"; + break; + case "RS512": + case "PS512": + case "RSA-OAEP-512": + hash2 = "SHA-512"; + break; + default: + throw new TypeError(unusableForAlg); + } + if (alg.startsWith("RSA-OAEP")) { + return keyObject.toCryptoKey({ + name: "RSA-OAEP", + hash: hash2 + }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); + } + cryptoKey = keyObject.toCryptoKey({ + name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", + hash: hash2 + }, extractable, [isPublic ? "verify" : "sign"]); + } + if (keyObject.asymmetricKeyType === "ec") { + const nist = /* @__PURE__ */ new Map([ + ["prime256v1", "P-256"], + ["secp384r1", "P-384"], + ["secp521r1", "P-521"] + ]); + const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); + if (!namedCurve) { + throw new TypeError(unusableForAlg); + } + const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; + if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) { + cryptoKey = keyObject.toCryptoKey({ + name: "ECDSA", + namedCurve + }, extractable, [isPublic ? "verify" : "sign"]); + } + if (alg.startsWith("ECDH-ES")) { + cryptoKey = keyObject.toCryptoKey({ + name: "ECDH", + namedCurve + }, extractable, isPublic ? [] : ["deriveBits"]); + } + } + if (!cryptoKey) { + throw new TypeError(unusableForAlg); + } + if (!cached2) { + cache.set(keyObject, { [alg]: cryptoKey }); + } else { + cached2[alg] = cryptoKey; + } + return cryptoKey; + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js +function parsePKCS8Header(state) { + expectTag(state, 48, "Invalid PKCS#8 structure"); + parseLength(state); + expectTag(state, 2, "Expected version field"); + const verLen = parseLength(state); + state.pos += verLen; + expectTag(state, 48, "Expected algorithm identifier"); + const algIdLen = parseLength(state); + const algIdStart = state.pos; + return { algIdStart, algIdLength: algIdLen }; +} +function parseSPKIHeader(state) { + expectTag(state, 48, "Invalid SPKI structure"); + parseLength(state); + expectTag(state, 48, "Expected algorithm identifier"); + const algIdLen = parseLength(state); + const algIdStart = state.pos; + return { algIdStart, algIdLength: algIdLen }; +} +function spkiFromX509(buf) { + const state = createASN1State(buf); + expectTag(state, 48, "Invalid certificate structure"); + parseLength(state); + expectTag(state, 48, "Invalid tbsCertificate structure"); + parseLength(state); + if (buf[state.pos] === 160) { + skipElement(state, 6); + } else { + skipElement(state, 5); + } + const spkiStart = state.pos; + expectTag(state, 48, "Invalid SPKI structure"); + const spkiContentLen = parseLength(state); + return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart)); +} +function extractX509SPKI(x509) { + const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g); + return spkiFromX509(derBytes); +} +var formatPEM, genericExport, toSPKI, toPKCS8, bytesEqual, createASN1State, parseLength, skipElement, expectTag, getSubarray, parseAlgorithmOID, parseECAlgorithmIdentifier, genericImport, processPEMData, fromPKCS8, fromSPKI, fromX509; +var init_asn1 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"() { + init_invalid_key_input(); + init_base64(); + init_errors3(); + init_is_key_like(); + formatPEM = (b64, descriptor) => { + const newlined = (b64.match(/.{1,64}/g) || []).join("\n"); + return `-----BEGIN ${descriptor}----- +${newlined} +-----END ${descriptor}-----`; + }; + genericExport = async (keyType, keyFormat, key) => { + if (isKeyObject(key)) { + if (key.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return key.export({ format: "pem", type: keyFormat }); + } + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject")); + } + if (!key.extractable) { + throw new TypeError("CryptoKey is not extractable"); + } + if (key.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); + }; + toSPKI = (key) => genericExport("public", "spki", key); + toPKCS8 = (key) => genericExport("private", "pkcs8", key); + bytesEqual = (a, b) => { + if (a.byteLength !== b.length) + return false; + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) + return false; + } + return true; + }; + createASN1State = (data) => ({ data, pos: 0 }); + parseLength = (state) => { + const first = state.data[state.pos++]; + if (first & 128) { + const lengthOfLen = first & 127; + let length = 0; + for (let i = 0; i < lengthOfLen; i++) { + length = length << 8 | state.data[state.pos++]; + } + return length; + } + return first; + }; + skipElement = (state, count = 1) => { + if (count <= 0) + return; + state.pos++; + const length = parseLength(state); + state.pos += length; + if (count > 1) { + skipElement(state, count - 1); + } + }; + expectTag = (state, expectedTag, errorMessage) => { + if (state.data[state.pos++] !== expectedTag) { + throw new Error(errorMessage); + } + }; + getSubarray = (state, length) => { + const result = state.data.subarray(state.pos, state.pos + length); + state.pos += length; + return result; + }; + parseAlgorithmOID = (state) => { + expectTag(state, 6, "Expected algorithm OID"); + const oidLen = parseLength(state); + return getSubarray(state, oidLen); + }; + parseECAlgorithmIdentifier = (state) => { + const algOid = parseAlgorithmOID(state); + if (bytesEqual(algOid, [43, 101, 110])) { + return "X25519"; + } + if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) { + throw new Error("Unsupported key algorithm"); + } + expectTag(state, 6, "Expected curve OID"); + const curveOidLen = parseLength(state); + const curveOid = getSubarray(state, curveOidLen); + for (const { name, oid } of [ + { name: "P-256", oid: [42, 134, 72, 206, 61, 3, 1, 7] }, + { name: "P-384", oid: [43, 129, 4, 0, 34] }, + { name: "P-521", oid: [43, 129, 4, 0, 35] } + ]) { + if (bytesEqual(curveOid, oid)) { + return name; + } + } + throw new Error("Unsupported named curve"); + }; + genericImport = async (keyFormat, keyData, alg, options) => { + let algorithm; + let keyUsages; + const isPublic = keyFormat === "spki"; + const getSigUsages = () => isPublic ? ["verify"] : ["sign"]; + const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"]; + switch (alg) { + case "PS256": + case "PS384": + case "PS512": + algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` }; + keyUsages = getSigUsages(); + break; + case "RS256": + case "RS384": + case "RS512": + algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` }; + keyUsages = getSigUsages(); + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + algorithm = { + name: "RSA-OAEP", + hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}` + }; + keyUsages = getEncUsages(); + break; + case "ES256": + case "ES384": + case "ES512": { + const curveMap = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; + algorithm = { name: "ECDSA", namedCurve: curveMap[alg] }; + keyUsages = getSigUsages(); + break; + } + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + try { + const namedCurve = options.getNamedCurve(keyData); + algorithm = namedCurve === "X25519" ? { name: "X25519" } : { name: "ECDH", namedCurve }; + } catch (cause) { + throw new JOSENotSupported("Invalid or unsupported key format"); + } + keyUsages = isPublic ? [] : ["deriveBits"]; + break; + } + case "Ed25519": + case "EdDSA": + algorithm = { name: "Ed25519" }; + keyUsages = getSigUsages(); + break; + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + algorithm = { name: alg }; + keyUsages = getSigUsages(); + break; + default: + throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); + } + return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages); + }; + processPEMData = (pem, pattern) => { + return decodeBase64(pem.replace(pattern, "")); + }; + fromPKCS8 = (pem, alg, options) => { + const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g); + let opts = options; + if (alg?.startsWith?.("ECDH-ES")) { + opts ||= {}; + opts.getNamedCurve = (keyData2) => { + const state = createASN1State(keyData2); + parsePKCS8Header(state); + return parseECAlgorithmIdentifier(state); + }; + } + return genericImport("pkcs8", keyData, alg, opts); + }; + fromSPKI = (pem, alg, options) => { + const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g); + let opts = options; + if (alg?.startsWith?.("ECDH-ES")) { + opts ||= {}; + opts.getNamedCurve = (keyData2) => { + const state = createASN1State(keyData2); + parseSPKIHeader(state); + return parseECAlgorithmIdentifier(state); + }; + } + return genericImport("spki", keyData, alg, opts); + }; + fromX509 = (pem, alg, options) => { + let spki; + try { + spki = extractX509SPKI(pem); + } catch (cause) { + throw new TypeError("Failed to parse the X.509 certificate", { cause }); + } + return fromSPKI(formatPEM(encodeBase64(spki), "PUBLIC KEY"), alg, options); + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js +async function importSPKI(spki, alg, options) { + if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) { + throw new TypeError('"spki" must be SPKI formatted string'); + } + return fromSPKI(spki, alg, options); +} +async function importX509(x509, alg, options) { + if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) { + throw new TypeError('"x509" must be X.509 formatted string'); + } + return fromX509(x509, alg, options); +} +async function importPKCS8(pkcs8, alg, options) { + if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) { + throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); + } + return fromPKCS8(pkcs8, alg, options); +} +async function importJWK(jwk, alg, options) { + if (!isObject2(jwk)) { + throw new TypeError("JWK must be an object"); + } + let ext; + alg ??= jwk.alg; + ext ??= options?.extractable ?? jwk.ext; + switch (jwk.kty) { + case "oct": + if (typeof jwk.k !== "string" || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + return decode2(jwk.k); + case "RSA": + if ("oth" in jwk && jwk.oth !== void 0) { + throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + return jwkToKey({ ...jwk, alg, ext }); + case "AKP": { + if (typeof jwk.alg !== "string" || !jwk.alg) { + throw new TypeError('missing "alg" (Algorithm) Parameter value'); + } + if (alg !== void 0 && alg !== jwk.alg) { + throw new TypeError("JWK alg and alg option value mismatch"); + } + return jwkToKey({ ...jwk, ext }); + } + case "EC": + case "OKP": + return jwkToKey({ ...jwk, alg, ext }); + default: + throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + } +} +var init_import = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"() { + init_base64url(); + init_asn1(); + init_jwk_to_key(); + init_errors3(); + init_type_checks(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js +async function keyToJWK(key) { + if (isKeyObject(key)) { + if (key.type === "secret") { + key = key.export(); + } else { + return key.export({ format: "jwk" }); + } + } + if (key instanceof Uint8Array) { + return { + kty: "oct", + k: encode3(key) + }; + } + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array")); + } + if (!key.extractable) { + throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); + } + const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key); + if (jwk.kty === "AKP") { + ; + jwk.alg = alg; + } + return jwk; +} +var init_key_to_jwk = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js"() { + init_invalid_key_input(); + init_base64url(); + init_is_key_like(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js +async function exportSPKI(key) { + return toSPKI(key); +} +async function exportPKCS8(key) { + return toPKCS8(key); +} +async function exportJWK(key) { + return keyToJWK(key); +} +var init_export = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js"() { + init_asn1(); + init_key_to_jwk(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js +async function wrap3(alg, key, cek, iv) { + const jweAlgorithm = alg.slice(0, 7); + const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array()); + return { + encryptedKey: wrapped.ciphertext, + iv: encode3(wrapped.iv), + tag: encode3(wrapped.tag) + }; +} +async function unwrap3(alg, key, encryptedKey, iv, tag2) { + const jweAlgorithm = alg.slice(0, 7); + return decrypt(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array()); +} +var init_aesgcmkw = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js"() { + init_content_encryption(); + init_base64url(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js +function assertEncryptedKey(encryptedKey) { + if (encryptedKey === void 0) + throw new JWEInvalid("JWE Encrypted Key missing"); +} +async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { + switch (alg) { + case "dir": { + if (encryptedKey !== void 0) + throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); + return key; + } + case "ECDH-ES": + if (encryptedKey !== void 0) + throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + if (!isObject2(joseHeader.epk)) + throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + assertCryptoKey(key); + if (!allowed(key)) + throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); + const epk = await importJWK(joseHeader.epk, alg); + assertCryptoKey(epk); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== void 0) { + if (typeof joseHeader.apu !== "string") + throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid); + } + if (joseHeader.apv !== void 0) { + if (typeof joseHeader.apv !== "string") + throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid); + } + const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg === "ECDH-ES") + return sharedSecret; + assertEncryptedKey(encryptedKey); + return unwrap(alg.slice(-6), sharedSecret, encryptedKey); + } + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + assertEncryptedKey(encryptedKey); + assertCryptoKey(key); + return decrypt2(alg, key, encryptedKey); + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": { + assertEncryptedKey(encryptedKey); + if (typeof joseHeader.p2c !== "number") + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = options?.maxPBES2Count || 1e4; + if (joseHeader.p2c > p2cLimit) + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== "string") + throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid); + return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s); + } + case "A128KW": + case "A192KW": + case "A256KW": { + assertEncryptedKey(encryptedKey); + return unwrap(alg, key, encryptedKey); + } + case "A128GCMKW": + case "A192GCMKW": + case "A256GCMKW": { + assertEncryptedKey(encryptedKey); + if (typeof joseHeader.iv !== "string") + throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== "string") + throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid); + let tag2; + tag2 = decodeBase64url(joseHeader.tag, "tag", JWEInvalid); + return unwrap3(alg, key, encryptedKey, iv, tag2); + } + default: { + throw new JOSENotSupported(unsupportedAlgHeader); + } + } +} +async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + switch (alg) { + case "dir": { + cek = key; + break; + } + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + assertCryptoKey(key); + if (!allowed(key)) { + throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); + } + const { apu, apv } = providedParameters; + let ephemeralKey; + if (providedParameters.epk) { + ephemeralKey = await normalizeKey(providedParameters.epk, alg); + } else { + ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey; + } + const { x, y, crv, kty } = await exportJWK(ephemeralKey); + const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x, crv, kty } }; + if (kty === "EC") + parameters.epk.y = y; + if (apu) + parameters.apu = encode3(apu); + if (apv) + parameters.apv = encode3(apv); + if (alg === "ECDH-ES") { + cek = sharedSecret; + break; + } + cek = providedCek || generateCek(enc); + const kwAlg = alg.slice(-6); + encryptedKey = await wrap(kwAlg, sharedSecret, cek); + break; + } + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + cek = providedCek || generateCek(enc); + assertCryptoKey(key); + encryptedKey = await encrypt2(alg, key, cek); + break; + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": { + cek = providedCek || generateCek(enc); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s)); + break; + } + case "A128KW": + case "A192KW": + case "A256KW": { + cek = providedCek || generateCek(enc); + encryptedKey = await wrap(alg, key, cek); + break; + } + case "A128GCMKW": + case "A192GCMKW": + case "A256GCMKW": { + cek = providedCek || generateCek(enc); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv)); + break; + } + default: { + throw new JOSENotSupported(unsupportedAlgHeader); + } + } + return { cek, encryptedKey, parameters }; +} +var unsupportedAlgHeader; +var init_key_management = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js"() { + init_aeskw(); + init_ecdhes(); + init_pbes2kw(); + init_rsaes(); + init_base64url(); + init_normalize_key(); + init_errors3(); + init_helpers(); + init_content_encryption(); + init_import(); + init_export(); + init_type_checks(); + init_aesgcmkw(); + init_is_key_like(); + unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value'; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === void 0) { + return /* @__PURE__ */ new Set(); + } + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== void 0) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + } + if (joseHeader[parameter] === void 0) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} +var init_validate_crit = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"() { + init_errors3(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js +function validateAlgorithms(option, algorithms) { + if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s3) => typeof s3 !== "string"))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return void 0; + } + return new Set(algorithms); +} +var init_validate_algorithms = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"() { + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js +function checkKeyType(alg, key, usage) { + switch (alg.substring(0, 2)) { + case "A1": + case "A2": + case "di": + case "HS": + case "PB": + symmetricTypeCheck(alg, key, usage); + break; + default: + asymmetricTypeCheck(alg, key, usage); + } +} +var tag, jwkMatchesOp, symmetricTypeCheck, asymmetricTypeCheck; +var init_check_key_type = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"() { + init_invalid_key_input(); + init_is_key_like(); + init_type_checks(); + tag = (key) => key?.[Symbol.toStringTag]; + jwkMatchesOp = (alg, key, usage) => { + if (key.use !== void 0) { + let expected; + switch (usage) { + case "sign": + case "verify": + expected = "sig"; + break; + case "encrypt": + case "decrypt": + expected = "enc"; + break; + } + if (key.use !== expected) { + throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); + } + } + if (key.alg !== void 0 && key.alg !== alg) { + throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); + } + if (Array.isArray(key.key_ops)) { + let expectedKeyOp; + switch (true) { + case (usage === "sign" || usage === "verify"): + case alg === "dir": + case alg.includes("CBC-HS"): + expectedKeyOp = usage; + break; + case alg.startsWith("PBES2"): + expectedKeyOp = "deriveBits"; + break; + case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg): + if (!alg.includes("GCM") && alg.endsWith("KW")) { + expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; + } else { + expectedKeyOp = usage; + } + break; + case (usage === "encrypt" && alg.startsWith("RSA")): + expectedKeyOp = "wrapKey"; + break; + case usage === "decrypt": + expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits"; + break; + } + if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { + throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); + } + } + return true; + }; + symmetricTypeCheck = (alg, key, usage) => { + if (key instanceof Uint8Array) + return; + if (isJWK(key)) { + if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); + } + if (!isKeyLike(key)) { + throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); + } + if (key.type !== "secret") { + throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); + } + }; + asymmetricTypeCheck = (alg, key, usage) => { + if (isJWK(key)) { + switch (usage) { + case "decrypt": + case "sign": + if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a private JWK`); + case "encrypt": + case "verify": + if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a public JWK`); + } + } + if (!isKeyLike(key)) { + throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + if (key.type === "secret") { + throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); + } + if (key.type === "public") { + switch (usage) { + case "sign": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); + case "decrypt": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); + } + } + if (key.type === "private") { + switch (usage) { + case "verify": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); + case "encrypt": + throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); + } + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js +function supported(name) { + if (typeof globalThis[name] === "undefined") { + throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`); + } +} +async function compress(input) { + supported("CompressionStream"); + const cs = new CompressionStream("deflate-raw"); + const writer = cs.writable.getWriter(); + writer.write(input).catch(() => { + }); + writer.close().catch(() => { + }); + const chunks = []; + const reader = cs.readable.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) + break; + chunks.push(value); + } + return concat(...chunks); +} +async function decompress(input, maxLength) { + supported("DecompressionStream"); + const ds = new DecompressionStream("deflate-raw"); + const writer = ds.writable.getWriter(); + writer.write(input).catch(() => { + }); + writer.close().catch(() => { + }); + const chunks = []; + let length = 0; + const reader = ds.readable.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) + break; + chunks.push(value); + length += value.byteLength; + if (maxLength !== Infinity && length > maxLength) { + throw new JWEInvalid("Decompressed plaintext exceeded the configured limit"); + } + } + return concat(...chunks); +} +var init_deflate = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js"() { + init_errors3(); + init_buffer_utils(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js +async function flattenedDecrypt(jwe, key, options) { + if (!isObject2(jwe)) { + throw new JWEInvalid("Flattened JWE must be an object"); + } + if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { + throw new JWEInvalid("JOSE Header missing"); + } + if (jwe.iv !== void 0 && typeof jwe.iv !== "string") { + throw new JWEInvalid("JWE Initialization Vector incorrect type"); + } + if (typeof jwe.ciphertext !== "string") { + throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); + } + if (jwe.tag !== void 0 && typeof jwe.tag !== "string") { + throw new JWEInvalid("JWE Authentication Tag incorrect type"); + } + if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { + throw new JWEInvalid("JWE Protected Header incorrect type"); + } + if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { + throw new JWEInvalid("JWE Encrypted Key incorrect type"); + } + if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { + throw new JWEInvalid("JWE AAD incorrect type"); + } + if (jwe.header !== void 0 && !isObject2(jwe.header)) { + throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); + } + if (jwe.unprotected !== void 0 && !isObject2(jwe.unprotected)) { + throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader2 = decode2(jwe.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader2)); + } catch { + throw new JWEInvalid("JWE Protected Header is invalid"); + } + } + if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { + throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected + }; + validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader); + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + } + if (joseHeader.zip !== void 0 && !parsedProt?.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); + } + const { alg, enc } = joseHeader; + if (typeof alg !== "string" || !alg) { + throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); + } + if (typeof enc !== "string" || !enc) { + throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); + } + const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { + throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== void 0) { + encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid); + } + let resolvedKey = false; + if (typeof key === "function") { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + checkKeyType(alg === "dir" ? enc : alg, key, "decrypt"); + const k = await normalizeKey(key, alg); + let cek; + try { + cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options); + } catch (err) { + if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { + throw err; + } + cek = generateCek(enc); + } + let iv; + let tag2; + if (jwe.iv !== void 0) { + iv = decodeBase64url(jwe.iv, "iv", JWEInvalid); + } + if (jwe.tag !== void 0) { + tag2 = decodeBase64url(jwe.tag, "tag", JWEInvalid); + } + const protectedHeader = jwe.protected !== void 0 ? encode2(jwe.protected) : new Uint8Array(); + let additionalData; + if (jwe.aad !== void 0) { + additionalData = concat(protectedHeader, encode2("."), encode2(jwe.aad)); + } else { + additionalData = protectedHeader; + } + const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid); + const plaintext = await decrypt(enc, cek, ciphertext, iv, tag2, additionalData); + const result = { plaintext }; + if (joseHeader.zip === "DEF") { + const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4; + if (maxDecompressedLength === 0) { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) { + throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity"); + } + result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => { + if (cause instanceof JWEInvalid) + throw cause; + throw new JWEInvalid("Failed to decompress plaintext", { cause }); + }); + } + if (jwe.protected !== void 0) { + result.protectedHeader = parsedProt; + } + if (jwe.aad !== void 0) { + result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid); + } + if (jwe.unprotected !== void 0) { + result.sharedUnprotectedHeader = jwe.unprotected; + } + if (jwe.header !== void 0) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key: k }; + } + return result; +} +var init_decrypt = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js"() { + init_base64url(); + init_content_encryption(); + init_helpers(); + init_errors3(); + init_type_checks(); + init_type_checks(); + init_key_management(); + init_buffer_utils(); + init_content_encryption(); + init_validate_crit(); + init_validate_algorithms(); + init_normalize_key(); + init_check_key_type(); + init_deflate(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js +async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = decoder.decode(jwe); + } + if (typeof jwe !== "string") { + throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split("."); + if (length !== 5) { + throw new JWEInvalid("Invalid Compact JWE"); + } + const decrypted = await flattenedDecrypt({ + ciphertext, + iv: iv || void 0, + protected: protectedHeader, + tag: tag2 || void 0, + encrypted_key: encryptedKey || void 0 + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: decrypted.key }; + } + return result; +} +var init_decrypt2 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js"() { + init_decrypt(); + init_errors3(); + init_buffer_utils(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/decrypt.js +async function generalDecrypt(jwe, key, options) { + if (!isObject2(jwe)) { + throw new JWEInvalid("General JWE must be an object"); + } + if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject2)) { + throw new JWEInvalid("JWE Recipients missing or incorrect type"); + } + if (!jwe.recipients.length) { + throw new JWEInvalid("JWE Recipients has no members"); + } + for (const recipient of jwe.recipients) { + try { + return await flattenedDecrypt({ + aad: jwe.aad, + ciphertext: jwe.ciphertext, + encrypted_key: recipient.encrypted_key, + header: recipient.header, + iv: jwe.iv, + protected: jwe.protected, + tag: jwe.tag, + unprotected: jwe.unprotected + }, key, options); + } catch { + } + } + throw new JWEDecryptionFailed(); +} +var init_decrypt3 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/decrypt.js"() { + init_decrypt(); + init_errors3(); + init_type_checks(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js +var FlattenedEncrypt; +var init_encrypt = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js"() { + init_base64url(); + init_helpers(); + init_content_encryption(); + init_key_management(); + init_errors3(); + init_type_checks(); + init_buffer_utils(); + init_validate_crit(); + init_normalize_key(); + init_check_key_type(); + init_deflate(); + FlattenedEncrypt = class { + #plaintext; + #protectedHeader; + #sharedUnprotectedHeader; + #unprotectedHeader; + #aad; + #cek; + #iv; + #keyManagementParameters; + constructor(plaintext) { + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError("plaintext must be an instance of Uint8Array"); + } + this.#plaintext = plaintext; + } + setKeyManagementParameters(parameters) { + assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); + this.#keyManagementParameters = parameters; + return this; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.#protectedHeader, "setProtectedHeader"); + this.#protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + assertNotSet(this.#sharedUnprotectedHeader, "setSharedUnprotectedHeader"); + this.#sharedUnprotectedHeader = sharedUnprotectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); + this.#unprotectedHeader = unprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this.#aad = aad; + return this; + } + setContentEncryptionKey(cek) { + assertNotSet(this.#cek, "setContentEncryptionKey"); + this.#cek = cek; + return this; + } + setInitializationVector(iv) { + assertNotSet(this.#iv, "setInitializationVector"); + this.#iv = iv; + return this; + } + async encrypt(key, options) { + if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) { + throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); + } + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) { + throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader, + ...this.#sharedUnprotectedHeader + }; + validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader); + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + } + if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); + } + const { alg, enc } = joseHeader; + if (typeof alg !== "string" || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc !== "string" || !enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) { + throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); + } + checkKeyType(alg === "dir" ? enc : alg, key, "encrypt"); + let cek; + { + let parameters; + const k = await normalizeKey(key, alg); + ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters)); + if (parameters) { + if (options && unprotected in options) { + if (!this.#unprotectedHeader) { + this.setUnprotectedHeader(parameters); + } else { + this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters }; + } + } else if (!this.#protectedHeader) { + this.setProtectedHeader(parameters); + } else { + this.#protectedHeader = { ...this.#protectedHeader, ...parameters }; + } + } + } + let additionalData; + let protectedHeaderS; + let protectedHeaderB; + let aadMember; + if (this.#protectedHeader) { + protectedHeaderS = encode3(JSON.stringify(this.#protectedHeader)); + protectedHeaderB = encode2(protectedHeaderS); + } else { + protectedHeaderS = ""; + protectedHeaderB = new Uint8Array(); + } + if (this.#aad) { + aadMember = encode3(this.#aad); + const aadMemberBytes = encode2(aadMember); + additionalData = concat(protectedHeaderB, encode2("."), aadMemberBytes); + } else { + additionalData = protectedHeaderB; + } + let plaintext = this.#plaintext; + if (joseHeader.zip === "DEF") { + plaintext = await compress(plaintext).catch((cause) => { + throw new JWEInvalid("Failed to compress plaintext", { cause }); + }); + } + const { ciphertext, tag: tag2, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData); + const jwe = { + ciphertext: encode3(ciphertext) + }; + if (iv) { + jwe.iv = encode3(iv); + } + if (tag2) { + jwe.tag = encode3(tag2); + } + if (encryptedKey) { + jwe.encrypted_key = encode3(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (this.#protectedHeader) { + jwe.protected = protectedHeaderS; + } + if (this.#sharedUnprotectedHeader) { + jwe.unprotected = this.#sharedUnprotectedHeader; + } + if (this.#unprotectedHeader) { + jwe.header = this.#unprotectedHeader; + } + return jwe; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/encrypt.js +var IndividualRecipient, GeneralEncrypt; +var init_encrypt2 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/encrypt.js"() { + init_encrypt(); + init_helpers(); + init_errors3(); + init_content_encryption(); + init_type_checks(); + init_key_management(); + init_base64url(); + init_validate_crit(); + init_normalize_key(); + init_check_key_type(); + IndividualRecipient = class { + #parent; + unprotectedHeader; + keyManagementParameters; + key; + options; + constructor(enc, key, options) { + this.#parent = enc; + this.key = key; + this.options = options; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(this.unprotectedHeader, "setUnprotectedHeader"); + this.unprotectedHeader = unprotectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + assertNotSet(this.keyManagementParameters, "setKeyManagementParameters"); + this.keyManagementParameters = parameters; + return this; + } + addRecipient(...args) { + return this.#parent.addRecipient(...args); + } + encrypt(...args) { + return this.#parent.encrypt(...args); + } + done() { + return this.#parent; + } + }; + GeneralEncrypt = class { + #plaintext; + #recipients = []; + #protectedHeader; + #unprotectedHeader; + #aad; + constructor(plaintext) { + this.#plaintext = plaintext; + } + addRecipient(key, options) { + const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); + this.#recipients.push(recipient); + return recipient; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.#protectedHeader, "setProtectedHeader"); + this.#protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + assertNotSet(this.#unprotectedHeader, "setSharedUnprotectedHeader"); + this.#unprotectedHeader = sharedUnprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this.#aad = aad; + return this; + } + async encrypt() { + if (!this.#recipients.length) { + throw new JWEInvalid("at least one recipient must be added"); + } + if (this.#recipients.length === 1) { + const [recipient] = this.#recipients; + const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options }); + const jwe2 = { + ciphertext: flattened.ciphertext, + iv: flattened.iv, + recipients: [{}], + tag: flattened.tag + }; + if (flattened.aad) + jwe2.aad = flattened.aad; + if (flattened.protected) + jwe2.protected = flattened.protected; + if (flattened.unprotected) + jwe2.unprotected = flattened.unprotected; + if (flattened.encrypted_key) + jwe2.recipients[0].encrypted_key = flattened.encrypted_key; + if (flattened.header) + jwe2.recipients[0].header = flattened.header; + return jwe2; + } + let enc; + for (let i = 0; i < this.#recipients.length; i++) { + const recipient = this.#recipients[i]; + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) { + throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader, + ...recipient.unprotectedHeader + }; + const { alg } = joseHeader; + if (typeof alg !== "string" || !alg) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (alg === "dir" || alg === "ECDH-ES") { + throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); + } + if (typeof joseHeader.enc !== "string" || !joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + if (!enc) { + enc = joseHeader.enc; + } else if (enc !== joseHeader.enc) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); + } + validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this.#protectedHeader, joseHeader); + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + } + if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); + } + } + const cek = generateCek(enc); + const jwe = { + ciphertext: "", + recipients: [] + }; + for (let i = 0; i < this.#recipients.length; i++) { + const recipient = this.#recipients[i]; + const target = {}; + jwe.recipients.push(target); + if (i === 0) { + const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setContentEncryptionKey(cek).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters(recipient.keyManagementParameters).encrypt(recipient.key, { + ...recipient.options, + [unprotected]: true + }); + jwe.ciphertext = flattened.ciphertext; + jwe.iv = flattened.iv; + jwe.tag = flattened.tag; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + target.encrypted_key = flattened.encrypted_key; + if (flattened.header) + target.header = flattened.header; + continue; + } + const alg = recipient.unprotectedHeader?.alg || this.#protectedHeader?.alg || this.#unprotectedHeader?.alg; + checkKeyType(alg === "dir" ? enc : alg, recipient.key, "encrypt"); + const k = await normalizeKey(recipient.key, alg); + const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters); + target.encrypted_key = encode3(encryptedKey); + if (recipient.unprotectedHeader || parameters) + target.header = { ...recipient.unprotectedHeader, ...parameters }; + } + return jwe; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js +async function flattenedVerify(jws, key, options) { + if (!isObject2(jws)) { + throw new JWSInvalid("Flattened JWS must be an object"); + } + if (jws.protected === void 0 && jws.header === void 0) { + throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== void 0 && typeof jws.protected !== "string") { + throw new JWSInvalid("JWS Protected Header incorrect type"); + } + if (jws.payload === void 0) { + throw new JWSInvalid("JWS Payload missing"); + } + if (typeof jws.signature !== "string") { + throw new JWSInvalid("JWS Signature missing or incorrect type"); + } + if (jws.header !== void 0 && !isObject2(jws.header)) { + throw new JWSInvalid("JWS Unprotected Header incorrect type"); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = decode2(jws.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } catch { + throw new JWSInvalid("JWS Protected Header is invalid"); + } + } + if (!isDisjoint(parsedProt, jws.header)) { + throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...parsedProt, + ...jws.header + }; + const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has("b64")) { + b64 = parsedProt.b64; + if (typeof b64 !== "boolean") { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== "string" || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && validateAlgorithms("algorithms", options.algorithms); + if (algorithms && !algorithms.has(alg)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (b64) { + if (typeof jws.payload !== "string") { + throw new JWSInvalid("JWS Payload must be a string"); + } + } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { + throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); + } + let resolvedKey = false; + if (typeof key === "function") { + key = await key(parsedProt, jws); + resolvedKey = true; + } + checkKeyType(alg, key, "verify"); + const data = concat(jws.protected !== void 0 ? encode2(jws.protected) : new Uint8Array(), encode2("."), typeof jws.payload === "string" ? b64 ? encode2(jws.payload) : encoder.encode(jws.payload) : jws.payload); + const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); + const k = await normalizeKey(key, alg); + const verified = await verify(alg, k, signature, data); + if (!verified) { + throw new JWSSignatureVerificationFailed(); + } + let payload; + if (b64) { + payload = decodeBase64url(jws.payload, "payload", JWSInvalid); + } else if (typeof jws.payload === "string") { + payload = encoder.encode(jws.payload); + } else { + payload = jws.payload; + } + const result = { payload }; + if (jws.protected !== void 0) { + result.protectedHeader = parsedProt; + } + if (jws.header !== void 0) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key: k }; + } + return result; +} +var init_verify = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"() { + init_base64url(); + init_signing(); + init_errors3(); + init_buffer_utils(); + init_helpers(); + init_type_checks(); + init_type_checks(); + init_check_key_type(); + init_validate_crit(); + init_validate_algorithms(); + init_normalize_key(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js +async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = decoder.decode(jws); + } + if (typeof jws !== "string") { + throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); + } + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); + if (length !== 3) { + throw new JWSInvalid("Invalid Compact JWS"); + } + const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: verified.key }; + } + return result; +} +var init_verify2 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"() { + init_verify(); + init_errors3(); + init_buffer_utils(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/verify.js +async function generalVerify(jws, key, options) { + if (!isObject2(jws)) { + throw new JWSInvalid("General JWS must be an object"); + } + if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject2)) { + throw new JWSInvalid("JWS Signatures missing or incorrect type"); + } + for (const signature of jws.signatures) { + try { + return await flattenedVerify({ + header: signature.header, + payload: jws.payload, + protected: signature.protected, + signature: signature.signature + }, key, options); + } catch { + } + } + throw new JWSSignatureVerificationFailed(); +} +var init_verify3 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/verify.js"() { + init_verify(); + init_errors3(); + init_type_checks(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +function secs(str) { + const matched = REGEX.exec(str); + if (!matched || matched[4] && matched[1]) { + throw new TypeError("Invalid time period format"); + } + const value = parseFloat(matched[2]); + const unit = matched[3].toLowerCase(); + let numericDate; + switch (unit) { + case "sec": + case "secs": + case "second": + case "seconds": + case "s": + numericDate = Math.round(value); + break; + case "minute": + case "minutes": + case "min": + case "mins": + case "m": + numericDate = Math.round(value * minute); + break; + case "hour": + case "hours": + case "hr": + case "hrs": + case "h": + numericDate = Math.round(value * hour); + break; + case "day": + case "days": + case "d": + numericDate = Math.round(value * day); + break; + case "week": + case "weeks": + case "w": + numericDate = Math.round(value * week); + break; + default: + numericDate = Math.round(value * year); + break; + } + if (matched[1] === "-" || matched[4] === "ago") { + return -numericDate; + } + return numericDate; +} +function validateInput(label, input) { + if (!Number.isFinite(input)) { + throw new TypeError(`Invalid ${label} input`); + } + return input; +} +function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { + let payload; + try { + payload = JSON.parse(decoder.decode(encodedPayload)); + } catch { + } + if (!isObject2(payload)) { + throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); + } + const { typ } = options; + if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed"); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + const presenceCheck = [...requiredClaims]; + if (maxTokenAge !== void 0) + presenceCheck.push("iat"); + if (audience !== void 0) + presenceCheck.push("aud"); + if (subject !== void 0) + presenceCheck.push("sub"); + if (issuer !== void 0) + presenceCheck.push("iss"); + for (const claim of new Set(presenceCheck.reverse())) { + if (!(claim in payload)) { + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + } + } + if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { + throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed"); + } + if (subject && payload.sub !== subject) { + throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed"); + } + if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { + throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed"); + } + let tolerance; + switch (typeof options.clockTolerance) { + case "string": + tolerance = secs(options.clockTolerance); + break; + case "number": + tolerance = options.clockTolerance; + break; + case "undefined": + tolerance = 0; + break; + default: + throw new TypeError("Invalid clockTolerance option type"); + } + const { currentDate } = options; + const now = epoch(currentDate || /* @__PURE__ */ new Date()); + if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") { + throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid"); + } + if (payload.nbf !== void 0) { + if (typeof payload.nbf !== "number") { + throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid"); + } + if (payload.nbf > now + tolerance) { + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed"); + } + } + if (payload.exp !== void 0) { + if (typeof payload.exp !== "number") { + throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid"); + } + if (payload.exp <= now - tolerance) { + throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed"); + } + } + if (maxTokenAge) { + const age = now - payload.iat; + const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); + if (age - tolerance > max) { + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed"); + } + if (age < 0 - tolerance) { + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed"); + } + } + return payload; +} +var epoch, minute, hour, day, week, year, REGEX, normalizeTyp, checkAudiencePresence, JWTClaimsBuilder; +var init_jwt_claims_set = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"() { + init_errors3(); + init_buffer_utils(); + init_type_checks(); + epoch = (date5) => Math.floor(date5.getTime() / 1e3); + minute = 60; + hour = minute * 60; + day = hour * 24; + week = day * 7; + year = day * 365.25; + REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; + normalizeTyp = (value) => { + if (value.includes("/")) { + return value.toLowerCase(); + } + return `application/${value.toLowerCase()}`; + }; + checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === "string") { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; + }; + JWTClaimsBuilder = class { + #payload; + constructor(payload) { + if (!isObject2(payload)) { + throw new TypeError("JWT Claims Set MUST be an object"); + } + this.#payload = structuredClone(payload); + } + data() { + return encoder.encode(JSON.stringify(this.#payload)); + } + get iss() { + return this.#payload.iss; + } + set iss(value) { + this.#payload.iss = value; + } + get sub() { + return this.#payload.sub; + } + set sub(value) { + this.#payload.sub = value; + } + get aud() { + return this.#payload.aud; + } + set aud(value) { + this.#payload.aud = value; + } + set jti(value) { + this.#payload.jti = value; + } + set nbf(value) { + if (typeof value === "number") { + this.#payload.nbf = validateInput("setNotBefore", value); + } else if (value instanceof Date) { + this.#payload.nbf = validateInput("setNotBefore", epoch(value)); + } else { + this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + } + set exp(value) { + if (typeof value === "number") { + this.#payload.exp = validateInput("setExpirationTime", value); + } else if (value instanceof Date) { + this.#payload.exp = validateInput("setExpirationTime", epoch(value)); + } else { + this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + } + set iat(value) { + if (value === void 0) { + this.#payload.iat = epoch(/* @__PURE__ */ new Date()); + } else if (value instanceof Date) { + this.#payload.iat = validateInput("setIssuedAt", epoch(value)); + } else if (typeof value === "string") { + this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); + } else { + this.#payload.iat = validateInput("setIssuedAt", value); + } + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js +async function jwtVerify(jwt2, key, options) { + const verified = await compactVerify(jwt2, key, options); + if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { + throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + } + const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options); + const result = { payload, protectedHeader: verified.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: verified.key }; + } + return result; +} +var init_verify4 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"() { + init_verify2(); + init_jwt_claims_set(); + init_errors3(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js +async function jwtDecrypt(jwt2, key, options) { + const decrypted = await compactDecrypt(jwt2, key, options); + const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { + throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch"); + } + if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { + throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch"); + } + if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { + throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch"); + } + const result = { payload, protectedHeader }; + if (typeof key === "function") { + return { ...result, key: decrypted.key }; + } + return result; +} +var init_decrypt4 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js"() { + init_decrypt2(); + init_jwt_claims_set(); + init_errors3(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js +var CompactEncrypt; +var init_encrypt3 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js"() { + init_encrypt(); + CompactEncrypt = class { + #flattened; + constructor(plaintext) { + this.#flattened = new FlattenedEncrypt(plaintext); + } + setContentEncryptionKey(cek) { + this.#flattened.setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + this.#flattened.setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + this.#flattened.setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + this.#flattened.setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await this.#flattened.encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js +var FlattenedSign; +var init_sign = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"() { + init_base64url(); + init_signing(); + init_type_checks(); + init_errors3(); + init_buffer_utils(); + init_check_key_type(); + init_validate_crit(); + init_normalize_key(); + init_helpers(); + FlattenedSign = class { + #payload; + #protectedHeader; + #unprotectedHeader; + constructor(payload) { + if (!(payload instanceof Uint8Array)) { + throw new TypeError("payload must be an instance of Uint8Array"); + } + this.#payload = payload; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.#protectedHeader, "setProtectedHeader"); + this.#protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); + this.#unprotectedHeader = unprotectedHeader; + return this; + } + async sign(key, options) { + if (!this.#protectedHeader && !this.#unprotectedHeader) { + throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); + } + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) { + throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader + }; + const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader); + let b64 = true; + if (extensions.has("b64")) { + b64 = this.#protectedHeader.b64; + if (typeof b64 !== "boolean") { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== "string" || !alg) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + checkKeyType(alg, key, "sign"); + let payloadS; + let payloadB; + if (b64) { + payloadS = encode3(this.#payload); + payloadB = encode2(payloadS); + } else { + payloadB = this.#payload; + payloadS = ""; + } + let protectedHeaderString; + let protectedHeaderBytes; + if (this.#protectedHeader) { + protectedHeaderString = encode3(JSON.stringify(this.#protectedHeader)); + protectedHeaderBytes = encode2(protectedHeaderString); + } else { + protectedHeaderString = ""; + protectedHeaderBytes = new Uint8Array(); + } + const data = concat(protectedHeaderBytes, encode2("."), payloadB); + const k = await normalizeKey(key, alg); + const signature = await sign(alg, k, data); + const jws = { + signature: encode3(signature), + payload: payloadS + }; + if (this.#unprotectedHeader) { + jws.header = this.#unprotectedHeader; + } + if (this.#protectedHeader) { + jws.protected = protectedHeaderString; + } + return jws; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js +var CompactSign; +var init_sign2 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"() { + init_sign(); + CompactSign = class { + #flattened; + constructor(payload) { + this.#flattened = new FlattenedSign(payload); + } + setProtectedHeader(protectedHeader) { + this.#flattened.setProtectedHeader(protectedHeader); + return this; + } + async sign(key, options) { + const jws = await this.#flattened.sign(key, options); + if (jws.payload === void 0) { + throw new TypeError("use the flattened module for creating JWS with b64: false"); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/sign.js +var IndividualSignature, GeneralSign; +var init_sign3 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/sign.js"() { + init_sign(); + init_errors3(); + init_helpers(); + IndividualSignature = class { + #parent; + protectedHeader; + unprotectedHeader; + options; + key; + constructor(sig, key, options) { + this.#parent = sig; + this.key = key; + this.options = options; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.protectedHeader, "setProtectedHeader"); + this.protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(this.unprotectedHeader, "setUnprotectedHeader"); + this.unprotectedHeader = unprotectedHeader; + return this; + } + addSignature(...args) { + return this.#parent.addSignature(...args); + } + sign(...args) { + return this.#parent.sign(...args); + } + done() { + return this.#parent; + } + }; + GeneralSign = class { + #payload; + #signatures = []; + constructor(payload) { + this.#payload = payload; + } + addSignature(key, options) { + const signature = new IndividualSignature(this, key, options); + this.#signatures.push(signature); + return signature; + } + async sign() { + if (!this.#signatures.length) { + throw new JWSInvalid("at least one signature must be added"); + } + const jws = { + signatures: [], + payload: "" + }; + for (let i = 0; i < this.#signatures.length; i++) { + const signature = this.#signatures[i]; + const flattened = new FlattenedSign(this.#payload); + flattened.setProtectedHeader(signature.protectedHeader); + flattened.setUnprotectedHeader(signature.unprotectedHeader); + const { payload, ...rest } = await flattened.sign(signature.key, signature.options); + if (i === 0) { + jws.payload = payload; + } else if (jws.payload !== payload) { + throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)"); + } + jws.signatures.push(rest); + } + return jws; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js +var SignJWT; +var init_sign4 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"() { + init_sign2(); + init_errors3(); + init_jwt_claims_set(); + SignJWT = class { + #protectedHeader; + #jwt; + constructor(payload = {}) { + this.#jwt = new JWTClaimsBuilder(payload); + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + this.#protectedHeader = protectedHeader; + return this; + } + async sign(key, options) { + const sig = new CompactSign(this.#jwt.data()); + sig.setProtectedHeader(this.#protectedHeader); + if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) { + throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + } + return sig.sign(key, options); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js +var EncryptJWT; +var init_encrypt4 = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js"() { + init_encrypt3(); + init_jwt_claims_set(); + init_helpers(); + EncryptJWT = class { + #cek; + #iv; + #keyManagementParameters; + #protectedHeader; + #replicateIssuerAsHeader; + #replicateSubjectAsHeader; + #replicateAudienceAsHeader; + #jwt; + constructor(payload = {}) { + this.#jwt = new JWTClaimsBuilder(payload); + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.#protectedHeader, "setProtectedHeader"); + this.#protectedHeader = protectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); + this.#keyManagementParameters = parameters; + return this; + } + setContentEncryptionKey(cek) { + assertNotSet(this.#cek, "setContentEncryptionKey"); + this.#cek = cek; + return this; + } + setInitializationVector(iv) { + assertNotSet(this.#iv, "setInitializationVector"); + this.#iv = iv; + return this; + } + replicateIssuerAsHeader() { + this.#replicateIssuerAsHeader = true; + return this; + } + replicateSubjectAsHeader() { + this.#replicateSubjectAsHeader = true; + return this; + } + replicateAudienceAsHeader() { + this.#replicateAudienceAsHeader = true; + return this; + } + async encrypt(key, options) { + const enc = new CompactEncrypt(this.#jwt.data()); + if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) { + this.#protectedHeader = { + ...this.#protectedHeader, + iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0, + sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0, + aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0 + }; + } + enc.setProtectedHeader(this.#protectedHeader); + if (this.#iv) { + enc.setInitializationVector(this.#iv); + } + if (this.#cek) { + enc.setContentEncryptionKey(this.#cek); + } + if (this.#keyManagementParameters) { + enc.setKeyManagementParameters(this.#keyManagementParameters); + } + return enc.encrypt(key, options); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js +async function calculateJwkThumbprint(key, digestAlgorithm) { + let jwk; + if (isJWK(key)) { + jwk = key; + } else if (isKeyLike(key)) { + jwk = await exportJWK(key); + } else { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + digestAlgorithm ??= "sha256"; + if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { + throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); + } + let components; + switch (jwk.kty) { + case "AKP": + check2(jwk.alg, '"alg" (Algorithm) Parameter'); + check2(jwk.pub, '"pub" (Public key) Parameter'); + components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub }; + break; + case "EC": + check2(jwk.crv, '"crv" (Curve) Parameter'); + check2(jwk.x, '"x" (X Coordinate) Parameter'); + check2(jwk.y, '"y" (Y Coordinate) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; + break; + case "OKP": + check2(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); + check2(jwk.x, '"x" (Public Key) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; + break; + case "RSA": + check2(jwk.e, '"e" (Exponent) Parameter'); + check2(jwk.n, '"n" (Modulus) Parameter'); + components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; + break; + case "oct": + check2(jwk.k, '"k" (Key Value) Parameter'); + components = { k: jwk.k, kty: jwk.kty }; + break; + default: + throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); + } + const data = encode2(JSON.stringify(components)); + return encode3(await digest(digestAlgorithm, data)); +} +async function calculateJwkThumbprintUri(key, digestAlgorithm) { + digestAlgorithm ??= "sha256"; + const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm); + return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; +} +var check2; +var init_thumbprint = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js"() { + init_helpers(); + init_base64url(); + init_errors3(); + init_buffer_utils(); + init_is_key_like(); + init_type_checks(); + init_export(); + init_invalid_key_input(); + check2 = (value, description) => { + if (typeof value !== "string" || !value) { + throw new JWKInvalid(`${description} missing or invalid`); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/embedded.js +async function EmbeddedJWK(protectedHeader, token) { + const joseHeader = { + ...protectedHeader, + ...token?.header + }; + if (!isObject2(joseHeader.jwk)) { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); + } + const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg); + if (key instanceof Uint8Array || key.type !== "public") { + throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); + } + return key; +} +var init_embedded = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/embedded.js"() { + init_import(); + init_type_checks(); + init_errors3(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js +function getKtyFromAlg(alg) { + switch (typeof alg === "string" && alg.slice(0, 2)) { + case "RS": + case "PS": + return "RSA"; + case "ES": + return "EC"; + case "Ed": + return "OKP"; + case "ML": + return "AKP"; + default: + throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + } +} +function isJWKSLike(jwks) { + return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); +} +function isJWKLike(key) { + return isObject2(key); +} +async function importWithAlgCache(cache2, jwk, alg) { + const cached2 = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk); + if (cached2[alg] === void 0) { + const key = await importJWK({ ...jwk, ext: true }, alg); + if (key instanceof Uint8Array || key.type !== "public") { + throw new JWKSInvalid("JSON Web Key Set members must be public keys"); + } + cached2[alg] = key; + } + return cached2[alg]; +} +function createLocalJWKSet(jwks) { + const set2 = new LocalJWKSet(jwks); + const localJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); + Object.defineProperties(localJWKSet, { + jwks: { + value: () => structuredClone(set2.jwks()), + enumerable: false, + configurable: false, + writable: false + } + }); + return localJWKSet; +} +var LocalJWKSet; +var init_local = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"() { + init_import(); + init_errors3(); + init_type_checks(); + LocalJWKSet = class { + #jwks; + #cached = /* @__PURE__ */ new WeakMap(); + constructor(jwks) { + if (!isJWKSLike(jwks)) { + throw new JWKSInvalid("JSON Web Key Set malformed"); + } + this.#jwks = structuredClone(jwks); + } + jwks() { + return this.#jwks; + } + async getKey(protectedHeader, token) { + const { alg, kid } = { ...protectedHeader, ...token?.header }; + const kty = getKtyFromAlg(alg); + const candidates = this.#jwks.keys.filter((jwk2) => { + let candidate = kty === jwk2.kty; + if (candidate && typeof kid === "string") { + candidate = kid === jwk2.kid; + } + if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) { + candidate = alg === jwk2.alg; + } + if (candidate && typeof jwk2.use === "string") { + candidate = jwk2.use === "sig"; + } + if (candidate && Array.isArray(jwk2.key_ops)) { + candidate = jwk2.key_ops.includes("verify"); + } + if (candidate) { + switch (alg) { + case "ES256": + candidate = jwk2.crv === "P-256"; + break; + case "ES384": + candidate = jwk2.crv === "P-384"; + break; + case "ES512": + candidate = jwk2.crv === "P-521"; + break; + case "Ed25519": + case "EdDSA": + candidate = jwk2.crv === "Ed25519"; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new JWKSNoMatchingKey(); + } + if (length !== 1) { + const error2 = new JWKSMultipleMatchingKeys(); + const _cached = this.#cached; + error2[Symbol.asyncIterator] = async function* () { + for (const jwk2 of candidates) { + try { + yield await importWithAlgCache(_cached, jwk2, alg); + } catch { + } + } + }; + throw error2; + } + return importWithAlgCache(this.#cached, jwk, alg); + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js +function isCloudflareWorkers() { + return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; +} +async function fetchJwks(url2, headers, signal, fetchImpl = fetch) { + const response = await fetchImpl(url2, { + method: "GET", + signal, + redirect: "manual", + headers + }).catch((err) => { + if (err.name === "TimeoutError") { + throw new JWKSTimeout(); + } + throw err; + }); + if (response.status !== 200) { + throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); + } + try { + return await response.json(); + } catch { + throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); + } +} +function isFreshJwksCache(input, cacheMaxAge) { + if (typeof input !== "object" || input === null) { + return false; + } + if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { + return false; + } + if (!("jwks" in input) || !isObject2(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject2)) { + return false; + } + return true; +} +function createRemoteJWKSet(url2, options) { + const set2 = new RemoteJWKSet(url2, options); + const remoteJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); + Object.defineProperties(remoteJWKSet, { + coolingDown: { + get: () => set2.coolingDown(), + enumerable: true, + configurable: false + }, + fresh: { + get: () => set2.fresh(), + enumerable: true, + configurable: false + }, + reload: { + value: () => set2.reload(), + enumerable: true, + configurable: false, + writable: false + }, + reloading: { + get: () => set2.pendingFetch(), + enumerable: true, + configurable: false + }, + jwks: { + value: () => set2.jwks(), + enumerable: true, + configurable: false, + writable: false + } + }); + return remoteJWKSet; +} +var USER_AGENT, customFetch, jwksCache, RemoteJWKSet; +var init_remote = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"() { + init_errors3(); + init_local(); + init_type_checks(); + if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { + const NAME = "jose"; + const VERSION = "v6.2.2"; + USER_AGENT = `${NAME}/${VERSION}`; + } + customFetch = /* @__PURE__ */ Symbol(); + jwksCache = /* @__PURE__ */ Symbol(); + RemoteJWKSet = class { + #url; + #timeoutDuration; + #cooldownDuration; + #cacheMaxAge; + #jwksTimestamp; + #pendingFetch; + #headers; + #customFetch; + #local; + #cache; + constructor(url2, options) { + if (!(url2 instanceof URL)) { + throw new TypeError("url must be an instance of URL"); + } + this.#url = new URL(url2.href); + this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; + this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; + this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; + this.#headers = new Headers(options?.headers); + if (USER_AGENT && !this.#headers.has("User-Agent")) { + this.#headers.set("User-Agent", USER_AGENT); + } + if (!this.#headers.has("accept")) { + this.#headers.set("accept", "application/json"); + this.#headers.append("accept", "application/jwk-set+json"); + } + this.#customFetch = options?.[customFetch]; + if (options?.[jwksCache] !== void 0) { + this.#cache = options?.[jwksCache]; + if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { + this.#jwksTimestamp = this.#cache.uat; + this.#local = createLocalJWKSet(this.#cache.jwks); + } + } + } + pendingFetch() { + return !!this.#pendingFetch; + } + coolingDown() { + return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false; + } + fresh() { + return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false; + } + jwks() { + return this.#local?.jwks(); + } + async getKey(protectedHeader, token) { + if (!this.#local || !this.fresh()) { + await this.reload(); + } + try { + return await this.#local(protectedHeader, token); + } catch (err) { + if (err instanceof JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return this.#local(protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (this.#pendingFetch && isCloudflareWorkers()) { + this.#pendingFetch = void 0; + } + this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json2) => { + this.#local = createLocalJWKSet(json2); + if (this.#cache) { + this.#cache.uat = Date.now(); + this.#cache.jwks = json2; + } + this.#jwksTimestamp = Date.now(); + this.#pendingFetch = void 0; + }).catch((err) => { + this.#pendingFetch = void 0; + throw err; + }); + await this.#pendingFetch; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/unsecured.js +var UnsecuredJWT; +var init_unsecured = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/unsecured.js"() { + init_base64url(); + init_buffer_utils(); + init_errors3(); + init_jwt_claims_set(); + UnsecuredJWT = class { + #jwt; + constructor(payload = {}) { + this.#jwt = new JWTClaimsBuilder(payload); + } + encode() { + const header = encode3(JSON.stringify({ alg: "none" })); + const payload = encode3(this.#jwt.data()); + return `${header}.${payload}.`; + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + static decode(jwt2, options) { + if (typeof jwt2 !== "string") { + throw new JWTInvalid("Unsecured JWT must be a string"); + } + const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt2.split("."); + if (length !== 3 || signature !== "") { + throw new JWTInvalid("Invalid Unsecured JWT"); + } + let header; + try { + header = JSON.parse(decoder.decode(decode2(encodedHeader))); + if (header.alg !== "none") + throw new Error(); + } catch { + throw new JWTInvalid("Invalid Unsecured JWT"); + } + const payload = validateClaimsSet(header, decode2(encodedPayload), options); + return { payload, header }; + } + }; + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js +function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === "string") { + const parts = token.split("."); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } else if (typeof token === "object" && token) { + if ("protected" in token) { + protectedB64u = token.protected; + } else { + throw new TypeError("Token does not contain a Protected Header"); + } + } + try { + if (typeof protectedB64u !== "string" || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(decoder.decode(decode2(protectedB64u))); + if (!isObject2(result)) { + throw new Error(); + } + return result; + } catch { + throw new TypeError("Invalid Token or Protected Header formatting"); + } +} +var init_decode_protected_header = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js"() { + init_base64url(); + init_buffer_utils(); + init_type_checks(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js +function decodeJwt(jwt2) { + if (typeof jwt2 !== "string") + throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); + const { 1: payload, length } = jwt2.split("."); + if (length === 5) + throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); + if (length !== 3) + throw new JWTInvalid("Invalid JWT"); + if (!payload) + throw new JWTInvalid("JWTs must contain a payload"); + let decoded; + try { + decoded = decode2(payload); + } catch { + throw new JWTInvalid("Failed to base64url decode the payload"); + } + let result; + try { + result = JSON.parse(decoder.decode(decoded)); + } catch { + throw new JWTInvalid("Failed to parse the decoded payload as JSON"); + } + if (!isObject2(result)) + throw new JWTInvalid("Invalid JWT Claims Set"); + return result; +} +var init_decode_jwt = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js"() { + init_base64url(); + init_buffer_utils(); + init_type_checks(); + init_errors3(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_key_pair.js +function getModulusLengthOption(options) { + const modulusLength = options?.modulusLength ?? 2048; + if (typeof modulusLength !== "number" || modulusLength < 2048) { + throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used"); + } + return modulusLength; +} +async function generateKeyPair(alg, options) { + let algorithm; + let keyUsages; + switch (alg) { + case "PS256": + case "PS384": + case "PS512": + algorithm = { + name: "RSA-PSS", + hash: `SHA-${alg.slice(-3)}`, + publicExponent: Uint8Array.of(1, 0, 1), + modulusLength: getModulusLengthOption(options) + }; + keyUsages = ["sign", "verify"]; + break; + case "RS256": + case "RS384": + case "RS512": + algorithm = { + name: "RSASSA-PKCS1-v1_5", + hash: `SHA-${alg.slice(-3)}`, + publicExponent: Uint8Array.of(1, 0, 1), + modulusLength: getModulusLengthOption(options) + }; + keyUsages = ["sign", "verify"]; + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + algorithm = { + name: "RSA-OAEP", + hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, + publicExponent: Uint8Array.of(1, 0, 1), + modulusLength: getModulusLengthOption(options) + }; + keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"]; + break; + case "ES256": + algorithm = { name: "ECDSA", namedCurve: "P-256" }; + keyUsages = ["sign", "verify"]; + break; + case "ES384": + algorithm = { name: "ECDSA", namedCurve: "P-384" }; + keyUsages = ["sign", "verify"]; + break; + case "ES512": + algorithm = { name: "ECDSA", namedCurve: "P-521" }; + keyUsages = ["sign", "verify"]; + break; + case "Ed25519": + case "EdDSA": { + keyUsages = ["sign", "verify"]; + algorithm = { name: "Ed25519" }; + break; + } + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": { + keyUsages = ["sign", "verify"]; + algorithm = { name: alg }; + break; + } + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + keyUsages = ["deriveBits"]; + const crv = options?.crv ?? "P-256"; + switch (crv) { + case "P-256": + case "P-384": + case "P-521": { + algorithm = { name: "ECDH", namedCurve: crv }; + break; + } + case "X25519": + algorithm = { name: "X25519" }; + break; + default: + throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519"); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); +} +var init_generate_key_pair = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_key_pair.js"() { + init_errors3(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_secret.js +async function generateSecret(alg, options) { + let length; + let algorithm; + let keyUsages; + switch (alg) { + case "HS256": + case "HS384": + case "HS512": + length = parseInt(alg.slice(-3), 10); + algorithm = { name: "HMAC", hash: `SHA-${length}`, length }; + keyUsages = ["sign", "verify"]; + break; + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + length = parseInt(alg.slice(-3), 10); + return crypto.getRandomValues(new Uint8Array(length >> 3)); + case "A128KW": + case "A192KW": + case "A256KW": + length = parseInt(alg.slice(1, 4), 10); + algorithm = { name: "AES-KW", length }; + keyUsages = ["wrapKey", "unwrapKey"]; + break; + case "A128GCMKW": + case "A192GCMKW": + case "A256GCMKW": + case "A128GCM": + case "A192GCM": + case "A256GCM": + length = parseInt(alg.slice(1, 4), 10); + algorithm = { name: "AES-GCM", length }; + keyUsages = ["encrypt", "decrypt"]; + break; + default: + throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); +} +var init_generate_secret = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_secret.js"() { + init_errors3(); + } +}); + +// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js +var webapi_exports = {}; +__export(webapi_exports, { + CompactEncrypt: () => CompactEncrypt, + CompactSign: () => CompactSign, + EmbeddedJWK: () => EmbeddedJWK, + EncryptJWT: () => EncryptJWT, + FlattenedEncrypt: () => FlattenedEncrypt, + FlattenedSign: () => FlattenedSign, + GeneralEncrypt: () => GeneralEncrypt, + GeneralSign: () => GeneralSign, + SignJWT: () => SignJWT, + UnsecuredJWT: () => UnsecuredJWT, + base64url: () => base64url_exports, + calculateJwkThumbprint: () => calculateJwkThumbprint, + calculateJwkThumbprintUri: () => calculateJwkThumbprintUri, + compactDecrypt: () => compactDecrypt, + compactVerify: () => compactVerify, + createLocalJWKSet: () => createLocalJWKSet, + createRemoteJWKSet: () => createRemoteJWKSet, + cryptoRuntime: () => cryptoRuntime, + customFetch: () => customFetch, + decodeJwt: () => decodeJwt, + decodeProtectedHeader: () => decodeProtectedHeader, + errors: () => errors_exports2, + exportJWK: () => exportJWK, + exportPKCS8: () => exportPKCS8, + exportSPKI: () => exportSPKI, + flattenedDecrypt: () => flattenedDecrypt, + flattenedVerify: () => flattenedVerify, + generalDecrypt: () => generalDecrypt, + generalVerify: () => generalVerify, + generateKeyPair: () => generateKeyPair, + generateSecret: () => generateSecret, + importJWK: () => importJWK, + importPKCS8: () => importPKCS8, + importSPKI: () => importSPKI, + importX509: () => importX509, + jwksCache: () => jwksCache, + jwtDecrypt: () => jwtDecrypt, + jwtVerify: () => jwtVerify +}); +var cryptoRuntime; +var init_webapi = __esm({ + "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"() { + init_decrypt2(); + init_decrypt(); + init_decrypt3(); + init_encrypt2(); + init_verify2(); + init_verify(); + init_verify3(); + init_verify4(); + init_decrypt4(); + init_encrypt3(); + init_encrypt(); + init_sign2(); + init_sign(); + init_sign3(); + init_sign4(); + init_encrypt4(); + init_thumbprint(); + init_embedded(); + init_local(); + init_remote(); + init_unsecured(); + init_export(); + init_import(); + init_decode_protected_header(); + init_decode_jwt(); + init_errors3(); + init_generate_key_pair(); + init_generate_secret(); + init_base64url(); + cryptoRuntime = "WebCryptoAPI"; + } +}); + +// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/index.mjs +var dist_exports = {}; +__export(dist_exports, { + AuthorizationServerMismatchError: () => AuthorizationServerMismatchError, + BAGGAGE_META_KEY: () => BAGGAGE_META_KEY, + CLIENT_CAPABILITIES_META_KEY: () => CLIENT_CAPABILITIES_META_KEY, + CLIENT_INFO_META_KEY: () => CLIENT_INFO_META_KEY, + Client: () => Client, + ClientCredentialsProvider: () => ClientCredentialsProvider, + CrossAppAccessProvider: () => CrossAppAccessProvider, + DEFAULT_NEGOTIATED_PROTOCOL_VERSION: () => DEFAULT_NEGOTIATED_PROTOCOL_VERSION, + DEFAULT_REQUEST_TIMEOUT_MSEC: () => DEFAULT_REQUEST_TIMEOUT_MSEC, + INTERNAL_ERROR: () => INTERNAL_ERROR, + INVALID_PARAMS: () => INVALID_PARAMS, + INVALID_REQUEST: () => INVALID_REQUEST, + InMemoryResponseCacheStore: () => InMemoryResponseCacheStore, + InMemoryTransport: () => InMemoryTransport, + InsecureTokenEndpointError: () => InsecureTokenEndpointError, + InsufficientScopeError: () => InsufficientScopeError, + IssuerMismatchError: () => IssuerMismatchError, + JSONRPC_VERSION: () => JSONRPC_VERSION, + LATEST_PROTOCOL_VERSION: () => LATEST_PROTOCOL_VERSION, + LOG_LEVEL_META_KEY: () => LOG_LEVEL_META_KEY, + MAX_CACHE_TTL_MS: () => MAX_CACHE_TTL_MS, + METHOD_NOT_FOUND: () => METHOD_NOT_FOUND, + MissingRequiredClientCapabilityError: () => MissingRequiredClientCapabilityError, + OAuthClientFlowError: () => OAuthClientFlowError, + OAuthError: () => OAuthError, + OAuthErrorCode: () => OAuthErrorCode, + PARSE_ERROR: () => PARSE_ERROR, + PROTOCOL_VERSION_META_KEY: () => PROTOCOL_VERSION_META_KEY, + PrivateKeyJwtProvider: () => PrivateKeyJwtProvider, + Protocol: () => Protocol, + ProtocolError: () => ProtocolError, + ProtocolErrorCode: () => ProtocolErrorCode, + RELATED_TASK_META_KEY: () => RELATED_TASK_META_KEY, + ReadBuffer: () => ReadBuffer, + RegistrationRejectedError: () => RegistrationRejectedError, + ResourceNotFoundError: () => ResourceNotFoundError, + SERVER_INFO_META_KEY: () => SERVER_INFO_META_KEY, + SSEClientTransport: () => SSEClientTransport, + STDIO_DEFAULT_MAX_BUFFER_SIZE: () => STDIO_DEFAULT_MAX_BUFFER_SIZE, + SUBSCRIPTION_ID_META_KEY: () => SUBSCRIPTION_ID_META_KEY, + SUPPORTED_PROTOCOL_VERSIONS: () => SUPPORTED_PROTOCOL_VERSIONS, + SdkError: () => SdkError, + SdkErrorCode: () => SdkErrorCode, + SdkHttpError: () => SdkHttpError, + SseError: () => SseError, + StaticPrivateKeyJwtProvider: () => StaticPrivateKeyJwtProvider, + StreamableHTTPClientTransport: () => StreamableHTTPClientTransport, + TRACEPARENT_META_KEY: () => TRACEPARENT_META_KEY, + TRACESTATE_META_KEY: () => TRACESTATE_META_KEY, + UnauthorizedError: () => UnauthorizedError, + UnsupportedProtocolVersionError: () => UnsupportedProtocolVersionError, + UriTemplate: () => UriTemplate, + UrlElicitationRequiredError: () => UrlElicitationRequiredError, + applyMiddlewares: () => applyMiddlewares, + assertCompleteRequestPrompt: () => assertCompleteRequestPrompt, + assertCompleteRequestResourceTemplate: () => assertCompleteRequestResourceTemplate, + assertSecureTokenEndpoint: () => assertSecureTokenEndpoint, + auth: () => auth, + buildDiscoveryUrls: () => buildDiscoveryUrls, + checkResourceAllowed: () => checkResourceAllowed, + computeScopeUnion: () => computeScopeUnion, + createFetchWithInit: () => createFetchWithInit, + createMiddleware: () => createMiddleware, + createPrivateKeyJwtAuth: () => createPrivateKeyJwtAuth, + deserializeMessage: () => deserializeMessage, + discoverAndRequestJwtAuthGrant: () => discoverAndRequestJwtAuthGrant, + discoverAuthorizationServerMetadata: () => discoverAuthorizationServerMetadata, + discoverOAuthMetadata: () => discoverOAuthMetadata, + discoverOAuthProtectedResourceMetadata: () => discoverOAuthProtectedResourceMetadata, + discoverOAuthServerInfo: () => discoverOAuthServerInfo, + exchangeAuthorization: () => exchangeAuthorization, + exchangeJwtAuthGrant: () => exchangeJwtAuthGrant, + extractResourceMetadataUrl: () => extractResourceMetadataUrl, + extractWWWAuthenticateParams: () => extractWWWAuthenticateParams, + fetchToken: () => fetchToken, + fromJsonSchema: () => fromJsonSchema2, + getDisplayName: () => getDisplayName, + getSupportedElicitationModes: () => getSupportedElicitationModes, + isCallToolResult: () => isCallToolResult, + isHttpsUrl: () => isHttpsUrl, + isInitializeRequest: () => isInitializeRequest, + isInitializedNotification: () => isInitializedNotification, + isInputRequiredResult: () => isInputRequiredResult, + isJSONRPCErrorResponse: () => isJSONRPCErrorResponse, + isJSONRPCNotification: () => isJSONRPCNotification, + isJSONRPCRequest: () => isJSONRPCRequest, + isJSONRPCResponse: () => isJSONRPCResponse, + isJSONRPCResultResponse: () => isJSONRPCResultResponse, + isJsonContentType: () => isJsonContentType, + isSpecType: () => isSpecType, + isStrictScopeSuperset: () => isStrictScopeSuperset, + isTaskAugmentedRequestParams: () => isTaskAugmentedRequestParams, + mergeCapabilities: () => mergeCapabilities, + parseErrorResponse: () => parseErrorResponse, + parseJSONRPCMessage: () => parseJSONRPCMessage, + preloadSchemas: () => preloadSchemas, + prepareAuthorizationCodeRequest: () => prepareAuthorizationCodeRequest, + refreshAuthorization: () => refreshAuthorization, + registerClient: () => registerClient, + requestJwtAuthorizationGrant: () => requestJwtAuthorizationGrant, + resolveClientMetadata: () => resolveClientMetadata, + resourceUrlFromServerUrl: () => resourceUrlFromServerUrl, + selectClientAuthMethod: () => selectClientAuthMethod, + selectResourceURL: () => selectResourceURL, + serializeMessage: () => serializeMessage, + specTypeSchemas: () => specTypeSchemas, + startAuthorization: () => startAuthorization, + validateAuthorizationResponseIssuer: () => validateAuthorizationResponseIssuer, + validateClientMetadataUrl: () => validateClientMetadataUrl, + withInputRequired: () => withInputRequired, + withLogging: () => withLogging, + withOAuth: () => withOAuth +}); +function discardIfIssuerMismatch(stored, issuer, opts) { + if (stored === void 0) return void 0; + if (stored.issuer === void 0) { + if (opts?.canPersistStamp !== false) console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."); + return stored; + } + return issuersMatch(stored.issuer, issuer) ? stored : void 0; +} +function issuersMatch(a, b) { + return a === b || a.endsWith("/") && a.slice(0, -1) === b || b.endsWith("/") && b.slice(0, -1) === a; +} +function isOAuthClientProvider(provider) { + if (provider == null) return false; + const p = provider; + return typeof p.tokens === "function" && typeof p.clientInformation === "function"; +} +async function handleOAuthUnauthorized(provider, ctx, extraAuthOptions) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(ctx.response); + if (await auth(provider, { + serverUrl: ctx.serverUrl, + resourceMetadataUrl, + scope, + fetchFn: ctx.fetchFn, + ...extraAuthOptions + }) !== "AUTHORIZED") throw new UnauthorizedError(); +} +function adaptOAuthProvider(provider, extraAuthOptions) { + return { + token: async () => { + return (await provider.tokens())?.access_token; + }, + onUnauthorized: async (ctx) => handleOAuthUnauthorized(provider, ctx, extraAuthOptions) + }; +} +function isIssParameterSupported(metadata) { + return metadata?.authorization_response_iss_parameter_supported === true; +} +function validateAuthorizationResponseIssuer({ iss, expectedIssuer, issParameterSupported }) { + if (expectedIssuer === void 0) return; + if (iss === void 0) { + if (issParameterSupported) throw new IssuerMismatchError("authorization_response", expectedIssuer, void 0); + return; + } + if (iss !== expectedIssuer) throw new IssuerMismatchError("authorization_response", expectedIssuer, iss); +} +function computeScopeUnion(...scopes) { + const seen = /* @__PURE__ */ new Set(); + for (const scope of scopes) { + if (!scope) continue; + for (const token of scope.split(/\s+/)) if (token) seen.add(token); + } + return seen.size > 0 ? [...seen].join(" ") : void 0; +} +function isStrictScopeSuperset(union2, current) { + if (!union2) return false; + const currentSet = new Set((current ?? "").split(/\s+/).filter(Boolean)); + for (const token of union2.split(/\s+/)) if (token && !currentSet.has(token)) return true; + return false; +} +async function resolveAuthorizationCallbackParams(codeOrParams, iss, provider, serverUrl, opts) { + if (typeof codeOrParams === "string") return { + authorizationCode: codeOrParams, + iss + }; + const issParam = codeOrParams.get("iss") ?? void 0; + const code = codeOrParams.get("code"); + if (code) return { + authorizationCode: code, + iss: issParam + }; + let metadata = (await provider.discoveryState?.())?.authorizationServerMetadata; + if (!metadata) try { + metadata = (await discoverOAuthServerInfo(serverUrl, opts)).authorizationServerMetadata; + } catch { + metadata = void 0; + } + if (!metadata) throw new UnauthorizedError("Authorization callback failed and the issuer could not be verified"); + validateAuthorizationResponseIssuer({ + iss: issParam, + expectedIssuer: metadata.issuer, + issParameterSupported: isIssParameterSupported(metadata) + }); + const error2 = codeOrParams.get("error"); + if (error2) throw new OAuthError(error2, codeOrParams.get("error_description") ?? error2, codeOrParams.get("error_uri") ?? void 0); + throw new UnauthorizedError("Authorization callback contained neither `code` nor `error`"); +} +function isClientAuthMethod(method) { + return [ + "client_secret_basic", + "client_secret_post", + "none" + ].includes(method); +} +function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== void 0; + if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) return clientInformation.token_endpoint_auth_method; + if (supportedMethods.length === 0) return hasClientSecret ? "client_secret_basic" : "none"; + if (hasClientSecret && supportedMethods.includes("client_secret_basic")) return "client_secret_basic"; + if (hasClientSecret && supportedMethods.includes("client_secret_post")) return "client_secret_post"; + if (supportedMethods.includes("none")) return "none"; + return hasClientSecret ? "client_secret_post" : "none"; +} +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case "client_secret_basic": + applyBasicAuth(client_id, client_secret, headers); + return; + case "client_secret_post": + applyPostAuth(client_id, client_secret, params); + return; + case "none": + applyPublicAuth(client_id, params); + return; + default: + throw new Error(`Unsupported client authentication method: ${method}`); + } +} +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) throw new Error("client_secret_basic authentication requires a client_secret"); + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set("Authorization", `Basic ${credentials}`); +} +function applyPostAuth(clientId, clientSecret, params) { + params.set("client_id", clientId); + if (clientSecret) params.set("client_secret", clientSecret); +} +function applyPublicAuth(clientId, params) { + params.set("client_id", clientId); +} +function isLoopbackHost(hostname3) { + return hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "[::1]" || hostname3 === "::1"; +} +function assertSecureTokenEndpoint(tokenEndpoint) { + const url2 = new URL(String(tokenEndpoint)); + if (url2.protocol !== "https:" && !isLoopbackHost(url2.hostname)) throw new InsecureTokenEndpointError(url2.href); + return url2; +} +function deriveApplicationType(redirectUris) { + for (const raw of redirectUris ?? []) { + let url2; + try { + url2 = new URL(raw); + } catch { + continue; + } + if (url2.protocol !== "http:" && url2.protocol !== "https:") return "native"; + if (isLoopbackHost(url2.hostname)) return "native"; + } + return "web"; +} +function resolveClientMetadata(provider) { + const clientMetadata = provider.clientMetadata; + return { + ...clientMetadata, + grant_types: clientMetadata.grant_types ?? (provider.redirectUrl === void 0 ? void 0 : ["authorization_code", "refresh_token"]), + application_type: clientMetadata.application_type ?? deriveApplicationType(clientMetadata.redirect_uris) + }; +} +async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : void 0; + const body = input instanceof Response ? await input.text() : input; + try { + const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); + return OAuthError.fromResponse(result); + } catch (error2) { + const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error2}. Raw body: ${body}`; + return new OAuthError(OAuthErrorCode.ServerError, errorMessage); + } +} +async function auth(provider, options) { + try { + return await authInternal(provider, options); + } catch (error2) { + if (error2 instanceof OAuthError) { + if (error2.code === OAuthErrorCode.InvalidClient || error2.code === OAuthErrorCode.UnauthorizedClient) { + await provider.invalidateCredentials?.("client"); + await provider.invalidateCredentials?.("tokens"); + return await authInternal(provider, options); + } else if (error2.code === OAuthErrorCode.InvalidGrant) { + await provider.invalidateCredentials?.("tokens"); + return await authInternal(provider, options); + } + } + throw error2; + } +} +function determineScope(options) { + const { requestedScope, resourceMetadata, authServerMetadata, clientMetadata } = options; + let effectiveScope = requestedScope || resourceMetadata?.scopes_supported?.join(" ") || clientMetadata.scope; + if (effectiveScope && authServerMetadata?.scopes_supported?.includes("offline_access") && !effectiveScope.split(" ").includes("offline_access") && clientMetadata.grant_types?.includes("refresh_token")) effectiveScope = `${effectiveScope} offline_access`; + return effectiveScope; +} +async function authInternal(provider, { serverUrl, authorizationCode, iss, scope, resourceMetadataUrl, fetchFn, skipIssuerMetadataValidation, forceReauthorization }) { + const clientMetadata = resolveClientMetadata(provider); + const cachedState = await provider.discoveryState?.(); + let resourceMetadata; + let authorizationServerUrl; + let metadata; + let freshDiscoveryState; + let effectiveResourceMetadataUrl = resourceMetadataUrl; + if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl); + if (cachedState?.authorizationServerUrl) { + authorizationServerUrl = cachedState.authorizationServerUrl; + resourceMetadata = cachedState.resourceMetadata; + metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { + fetchFn, + skipIssuerValidation: skipIssuerMetadataValidation + }); + if (!resourceMetadata) try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn); + } catch (error2) { + if (error2 instanceof TypeError) throw error2; + } + if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) await provider.saveDiscoveryState?.({ + authorizationServerUrl: String(authorizationServerUrl), + resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), + resourceMetadata, + authorizationServerMetadata: metadata + }); + } else { + const serverInfo = await discoverOAuthServerInfo(serverUrl, { + resourceMetadataUrl: effectiveResourceMetadataUrl, + fetchFn, + skipIssuerMetadataValidation + }); + authorizationServerUrl = serverInfo.authorizationServerUrl; + metadata = serverInfo.authorizationServerMetadata; + resourceMetadata = serverInfo.resourceMetadata; + freshDiscoveryState = { + authorizationServerUrl: String(authorizationServerUrl), + resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), + resourceMetadata, + authorizationServerMetadata: metadata + }; + } + const issuer = metadata?.issuer ?? String(authorizationServerUrl); + const infoCtx = { issuer }; + await provider.saveAuthorizationServerUrl?.(issuer); + if (authorizationCode !== void 0) { + const recordedIssuer = cachedState?.authorizationServerMetadata?.issuer ?? cachedState?.authorizationServerUrl; + if (recordedIssuer === void 0) { + if (provider.saveDiscoveryState !== void 0) throw new AuthorizationServerMismatchError("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier", issuer); + console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352."); + } else if (!issuersMatch(recordedIssuer, issuer)) throw new AuthorizationServerMismatchError(recordedIssuer, issuer); + } + if (freshDiscoveryState) await provider.saveDiscoveryState?.(freshDiscoveryState); + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + if (resource) await provider.saveResourceUrl?.(String(resource)); + const resolvedScope = determineScope({ + requestedScope: scope, + resourceMetadata, + authServerMetadata: metadata, + clientMetadata: provider.clientMetadata + }); + const rawClientInfo = await Promise.resolve(provider.clientInformation(infoCtx)); + let clientInformation = discardIfIssuerMismatch(rawClientInfo, issuer, { canPersistStamp: provider.saveClientInformation !== void 0 }); + if (clientInformation === void 0 && rawClientInfo?.issuer && provider.saveClientInformation === void 0) throw new AuthorizationServerMismatchError(rawClientInfo.issuer, issuer); + if (clientInformation && clientInformation.issuer === void 0) { + clientInformation = { + ...clientInformation, + issuer + }; + await provider.saveClientInformation?.(clientInformation, infoCtx); + } + if (!clientInformation) { + if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code"); + const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) throw new OAuthError(OAuthErrorCode.InvalidClientMetadata, `clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + if (supportsUrlBasedClientId && clientMetadataUrl) { + clientInformation = { + client_id: clientMetadataUrl, + issuer + }; + await provider.saveClientInformation?.(clientInformation, infoCtx); + } else { + if (!provider.saveClientInformation) throw new Error("OAuth client information must be saveable for dynamic registration"); + clientInformation = { + ...await registerClient(authorizationServerUrl, { + metadata, + clientMetadata, + scope: resolvedScope, + fetchFn + }), + issuer + }; + await provider.saveClientInformation(clientInformation, infoCtx); + } + } + const nonInteractiveFlow = !provider.redirectUrl; + if (authorizationCode !== void 0 || nonInteractiveFlow) { + if (authorizationCode !== void 0) validateAuthorizationResponseIssuer({ + iss, + expectedIssuer: metadata?.issuer, + issParameterSupported: isIssParameterSupported(metadata) + }); + const tokens$1 = await fetchToken(provider, authorizationServerUrl, { + metadata, + resource, + authorizationCode, + iss, + scope: resolvedScope, + fetchFn + }); + await provider.saveTokens({ + ...tokens$1, + issuer + }, infoCtx); + return "AUTHORIZED"; + } + let tokens = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer); + if (tokens && tokens.issuer === void 0) { + tokens = { + ...tokens, + issuer + }; + await provider.saveTokens(tokens, infoCtx); + } + if (tokens?.refresh_token && !forceReauthorization) try { + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens({ + ...newTokens, + issuer + }, infoCtx); + return "AUTHORIZED"; + } catch (error2) { + if (error2 instanceof InsecureTokenEndpointError) throw error2; + if (!(error2 instanceof OAuthError) || error2.code === OAuthErrorCode.ServerError) { + } else throw error2; + } + const state = provider.state ? await provider.state() : void 0; + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: resolvedScope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return "REDIRECT"; +} +function validateClientMetadataUrl(url2) { + if (url2 && !isHttpsUrl(url2)) throw new OAuthError(OAuthErrorCode.InvalidClientMetadata, `clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${url2}`); +} +function isHttpsUrl(value) { + if (!value) return false; + try { + const url2 = new URL(value); + return url2.protocol === "https:" && url2.pathname !== "/"; + } catch { + return false; + } +} +async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = resourceUrlFromServerUrl(serverUrl); + if (provider.validateResourceURL) return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); + if (!resourceMetadata) return; + if (!checkResourceAllowed({ + requestedResource: defaultResource, + configuredResource: resourceMetadata.resource + })) throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + return new URL(resourceMetadata.resource); +} +function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get("WWW-Authenticate"); + if (!authenticateHeader) return {}; + const [type, scheme] = authenticateHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !scheme) return {}; + const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0; + let resourceMetadataUrl; + if (resourceMetadataMatch) try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } catch { + } + const scope = extractFieldFromWwwAuth(res, "scope") || void 0; + const error2 = extractFieldFromWwwAuth(res, "error") || void 0; + const errorDescription = extractFieldFromWwwAuth(res, "error_description") || void 0; + return { + resourceMetadataUrl, + scope, + error: error2, + errorDescription + }; +} +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get("WWW-Authenticate"); + if (!wwwAuthHeader) return null; + const pattern = new RegExp(String.raw`${fieldName}=(?:"([^"]+)"|([^\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) { + const result = match[1] || match[2]; + if (result) return result; + } + return null; +} +function extractResourceMetadataUrl(res) { + const authenticateHeader = res.headers.get("WWW-Authenticate"); + if (!authenticateHeader) return; + const [type, scheme] = authenticateHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !scheme) return; + const match = /resource_metadata="([^"]*)"/.exec(authenticateHeader); + if (!match || !match[1]) return; + try { + return new URL(match[1]); + } catch { + return; + } +} +async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, { + protocolVersion: opts?.protocolVersion, + metadataUrl: opts?.resourceMetadataUrl + }); + if (!response || response.status === 404) { + await response?.text?.().catch(() => { + }); + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + await response.text?.().catch(() => { + }); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) { + try { + return await fetchFn(url2, { headers }); + } catch (error2) { + if (!(error2 instanceof TypeError) || !CORS_IS_POSSIBLE) throw error2; + if (headers) try { + return await fetchFn(url2, {}); + } catch (retryError) { + if (!(retryError instanceof TypeError)) throw retryError; + return; + } + return; + } +} +function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) { + if (pathname.endsWith("/")) pathname = pathname.slice(0, -1); + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) { + return await fetchWithCorsRetry(url2, { "MCP-Protocol-Version": protocolVersion }, fetchFn); +} +function shouldAttemptFallback(response, pathname) { + if (!response) return true; + if (pathname === "/") return false; + return response.status >= 400 && response.status < 500 || response.status === 502; +} +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + const issuer = new URL(serverUrl); + const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION; + let url2; + if (opts?.metadataUrl) url2 = new URL(opts.metadataUrl); + else { + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); + url2.search = issuer.search; + } + let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn); + if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) response = await tryMetadataDiscovery(new URL(`/.well-known/${wellKnownType}`, issuer), protocolVersion, fetchFn); + return response; +} +async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { + if (typeof issuer === "string") issuer = new URL(issuer); + if (!authorizationServerUrl) authorizationServerUrl = issuer; + if (typeof authorizationServerUrl === "string") authorizationServerUrl = new URL(authorizationServerUrl); + protocolVersion ??= LATEST_PROTOCOL_VERSION; + const response = await discoverMetadataWithFallback(authorizationServerUrl, "oauth-authorization-server", fetchFn, { + protocolVersion, + metadataServerUrl: authorizationServerUrl + }); + if (!response || response.status === 404) { + await response?.text?.().catch(() => { + }); + return; + } + if (!response.ok) { + await response.text?.().catch(() => { + }); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); + } + return OAuthMetadataSchema.parse(await response.json()); +} +function buildDiscoveryUrls(authorizationServerUrl) { + const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url2.pathname !== "/"; + const urlsToTry = []; + if (!hasPath) { + urlsToTry.push({ + url: new URL("/.well-known/oauth-authorization-server", url2.origin), + type: "oauth" + }, { + url: new URL(`/.well-known/openid-configuration`, url2.origin), + type: "oidc" + }); + return urlsToTry; + } + let pathname = url2.pathname; + if (pathname.endsWith("/")) pathname = pathname.slice(0, -1); + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin), + type: "oauth" + }, { + url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin), + type: "oidc" + }, { + url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin), + type: "oidc" + }); + return urlsToTry; +} +async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION, skipIssuerValidation = false } = {}) { + const headers = { + "MCP-Protocol-Version": protocolVersion, + Accept: "application/json" + }; + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) + continue; + if (!response.ok) { + await response.text?.().catch(() => { + }); + if (response.status >= 400 && response.status < 500 || response.status === 502) continue; + throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`); + } + const parsed = type === "oauth" ? OAuthMetadataSchema.parse(await response.json()) : OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + if (!skipIssuerValidation) { + const expectedIssuer = typeof authorizationServerUrl === "string" ? authorizationServerUrl : authorizationServerUrl.href; + if (!(parsed.issuer === expectedIssuer || expectedIssuer.endsWith("/") && parsed.issuer === expectedIssuer.slice(0, -1))) throw new IssuerMismatchError("metadata", expectedIssuer, parsed.issuer); + } + return parsed; + } +} +async function discoverOAuthServerInfo(serverUrl, opts) { + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } catch (error2) { + if (error2 instanceof TypeError) throw error2; + } + if (!authorizationServerUrl) authorizationServerUrl = String(new URL("/", serverUrl)); + const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { + fetchFn: opts?.fetchFn, + skipIssuerValidation: opts?.skipIssuerMetadataValidation + }); + return { + authorizationServerUrl, + authorizationServerMetadata, + resourceMetadata + }; +} +async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } else authorizationUrl = new URL("/authorize", authorizationServerUrl); + const challenge = await pkceChallenge(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set("client_id", clientInformation.client_id); + authorizationUrl.searchParams.set("code_challenge", codeChallenge); + authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl)); + if (state) authorizationUrl.searchParams.set("state", state); + if (scope) authorizationUrl.searchParams.set("scope", scope); + if (scope?.split(" ").includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent"); + if (resource) authorizationUrl.searchParams.set("resource", resource.href); + return { + authorizationUrl, + codeVerifier + }; +} +function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { + return new URLSearchParams({ + grant_type: "authorization_code", + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); +} +async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { + const tokenUrl = assertSecureTokenEndpoint(metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl)); + const headers = new Headers({ + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json" + }); + if (resource) tokenRequestParams.set("resource", resource.href); + if (addClientAuthentication) await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); + else if (clientInformation) applyClientAuthentication(selectClientAuthMethod(clientInformation, metadata?.token_endpoint_auth_methods_supported ?? []), clientInformation, headers, tokenRequestParams); + const response = await (fetchFn ?? fetch)(tokenUrl, { + method: "POST", + headers, + body: tokenRequestParams + }); + if (!response.ok) throw await parseErrorResponse(response); + const json2 = await response.json(); + try { + return OAuthTokensSchema.parse(json2); + } catch (parseError) { + if (typeof json2 === "object" && json2 !== null && "error" in json2) throw await parseErrorResponse(JSON.stringify(json2)); + throw parseError; + } +} +async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, iss, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { + validateAuthorizationResponseIssuer({ + iss, + expectedIssuer: metadata?.issuer, + issParameterSupported: isIssParameterSupported(metadata) + }); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams: prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri), + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); +} +async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + return { + refresh_token: refreshToken, + ...await executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams: new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: refreshToken + }), + clientInformation, + addClientAuthentication, + resource, + fetchFn + }) + }; +} +async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, iss, scope, fetchFn } = {}) { + if (authorizationCode !== void 0) validateAuthorizationResponseIssuer({ + iss, + expectedIssuer: metadata?.issuer, + issParameterSupported: isIssParameterSupported(metadata) + }); + const effectiveScope = scope ?? provider.clientMetadata.scope; + let tokenRequestParams; + if (provider.prepareTokenRequest) tokenRequestParams = await provider.prepareTokenRequest(effectiveScope); + if (!tokenRequestParams) { + if (!authorizationCode) throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required"); + if (!provider.redirectUrl) throw new Error("redirectUrl is required for authorization_code flow"); + tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, await provider.codeVerifier(), provider.redirectUrl); + } + const clientInformation = await provider.clientInformation({ issuer: metadata?.issuer ?? String(authorizationServerUrl) }); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation: clientInformation ?? void 0, + addClientAuthentication: provider.addClientAuthentication, + resource, + fetchFn + }); +} +async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration"); + registrationUrl = new URL(metadata.registration_endpoint); + } else registrationUrl = new URL("/register", authorizationServerUrl); + const submittedMetadata = { + ...clientMetadata, + ...scope === void 0 ? {} : { scope } + }; + const response = await (fetchFn ?? fetch)(registrationUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(submittedMetadata) + }); + if (!response.ok) throw new RegistrationRejectedError({ + status: response.status, + body: await response.text(), + submittedMetadata + }); + return OAuthClientInformationFullSchema.parse(await response.json()); +} +function createPrivateKeyJwtAuth(options) { + return async (_headers, params, url2, metadata) => { + if (globalThis.crypto === void 0) throw new TypeError("crypto is not available, please ensure you have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)"); + const jose = await Promise.resolve().then(() => (init_webapi(), webapi_exports)); + const audience = String(options.audience ?? metadata?.issuer ?? url2); + const lifetimeSeconds = options.lifetimeSeconds ?? 300; + const now = Math.floor(Date.now() / 1e3); + const jti = `${Date.now()}-${Math.random().toString(36).slice(2)}`; + const baseClaims = { + iss: options.issuer, + sub: options.subject, + aud: audience, + exp: now + lifetimeSeconds, + iat: now, + jti + }; + const claims = options.claims ? { + ...baseClaims, + ...options.claims + } : baseClaims; + const alg = options.alg; + let key; + if (typeof options.privateKey === "string") if (alg.startsWith("RS") || alg.startsWith("ES") || alg.startsWith("PS")) key = await jose.importPKCS8(options.privateKey, alg); + else if (alg.startsWith("HS")) key = new TextEncoder().encode(options.privateKey); + else throw new Error(`Unsupported algorithm ${alg}`); + else if (options.privateKey instanceof Uint8Array) key = alg.startsWith("HS") ? options.privateKey : await jose.importPKCS8(new TextDecoder().decode(options.privateKey), alg); + else key = await jose.importJWK(options.privateKey, alg); + const assertion = await new jose.SignJWT(claims).setProtectedHeader({ + alg, + typ: "JWT" + }).setIssuer(options.issuer).setSubject(options.subject).setAudience(audience).setIssuedAt(now).setExpirationTime(now + lifetimeSeconds).setJti(jti).sign(key); + params.set("client_assertion", assertion); + params.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); + }; +} +function keyOf(key) { + return `${key.method}\0${JSON.stringify([key.partition ?? "", key.params ?? ""])}`; +} +function genKey(method, params) { + return params === void 0 ? method : `${method}\0${params}`; +} +function encodeCacheValue(value) { + let json2; + try { + json2 = JSON.stringify(value); + } catch (error2) { + throw new TypeError(`cache value is not JSON-serializable: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + if (typeof json2 !== "string") throw new TypeError("cache value is not JSON-serializable: it has no JSON representation"); + return json2; +} +function classifyProbeOutcome(outcome, context) { + switch (outcome.kind) { + case "result": + return classifyResult(outcome.result, context); + case "rpc-error": + return classifyRpcError(outcome, context); + case "http-error": + return classifyHttpError(outcome, context); + case "network-error": + return classifyNetworkError(outcome.error, context); + case "auth-required": + return { + kind: "error", + error: outcome.error + }; + case "closed": + if (context.transportKind === "stdio") return { kind: "legacy" }; + return classifyNetworkError(/* @__PURE__ */ new Error("Connection closed during the version negotiation probe"), context); + case "timeout": + if (context.transportKind === "stdio") return { kind: "legacy" }; + return { + kind: "error", + error: new SdkError(SdkErrorCode.RequestTimeout, `Version negotiation probe timed out after ${outcome.timeoutMs}ms`, { timeout: outcome.timeoutMs }) + }; + } +} +function classifyResult(result, context) { + const parsed = codecForVersion(MODERN_WIRE_REVISION).validateResult("server/discover", result); + if (!parsed.ok) return { kind: "legacy" }; + const supportedVersions = parsed.value.supportedVersions; + const overlap = context.clientModernVersions.find((version2) => supportedVersions.includes(version2)); + if (overlap !== void 0) return { + kind: "modern", + version: overlap, + discover: parsed.value + }; + if (context.fallbackAvailable) return { kind: "legacy" }; + return { + kind: "error", + error: new UnsupportedProtocolVersionError({ + supported: [...supportedVersions], + requested: context.requestedVersion + }) + }; +} +function classifyRpcError(outcome, context) { + const { code, message: message2, data } = outcome; + if (code === UNSUPPORTED_PROTOCOL_VERSION) { + const supported2 = parseSupportedList(data); + if (supported2 === void 0) return { kind: "legacy" }; + const error2 = new UnsupportedProtocolVersionError({ + supported: supported2, + requested: parseRequested(data) ?? context.requestedVersion + }, message2); + const supportedModern = modernProtocolVersions(supported2); + const mutual = context.clientModernVersions.find((version2) => supportedModern.includes(version2)); + if (mutual !== void 0) return { + kind: "corrective", + version: mutual, + error: error2 + }; + if (supportedModern.length > 0) return { + kind: "error", + error: error2 + }; + return context.fallbackAvailable ? { kind: "legacy" } : { + kind: "error", + error: error2 + }; + } + if (NOT_PROBE_RECOGNIZED.has(code)) return { kind: "legacy" }; + return { kind: "legacy" }; +} +function classifyHttpError(outcome, context) { + const rpcError = parseJsonRpcErrorBody(outcome.body); + if (rpcError !== void 0) return classifyRpcError(rpcError, context); + return { kind: "legacy" }; +} +function classifyNetworkError(error2, context) { + if (context.environment === "browser" && isOpaqueFetchTypeError(error2)) return { kind: "legacy" }; + return { + kind: "error", + error: new SdkError(SdkErrorCode.EraNegotiationFailed, `Version negotiation probe failed: ${describeError(error2)}`, { cause: error2 }) + }; +} +function isOpaqueFetchTypeError(error2) { + return error2 instanceof TypeError || error2 instanceof Error && error2.name === "TypeError"; +} +function describeError(error2) { + return error2 instanceof Error ? error2.message : String(error2); +} +function parseSupportedList(data) { + if (typeof data !== "object" || data === null) return void 0; + const supported2 = data.supported; + if (!Array.isArray(supported2) || supported2.length === 0 || !supported2.every((v) => typeof v === "string")) return; + return supported2; +} +function parseRequested(data) { + if (typeof data !== "object" || data === null) return void 0; + const requested = data.requested; + return typeof requested === "string" ? requested : void 0; +} +function parseJsonRpcErrorBody(body) { + if (body === void 0 || body === "") return void 0; + let parsed; + try { + parsed = JSON.parse(body); + } catch { + return; + } + if (typeof parsed !== "object" || parsed === null) return void 0; + const error2 = parsed.error; + if (typeof error2 !== "object" || error2 === null) return void 0; + const { code, message: message2, data } = error2; + if (typeof code !== "number") return void 0; + return { + code, + message: typeof message2 === "string" ? message2 : "", + data + }; +} +function resolveVersionNegotiation(options, supportedProtocolVersionsOption) { + const mode = options?.mode ?? DEFAULT_VERSION_NEGOTIATION_MODE; + if (mode === "legacy") return { kind: "legacy" }; + const probe = options?.probe ?? {}; + if (typeof mode === "object") { + if (!isModernProtocolVersion(mode.pin)) throw new TypeError(`versionNegotiation: { pin: '${mode.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`); + return { + kind: "pin", + version: mode.pin, + probe + }; + } + const explicitModern = supportedProtocolVersionsOption ? modernProtocolVersions(supportedProtocolVersionsOption) : []; + return { + kind: "auto", + modernVersions: explicitModern.length > 0 ? explicitModern : [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + fallbackAvailable: supportedProtocolVersionsOption ? legacyProtocolVersions(supportedProtocolVersionsOption).length > 0 : true, + probe + }; +} +function detectProbeEnvironment() { + const g = globalThis; + return g.window !== void 0 && g.document !== void 0 ? "browser" : "node"; +} +function detectProbeTransportKind(transport) { + return "stderr" in transport && "pid" in transport ? "stdio" : "http"; +} +function disarmSpentCloseGuard(transport) { + const disarm = pendingSpentCloseGuards.get(transport); + pendingSpentCloseGuards.delete(transport); + disarm?.(); +} +function buildProbeRequest(id, protocolVersion, clientInfo, capabilities) { + return { + jsonrpc: "2.0", + id, + method: "server/discover", + params: { _meta: codecForVersion(protocolVersion).outboundEnvelope({ + protocolVersion, + clientInfo, + clientCapabilities: capabilities + }) } + }; +} +function normalizeReply(reply, timeoutMs) { + switch (reply.kind) { + case "response": + return reply.error === void 0 ? { + kind: "result", + result: reply.result + } : { + kind: "rpc-error", + ...reply.error + }; + case "send-error": { + const error2 = reply.error; + if (error2 instanceof SdkHttpError) { + const text = error2.data?.text; + return { + kind: "http-error", + status: error2.data.status, + body: typeof text === "string" ? text : void 0 + }; + } + if (error2 instanceof UnauthorizedError || error2 instanceof Error && error2.name === "UnauthorizedError") return { + kind: "auth-required", + error: error2 + }; + return { + kind: "network-error", + error: error2 + }; + } + case "closed": + return { kind: "closed" }; + case "timeout": + return { + kind: "timeout", + timeoutMs + }; + } +} +async function negotiateEra(negotiation, deps) { + const timeoutMs = negotiation.probe.timeoutMs ?? deps.defaultTimeoutMs; + const maxRetries = Math.max(0, negotiation.probe.maxRetries ?? 0); + const clientModernVersions = negotiation.kind === "pin" ? [negotiation.version] : negotiation.modernVersions; + const fallbackAvailable = negotiation.kind === "auto" && negotiation.fallbackAvailable; + const window = await ProbeWindow.open(deps.transport); + const probe = async () => { + let requestedVersion = clientModernVersions[0]; + let correctiveUsed = false; + let timeoutRetriesRemaining = maxRetries; + for (; ; ) { + const reply = await window.exchange((id) => buildProbeRequest(id, requestedVersion, deps.clientInfo, deps.capabilities), timeoutMs); + if (reply.kind === "timeout" && timeoutRetriesRemaining > 0) { + timeoutRetriesRemaining--; + continue; + } + const outcome = normalizeReply(reply, timeoutMs); + const verdict = classifyProbeOutcome(outcome, { + clientModernVersions, + requestedVersion, + fallbackAvailable, + environment: deps.environment, + transportKind: deps.transportKind + }); + switch (verdict.kind) { + case "modern": + return { + era: "modern", + version: verdict.version, + discover: verdict.discover + }; + case "corrective": + if (correctiveUsed) throw verdict.error; + correctiveUsed = true; + requestedVersion = verdict.version; + continue; + case "legacy": { + const closedCause = outcome.kind === "closed" ? "the connection closed during the server/discover probe" : void 0; + if (negotiation.kind === "pin") throw new SdkError(SdkErrorCode.EraNegotiationFailed, closedCause === void 0 ? `Version negotiation failed: the server did not offer pinned protocol version ${negotiation.version} via server/discover (no fallback in pin mode)` : `Version negotiation failed: ${closedCause} before the server offered pinned protocol version ${negotiation.version} (no fallback in pin mode)`); + if (!negotiation.fallbackAvailable) throw new SdkError(SdkErrorCode.EraNegotiationFailed, closedCause === void 0 ? "Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to" : `Version negotiation failed: ${closedCause} and this client supports no pre-2026-07-28 protocol version to fall back to`); + if (closedCause !== void 0 && deps.disposableProbe !== true) throw new SdkError(SdkErrorCode.EraNegotiationFailed, `Version negotiation failed: ${closedCause} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`); + return { era: "legacy" }; + } + case "error": + throw verdict.error; + } + } + }; + let result; + try { + result = await probe(); + } catch (error2) { + window.detach(); + throw error2; + } + window.release(); + return result; +} +function readStdioServerParams(transport) { + const proto = Object.getPrototypeOf(transport); + if (proto === null || !Object.prototype.hasOwnProperty.call(proto, "_dispose")) return; + const params = transport._serverParams; + return typeof params === "object" && params !== null && typeof params.command === "string" ? params : void 0; +} +async function negotiateStdioViaSibling(negotiation, sessionTransport, params, deps) { + const SiblingTransport = sessionTransport.constructor; + const sibling = new SiblingTransport({ + ...params, + stderr: "ignore" + }); + const originalClose = sessionTransport.close; + let callerClosed = false; + let signalClosed; + const closedSignal = new Promise((_, reject) => { + signalClosed = () => reject(callerCloseAbortError()); + }); + sessionTransport.close = async function() { + callerClosed = true; + signalClosed?.(); + return originalClose.call(sessionTransport); + }; + let result; + try { + const negotiated = negotiateEra(negotiation, { + ...deps, + transport: sibling, + transportKind: "stdio", + disposableProbe: true + }); + negotiated.catch(() => { + }); + result = await Promise.race([negotiated, closedSignal]); + } finally { + await disposeSibling(sibling); + sessionTransport.close = originalClose; + } + if (callerClosed) throw callerCloseAbortError(); + return result; +} +function callerCloseAbortError() { + return new SdkError(SdkErrorCode.EraNegotiationFailed, "Version negotiation failed: the transport was closed during the server/discover probe"); +} +async function disposeSibling(sibling) { + try { + const dispose = sibling._dispose; + await (typeof dispose === "function" ? dispose.call(sibling) : sibling.close()); + } catch { + } +} +function serverInfoFromDiscover(discover) { + const fromMeta = discover._meta?.[SERVER_INFO_META_KEY]; + return isSpecType.Implementation(fromMeta) ? fromMeta : void 0; +} +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== "object") return; + if (schema.type === "object" && schema.properties && typeof schema.properties === "object") { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) obj[key] = propSchema.default; + if (obj[key] !== void 0) applyElicitationDefaults(propSchema, obj[key]); + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data); + } + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data); + } +} +function getSupportedElicitationModes(capabilities) { + if (!capabilities) return { + supportsFormMode: false, + supportsUrlMode: false + }; + const hasFormCapability = capabilities.form !== void 0; + const hasUrlCapability = capabilities.url !== void 0; + return { + supportsFormMode: hasFormCapability || !hasFormCapability && !hasUrlCapability, + supportsUrlMode: hasUrlCapability + }; +} +function validatePrior(prior) { + if (typeof prior === "object" && prior !== null) { + if (prior.kind === "legacy" && !("supportedVersions" in prior) && !("discover" in prior)) return prior; + if (prior.kind === "modern" && DiscoverResultSchema.safeParse(prior.discover).success) return prior; + } + throw new SdkError(SdkErrorCode.EraNegotiationFailed, "connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }"); +} +async function requestJwtAuthorizationGrant(options) { + const { tokenEndpoint, audience, resource, idToken, clientId, clientSecret, scope, fetchFn = fetch } = options; + const tokenUrl = assertSecureTokenEndpoint(tokenEndpoint); + const params = new URLSearchParams({ + grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", + requested_token_type: "urn:ietf:params:oauth:token-type:id-jag", + audience: String(audience), + resource: String(resource), + subject_token: idToken, + subject_token_type: "urn:ietf:params:oauth:token-type:id_token", + client_id: clientId + }); + if (clientSecret) params.set("client_secret", clientSecret); + if (scope) params.set("scope", scope); + const response = await fetchFn(tokenUrl, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: params.toString() + }); + if (!response.ok) { + const errorBody = await response.json().catch(() => ({})); + const parseResult$1 = OAuthErrorResponseSchema.safeParse(errorBody); + if (parseResult$1.success) { + const { error: error2, error_description } = parseResult$1.data; + throw new Error(`Token exchange failed: ${error2}${error_description ? ` - ${error_description}` : ""}`); + } + throw new Error(`Token exchange failed with status ${response.status}: ${JSON.stringify(errorBody)}`); + } + const parseResult = IdJagTokenExchangeResponseSchema.safeParse(await response.json()); + if (!parseResult.success) throw new Error(`Invalid token exchange response: ${parseResult.error.message}`); + return { + jwtAuthGrant: parseResult.data.access_token, + expiresIn: parseResult.data.expires_in, + scope: parseResult.data.scope + }; +} +async function discoverAndRequestJwtAuthGrant(options) { + const { idpUrl, fetchFn = fetch, ...restOptions } = options; + const metadata = await discoverAuthorizationServerMetadata(String(idpUrl), { fetchFn }); + if (!metadata?.token_endpoint) throw new Error(`Failed to discover token endpoint for IdP: ${idpUrl}`); + return requestJwtAuthorizationGrant({ + ...restOptions, + tokenEndpoint: metadata.token_endpoint, + fetchFn + }); +} +async function exchangeJwtAuthGrant(options) { + const { tokenEndpoint, jwtAuthGrant, clientId, clientSecret, authMethod = "client_secret_basic", fetchFn = fetch } = options; + const tokenUrl = assertSecureTokenEndpoint(tokenEndpoint); + const params = new URLSearchParams({ + grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", + assertion: jwtAuthGrant + }); + const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded" }); + applyClientAuthentication(authMethod, { + client_id: clientId, + client_secret: clientSecret + }, headers, params); + const response = await fetchFn(tokenUrl, { + method: "POST", + headers, + body: params.toString() + }); + if (!response.ok) { + const errorBody = await response.json().catch(() => ({})); + const parseResult$1 = OAuthErrorResponseSchema.safeParse(errorBody); + if (parseResult$1.success) { + const { error: error2, error_description } = parseResult$1.data; + throw new Error(`JWT grant exchange failed: ${error2}${error_description ? ` - ${error_description}` : ""}`); + } + throw new Error(`JWT grant exchange failed with status ${response.status}: ${JSON.stringify(errorBody)}`); + } + const responseBody = await response.json(); + const parseResult = OAuthTokensSchema.safeParse(responseBody); + if (!parseResult.success) throw new Error(`Invalid token response: ${parseResult.error.message}`); + return parseResult.data; +} +function anySignal(a, b) { + if (typeof AbortSignal.any === "function") return AbortSignal.any([a, b]); + const controller = new AbortController(); + if (a.aborted) return controller.abort(a.reason), controller.signal; + if (b.aborted) return controller.abort(b.reason), controller.signal; + const cleanup = () => { + a.removeEventListener("abort", onA); + b.removeEventListener("abort", onB); + }; + function onA() { + cleanup(); + controller.abort(a.reason); + } + function onB() { + cleanup(); + controller.abort(b.reason); + } + a.addEventListener("abort", onA, { once: true }); + b.addEventListener("abort", onB, { once: true }); + return controller.signal; +} +function fromJsonSchema2(schema, validator) { + return fromJsonSchema(schema, validator ?? (_defaultValidator ??= new AjvJsonSchemaValidator())); +} +var OAuthClientFlowError, IssuerMismatchError, RegistrationRejectedError, InsecureTokenEndpointError, AuthorizationServerMismatchError, InsufficientScopeError, UnauthorizedError, AUTHORIZATION_CODE_RESPONSE_TYPE, AUTHORIZATION_CODE_CHALLENGE_METHOD, ClientCredentialsProvider, PrivateKeyJwtProvider, StaticPrivateKeyJwtProvider, CrossAppAccessProvider, CAP_EXEMPT_METHODS, InMemoryResponseCacheStore, MAX_CACHE_TTL_MS, ClientResponseCache, UNSUPPORTED_PROTOCOL_VERSION, NOT_PROBE_RECOGNIZED, DEFAULT_VERSION_NEGOTIATION_MODE, ProbeWindow, pendingSpentCloseGuards, LIST_CHANGED_EVICTIONS, DEFAULT_LIST_MAX_PAGES, Client, withOAuth, withLogging, applyMiddlewares, createMiddleware, SseError, SSEClientTransport, DEFAULT_MAX_STEP_UP_RETRIES, DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS, RESERVED_REQUEST_HEADER_NAMES, StreamableHTTPClientTransport, _defaultValidator; +var init_dist3 = __esm({ + "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/index.mjs"() { + init_src_CgOncMok(); + init_shimsNode(); + init_index_node(); + init_dist2(); + init_stream(); + OAuthClientFlowError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthClientFlowError" }); + } + 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(message2) { + super(message2); + this.name = new.target.name; + stampErrorBrands(this, new.target); + } + }; + IssuerMismatchError = class extends OAuthClientFlowError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.IssuerMismatchError" }); + } + /** Which check failed — metadata echo (RFC 8414 §3.3) or authorization-response `iss` (RFC 9207). */ + kind; + /** The issuer the client expected (from validated metadata / discovery input). */ + expected; + /** The issuer value that was received. Attacker-controllable on the `'authorization_response'` path. */ + received; + constructor(kind, expected, received) { + super(`Issuer mismatch in ${kind === "metadata" ? "authorization server metadata (RFC 8414 \xA73.3)" : "authorization response (RFC 9207)"}: expected ${JSON.stringify(expected)}, received ${JSON.stringify(received)}`); + this.kind = kind; + this.expected = expected; + this.received = received; + } + }; + RegistrationRejectedError = class extends OAuthClientFlowError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.RegistrationRejectedError" }); + } + /** HTTP status code returned by the registration endpoint. */ + status; + /** Raw response body text (typically an RFC 7591 error JSON document). */ + body; + /** The exact client metadata that was POSTed (after SDK defaults were applied). */ + submittedMetadata; + constructor(args) { + super(`Dynamic Client Registration rejected (HTTP ${args.status}): ${args.body}`); + this.status = args.status; + this.body = args.body; + this.submittedMetadata = args.submittedMetadata; + } + }; + InsecureTokenEndpointError = class extends OAuthClientFlowError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.InsecureTokenEndpointError" }); + } + /** The token endpoint URL that was rejected. */ + tokenEndpoint; + constructor(tokenEndpoint) { + super(`Refusing to send credentials to non-https token endpoint '${tokenEndpoint}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`); + this.tokenEndpoint = tokenEndpoint; + } + }; + AuthorizationServerMismatchError = class extends OAuthClientFlowError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.AuthorizationServerMismatchError" }); + } + constructor(recordedIssuer, currentIssuer) { + super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(recordedIssuer)}, callback resolved ${JSON.stringify(currentIssuer)}); refusing to send authorization_code/code_verifier to a different token endpoint`); + this.recordedIssuer = recordedIssuer; + this.currentIssuer = currentIssuer; + } + }; + InsufficientScopeError = class extends OAuthClientFlowError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.InsufficientScopeError" }); + } + /** The `scope` value from the `WWW-Authenticate` challenge — the scopes the resource server says are required. */ + requiredScope; + /** The `resource_metadata` URL from the `WWW-Authenticate` challenge, if present. */ + resourceMetadataUrl; + /** The `error_description` from the `WWW-Authenticate` challenge, if present. */ + errorDescription; + constructor(init) { + super(`Insufficient scope${init.requiredScope ? `: required "${init.requiredScope}"` : ""}`); + this.requiredScope = init.requiredScope; + this.resourceMetadataUrl = init.resourceMetadataUrl; + this.errorDescription = init.errorDescription; + } + }; + UnauthorizedError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnauthorizedError" }); + } + 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(message2) { + super(message2 ?? "Unauthorized"); + this.name = "UnauthorizedError"; + stampErrorBrands(this, new.target); + } + }; + AUTHORIZATION_CODE_RESPONSE_TYPE = "code"; + AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256"; + ClientCredentialsProvider = class { + _tokens; + _clientInfo; + _clientMetadata; + constructor(options) { + this._clientInfo = { + client_id: options.clientId, + client_secret: options.clientSecret, + issuer: options.expectedIssuer + }; + this._clientMetadata = { + client_name: options.clientName ?? "client-credentials-client", + redirect_uris: [], + grant_types: ["client_credentials"], + token_endpoint_auth_method: "client_secret_basic", + scope: options.scope + }; + } + get redirectUrl() { + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error("redirectToAuthorization is not used for client_credentials flow"); + } + saveCodeVerifier() { + } + codeVerifier() { + throw new Error("codeVerifier is not used for client_credentials flow"); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: "client_credentials" }); + if (scope) params.set("scope", scope); + return params; + } + }; + PrivateKeyJwtProvider = class { + _tokens; + _clientInfo; + _clientMetadata; + addClientAuthentication; + constructor(options) { + this._clientInfo = { + client_id: options.clientId, + issuer: options.expectedIssuer + }; + this._clientMetadata = { + client_name: options.clientName ?? "private-key-jwt-client", + redirect_uris: [], + grant_types: ["client_credentials"], + token_endpoint_auth_method: "private_key_jwt", + scope: options.scope + }; + this.addClientAuthentication = createPrivateKeyJwtAuth({ + issuer: options.clientId, + subject: options.clientId, + privateKey: options.privateKey, + alg: options.algorithm, + lifetimeSeconds: options.jwtLifetimeSeconds, + claims: options.claims + }); + } + get redirectUrl() { + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error("redirectToAuthorization is not used for client_credentials flow"); + } + saveCodeVerifier() { + } + codeVerifier() { + throw new Error("codeVerifier is not used for client_credentials flow"); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: "client_credentials" }); + if (scope) params.set("scope", scope); + return params; + } + }; + StaticPrivateKeyJwtProvider = class { + _tokens; + _clientInfo; + _clientMetadata; + addClientAuthentication; + constructor(options) { + this._clientInfo = { + client_id: options.clientId, + issuer: options.expectedIssuer + }; + this._clientMetadata = { + client_name: options.clientName ?? "static-private-key-jwt-client", + redirect_uris: [], + grant_types: ["client_credentials"], + token_endpoint_auth_method: "private_key_jwt", + scope: options.scope + }; + const assertion = options.jwtBearerAssertion; + this.addClientAuthentication = async (_headers, params) => { + params.set("client_assertion", assertion); + params.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); + }; + } + get redirectUrl() { + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error("redirectToAuthorization is not used for client_credentials flow"); + } + saveCodeVerifier() { + } + codeVerifier() { + throw new Error("codeVerifier is not used for client_credentials flow"); + } + prepareTokenRequest(scope) { + const params = new URLSearchParams({ grant_type: "client_credentials" }); + if (scope) params.set("scope", scope); + return params; + } + }; + CrossAppAccessProvider = class { + _tokens; + _clientInfo; + _clientMetadata; + _assertionCallback; + _fetchFn; + _authorizationServerUrl; + _resourceUrl; + _scope; + constructor(options) { + this._clientInfo = { + client_id: options.clientId, + client_secret: options.clientSecret, + issuer: options.expectedIssuer + }; + this._clientMetadata = { + client_name: options.clientName ?? "cross-app-access-client", + redirect_uris: [], + grant_types: ["urn:ietf:params:oauth:grant-type:jwt-bearer"], + token_endpoint_auth_method: "client_secret_basic" + }; + this._assertionCallback = options.assertion; + this._fetchFn = options.fetchFn ?? fetch; + } + get redirectUrl() { + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInfo; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization() { + throw new Error("redirectToAuthorization is not used for jwt-bearer flow"); + } + saveCodeVerifier() { + } + codeVerifier() { + throw new Error("codeVerifier is not used for jwt-bearer flow"); + } + /** + * Saves the authorization server URL discovered during OAuth flow. + * This is called by the auth() function after RFC 9728 discovery. + */ + saveAuthorizationServerUrl(authorizationServerUrl) { + this._authorizationServerUrl = authorizationServerUrl; + } + /** + * Returns the cached authorization server URL if available. + */ + authorizationServerUrl() { + return this._authorizationServerUrl; + } + /** + * Saves the resource URL discovered during OAuth flow. + * This is called by the auth() function after RFC 9728 discovery. + */ + saveResourceUrl(resourceUrl) { + this._resourceUrl = resourceUrl; + } + /** + * Returns the cached resource URL if available. + */ + resourceUrl() { + return this._resourceUrl; + } + async prepareTokenRequest(scope) { + const authServerUrl = this._authorizationServerUrl; + const resourceUrl = this._resourceUrl; + if (!authServerUrl) throw new Error("Authorization server URL not available. Ensure auth() has been called first."); + if (!resourceUrl) throw new Error("Resource URL not available \u2014 server may not implement RFC 9728 Protected Resource Metadata (required for Cross-App Access), or auth() has not been called"); + this._scope = scope; + const jwtAuthGrant = await this._assertionCallback({ + authorizationServerUrl: authServerUrl, + resourceUrl, + scope: this._scope, + fetchFn: this._fetchFn + }); + const params = new URLSearchParams({ + grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", + assertion: jwtAuthGrant + }); + if (scope) params.set("scope", scope); + return params; + } + }; + CAP_EXEMPT_METHODS = /* @__PURE__ */ new Set([ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "server/discover" + ]); + InMemoryResponseCacheStore = class { + _entries = /* @__PURE__ */ new Map(); + _maxEntries; + _stamp = 0; + /** Count of held entries that are subject to the cap (i.e. not in {@linkcode CAP_EXEMPT_METHODS}). */ + _cappedSize = 0; + constructor(options) { + this._maxEntries = options?.maxEntries ?? 512; + } + /** Number of held entries (for diagnostics / bounding tests). */ + get size() { + return this._entries.size; + } + get(key) { + return this._entries.get(keyOf(key)); + } + set(key, entry) { + const k = keyOf(key); + const exempt = CAP_EXEMPT_METHODS.has(key.method); + const isNew = !this._entries.has(k); + if (!exempt && isNew && this._maxEntries > 0 && this._cappedSize >= this._maxEntries) { + for (const oldKey of this._entries.keys()) if (!CAP_EXEMPT_METHODS.has(oldKey.slice(0, oldKey.indexOf("\0")))) { + this._entries.delete(oldKey); + this._cappedSize--; + break; + } + } + const stamp = ++this._stamp; + this._entries.set(k, { + ...entry, + stamp + }); + if (isNew && !exempt) this._cappedSize++; + return stamp; + } + delete(key) { + if (this._entries.delete(keyOf(key)) && !CAP_EXEMPT_METHODS.has(key.method)) this._cappedSize--; + } + evict(method) { + const prefix = `${method}\0`; + const exempt = CAP_EXEMPT_METHODS.has(method); + for (const k of this._entries.keys()) if (k.startsWith(prefix)) { + this._entries.delete(k); + if (!exempt) this._cappedSize--; + } + } + clear() { + this._entries.clear(); + this._cappedSize = 0; + } + }; + MAX_CACHE_TTL_MS = 864e5; + ClientResponseCache = class { + /** + * Per-logical-key eviction-generation counter. {@linkcode evict} (whole + * method) and {@linkcode evictKey} (single `{method, params}`) bump it + * before touching the store; {@linkcode captureGeneration} reads it before + * the request; {@linkcode write} skips when it moved — so a `list_changed` + * arriving mid-walk, or a `resources/updated` arriving while a + * `readResource()` for the same URI is in flight, is not overwritten by + * the in-flight request's stale write. The map key is `method` for the + * list singletons and `` `${method}\0${params}` `` for per-URI keys. + * + * Growth is bounded by keys the CLIENT has issued a `captureGeneration` + * for: {@linkcode captureGeneration} records the key (so an interleaved + * {@linkcode evictKey} sees there is an in-flight write to suppress); + * {@linkcode evictKey} only bumps a key that is already recorded — a + * server streaming `notifications/resources/updated` for URIs the client + * has never read therefore cannot grow this map. + */ + _evictionGeneration = /* @__PURE__ */ new Map(); + /** + * `name → Tool` index derived from the cached `tools/list` entry, memoized + * against the entry's `stamp` so it re-derives only when the backing entry + * changes (mcp.d's `cachedTool` pattern). + */ + _toolIndex; + /** + * `name → compiled output-schema validator` derived from the cached + * `tools/list` entry; same stamp-keyed memoization as `_toolIndex`. Typed + * `unknown` so this class stays free of any validator-provider dependency + * — the compile callback supplied to {@linkcode outputValidator} owns the + * concrete type. + */ + _toolOutputValidatorIndex; + /** + * The connected server's identity (`serverInfo.name@version`, the + * transport's `sessionId`, or a client-generated per-connection + * surrogate). Set by the `Client` immediately after a successful connect; + * `''` is the pre-connect sentinel. Every storage partition is derived + * from this (see `_partitionFor`), so two clients sharing one store but + * connected to different servers never collide on `tools/list` and a + * server cannot read another server's `'public'` entries. + */ + _serverIdentity = ""; + constructor(_store, _isUserSupplied, _reportError = () => { + }, _cachePartition = "", _now = Date.now) { + this._store = _store; + this._isUserSupplied = _isUserSupplied; + this._reportError = _reportError; + this._cachePartition = _cachePartition; + this._now = _now; + } + /** The clock used for every freshness computation and check. */ + now() { + return this._now(); + } + /** + * Record the connected server's identity. Called by `Client` immediately + * after a successful connect: `serverInfo.name@version` when the server + * identified itself, else the transport's `sessionId`, else a + * client-generated per-connection surrogate (`serverInfo` is a spec + * SHOULD on 2026-07-28, so anonymous servers exist). Surrogate-keyed + * partitions are NOT stable across reconnects — no identity means no + * cross-connection cache reuse, and a shared long-lived store should + * bound its own size accordingly. Every partition derived after this + * call is scoped to this identity; entries written under the pre-connect + * `''` sentinel are no longer reachable. + */ + setServerIdentity(identity) { + this._serverIdentity = identity; + } + /** + * Derive the storage partition for `scope`. The encoding is + * `JSON.stringify([serverIdentity, principal])` — JSON escaping makes it + * collision-free by construction: a malicious server cannot craft a + * `serverInfo.name`/`version` whose concatenated form bleeds into another + * server's namespace or another principal's slot, regardless of `@` / `|` + * / `"` / NUL in the server-controlled strings. `'public'` → + * `[serverIdentity, '']` (shared within this server); `'private'` → + * `[serverIdentity, cachePartition]`. When `cachePartition` is `''` the + * two coincide. + */ + _partitionFor(scope) { + return JSON.stringify([this._serverIdentity, scope === "public" ? "" : this._cachePartition]); + } + /** + * Two-probe lookup: this client's own (private) partition first, then the + * connected server's shared (public) partition. The shared probe is gated + * on `entry.scope === 'public'` — a co-tenant client that omits + * `cachePartition` writes its `'private'`-scoped entries at the public + * partition, and serving those to a correctly-partitioned client would + * leak private bodies (mcp.d's `cachedEntry` two-probe order; the scope + * gate is defence-in-depth on top of the partition split). When + * `cachePartition` is `''` the two partitions are identical and only one + * probe is issued. + */ + async _probe(method, params) { + const key = { + method, + params: params ?? "" + }; + const ownPartition = this._partitionFor("private"); + const own = await this._store.get({ + ...key, + partition: ownPartition + }); + if (own !== void 0) return own; + const sharedPartition = this._partitionFor("public"); + if (sharedPartition === ownPartition) return void 0; + const shared = await this._store.get({ + ...key, + partition: sharedPartition + }); + return shared?.scope === "public" ? shared : void 0; + } + /** + * Bump the per-method generation (so an in-flight {@linkcode write} for the + * same method becomes a no-op) and drop the connected server's two list + * singletons (own + shared partition; `params: ''`). The generation bump + * is unconditional and FIRST — the {@linkcode write} race guard relies on + * the bump, not on the store's deletes completing. + * + * Eviction is scoped to this client's `[serverIdentity, principal]` + * partitions (mirroring {@linkcode evictKey}) — the method-wide + * `store.evict()` is NOT called, so on a shared store one server's + * `list_changed` cannot wipe a co-tenant's entry. A custom store's + * `delete()` may throw or reject; each partition is guarded + * independently so a failure on one does not skip the other, the failure + * is reported via the constructor's sink, and the call resolves so + * dispatch proceeds. + */ + async evict(method) { + this._evictionGeneration.set(method, (this._evictionGeneration.get(method) ?? 0) + 1); + await this._deleteBoth(method, ""); + } + /** + * Guarded two-partition delete of `{method, params}`: each partition's + * `delete` is independently wrapped so a custom store's failure on one is + * reported and does not skip the other, and the call always resolves. + */ + async _deleteBoth(method, params) { + const ownPartition = this._partitionFor("private"); + const sharedPartition = this._partitionFor("public"); + try { + await this._store.delete({ + method, + params, + partition: ownPartition + }); + } catch (error2) { + this._reportError(error2); + } + if (sharedPartition !== ownPartition) try { + await this._store.delete({ + method, + params, + partition: sharedPartition + }); + } catch (error2) { + this._reportError(error2); + } + } + /** + * Drop the single logical entry `{method, params}` from BOTH the private + * and public partitions for this client's connected server (mcp.d's + * `invalidateLogical`). Used for `notifications/resources/updated`'s + * per-URI eviction. The per-key generation is bumped FIRST (so an + * in-flight {@linkcode write} for the same `{method, params}` becomes a + * no-op and cannot re-cache the now-stale body) but only when the key was + * already recorded by {@linkcode captureGeneration} — bounding the map to + * keys the client has actually read. A custom store's `delete()` may + * throw or reject; each partition's delete is guarded independently so a + * failure on one does not skip the other, and the call resolves so + * dispatch proceeds. + */ + async evictKey(method, params) { + const gk = genKey(method, params); + const current = this._evictionGeneration.get(gk); + if (current !== void 0) this._evictionGeneration.set(gk, current + 1); + await this._deleteBoth(method, params); + } + /** + * Snapshot the eviction generation for `{method, params}` before issuing + * the request (a list walk's page 1, or a `resources/read` for `params`). + * Records the key so an interleaved {@linkcode evictKey} for the same + * `{method, params}` knows there is an in-flight write to suppress and + * bumps; without the record, `evictKey`'s recorded-only bump would skip + * and the stale body would be cached. + */ + captureGeneration(method, params) { + const gk = genKey(method, params); + const current = this._evictionGeneration.get(gk) ?? 0; + this._evictionGeneration.set(gk, current); + return current; + } + /** + * Write `value` under `{method}` unless the per-method generation moved + * since `capturedGen` was taken — a `list_changed` that landed mid-walk has + * already invalidated the result the caller is about to write, and + * overwriting the eviction with the stale aggregate would lose the + * invalidation. + * + * The value is stored as its JSON-serialized document; serialization + * doubles as the mutation barrier, so a caller mutating the returned + * aggregate cannot reach the cache or its derived indices. A value that + * is not JSON-serializable (reachable only via in-process transports) + * fails the write loudly into the `reportError` sink. A custom store + * whose `set()` throws or rejects is routed to the same sink and the + * write resolves — cache bookkeeping never costs the caller a result it + * already fetched. + * + * `freshness` carries the client-computed `expiresAt` (absolute ms epoch, + * `now + ttlMs`) and the server-reported `cacheScope`. The storage + * `partition` is derived from the scope via `_partitionFor`: + * `'public'` → `[serverIdentity, '']` (shared within this server); + * `'private'` → `[serverIdentity, cachePartition]` (so a shared store + * never serves a private entry to another identity). Absent `freshness` + * preserves the substrate write (no `expiresAt`, private partition) — the + * `tools/list` retain-for-schema posture: never served by + * {@linkcode read}'s freshness gate, always readable by + * {@linkcode toolDefinition}. + * + * After storing under the derived partition, the same `{method, params}` + * is deleted from the OPPOSITE partition (mirroring {@linkcode evictKey}'s + * two-partition posture). A server that flips a result's `cacheScope` for + * the same key would otherwise leave the previous entry in the other slot + * — and since `_probe` checks own-partition first, a stale private entry + * would shadow the fresh public one (or a stale public entry would keep + * serving co-tenants). Both store calls are independently guarded so a + * custom store's failure on one does not skip the other. + */ + async write(method, value, capturedGen, freshness) { + if ((this._evictionGeneration.get(genKey(method, freshness?.params)) ?? 0) !== capturedGen) return; + const params = freshness?.params ?? ""; + const ownPartition = this._partitionFor("private"); + const sharedPartition = this._partitionFor("public"); + const partition = (freshness?.scope ?? "private") === "public" ? sharedPartition : ownPartition; + try { + await this._store.set({ + method, + params, + partition + }, { + value: encodeCacheValue(value), + expiresAt: freshness?.expiresAt, + scope: freshness?.scope + }); + } catch (error2) { + this._reportError(error2); + } + if (sharedPartition !== ownPartition) try { + await this._store.delete({ + method, + params, + partition: partition === ownPartition ? sharedPartition : ownPartition + }); + } catch (error2) { + this._reportError(error2); + } + } + /** + * Serve the fresh cached result for `{method, params}`, or `undefined`. + * Lookup is the two-probe order (own-partition then this server's shared + * partition, gated on `scope === 'public'`); freshness is + * `entry.expiresAt > now()` (a missing `expiresAt` is never fresh), + * checked BEFORE decoding so stale entries cost no parse. Every hit is + * freshly parsed, so the caller owns the value outright. An entry whose + * document does not parse or is not an object (corrupted external + * store) is reported, + * deleted, and treated as a miss — deleted because a fresh-but-corrupt + * entry would otherwise re-parse and re-report on every read until its + * `expiresAt` passes. + */ + async read(method, params) { + const entry = await this._probe(method, params); + if (entry?.expiresAt === void 0 || !(entry.expiresAt > this.now())) return void 0; + try { + const parsed = JSON.parse(entry.value); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new TypeError("cached document is not an object"); + return { value: parsed }; + } catch (error2) { + this._reportError(error2); + await this._deleteBoth(method, params ?? ""); + return; + } + } + /** + * Connection reset. The per-instance default store IS cleared + * (connection-scoped); a user-supplied store is NOT — that would defeat + * the only reason to supply one. The generation map and every derived + * index are dropped regardless: they are connection-scoped even when the + * backing store survives, so the next read re-derives from whatever the + * store still holds. The server identity returns to the pre-connect + * sentinel. The default impl is synchronous, so the `MaybePromise` + * return is a plain void here and the caller need not await. + */ + resetForReconnect() { + if (!this._isUserSupplied) this._store.clear(); + this._evictionGeneration.clear(); + this._toolIndex = void 0; + this._toolOutputValidatorIndex = void 0; + this._serverIdentity = ""; + } + /** + * The descriptor for tool `name` taken from the cached `tools/list` entry. + * The `name → Tool` index is memoized against the entry's `stamp` and + * re-derived only when the backing entry changes (mcp.d's `cachedTool`). + * Returns `undefined` only when no `tools/list` response is held at all, + * or the held list does not contain `name`. + * + * Consumed by `callTool()`'s SEP-2243 `_resolveXMcpHeaderScan` (mirroring) + * and, via {@linkcode outputValidator}, its output-schema validation. + */ + async toolDefinition(name) { + const entry = await this._probe("tools/list"); + if (entry === void 0) { + this._toolIndex = void 0; + return; + } + if (this._toolIndex?.stamp !== entry.stamp) { + const list = this._decodeListTools(entry); + const byName = /* @__PURE__ */ new Map(); + if (list !== void 0) for (const tool of list.tools) byName.set(tool.name, tool); + this._toolIndex = { + stamp: entry.stamp, + byName + }; + } + return this._toolIndex.byName.get(name); + } + /** + * The compiled output-schema validator for tool `name`, derived from the + * cached `tools/list` entry — same source and same stamp-keyed + * memoization as {@linkcode toolDefinition}. The `name → validator` index + * re-derives only when the backing entry's stamp changes (a refetched + * `tools/list` recompiles; a `list_changed` eviction drops it). Returns + * `undefined` when no `tools/list` is held, the tool is absent, or it has + * no `outputSchema`. + * + * `compile` is the caller-supplied validator-compile callback (the + * `Client` passes its `_jsonSchemaValidator` wrapper) so this + * class carries no validator-provider dependency. One tool's uncompilable + * `outputSchema` (e.g. an invalid `pattern` regex or unresolvable `$ref`) + * must not poison every other tool's `callTool` — the callback isolates + * that compile error per tool by returning a per-tool error variant which + * the index stores alongside the good ones, and `callTool` surfaces it as + * a typed `InvalidParams` only for that name. Because the error is held on + * this stamp-keyed substrate (not a parallel map), it inherits the + * substrate's invalidation lifecycle: a `list_changed` eviction drops it, + * a refetched `tools/list` re-derives it, and `resetForReconnect` clears + * the lot. + */ + async outputValidator(name, compile) { + const entry = await this._probe("tools/list"); + if (entry === void 0) { + this._toolOutputValidatorIndex = void 0; + return; + } + if (this._toolOutputValidatorIndex?.stamp !== entry.stamp) { + const list = this._decodeListTools(entry) ?? { tools: [] }; + const byName = /* @__PURE__ */ new Map(); + for (const tool of list.tools) { + const compiled = compile(tool); + if (compiled !== void 0) byName.set(tool.name, compiled); + } + this._toolOutputValidatorIndex = { + stamp: entry.stamp, + byName + }; + } + return this._toolOutputValidatorIndex.byName.get(name); + } + /** Parse a held `tools/list` document for the index builders; a document + * that does not parse OR whose `tools` is not an array of objects + * (both mean a corrupted external store) is reported and treated as if + * nothing were held. Callers memoize the outcome against the entry's + * stamp, so a corrupt document costs one parse + report per stamp, not + * per lookup. */ + _decodeListTools(entry) { + try { + const parsed = JSON.parse(entry.value); + if (!Array.isArray(parsed?.tools) || !parsed.tools.every((t) => t !== null && typeof t === "object")) throw new TypeError("cached tools/list document has a malformed tools array"); + return parsed; + } catch (error2) { + this._reportError(error2); + return; + } + } + }; + UNSUPPORTED_PROTOCOL_VERSION = -32022; + NOT_PROBE_RECOGNIZED = /* @__PURE__ */ new Set([ + -32001, + -32020, + -32021 + ]); + DEFAULT_VERSION_NEGOTIATION_MODE = "legacy"; + ProbeWindow = class ProbeWindow2 { + _pending; + _probeCounter = 0; + _savedOnMessage; + _savedOnError; + _savedOnClose; + _closeDelivered = false; + constructor(_transport) { + this._transport = _transport; + this._savedOnMessage = _transport.onmessage; + this._savedOnError = _transport.onerror; + this._savedOnClose = _transport.onclose; + } + static async open(transport) { + const window = new ProbeWindow2(transport); + transport.onmessage = (message2) => { + const pending = window._pending; + if (pending !== void 0 && (isJSONRPCResultResponse(message2) || isJSONRPCErrorResponse(message2)) && message2.id === pending.id) { + window._pending = void 0; + if (isJSONRPCResultResponse(message2)) pending.resolve({ + kind: "response", + result: message2.result + }); + else pending.resolve({ + kind: "response", + error: message2.error + }); + return; + } + }; + transport.onerror = (error2) => { + window._savedOnError?.(error2); + }; + transport.onclose = () => { + const pending = window._pending; + if (pending !== void 0) { + window._pending = void 0; + pending.resolve({ kind: "closed" }); + } + window._closeDelivered = true; + window._savedOnClose?.(); + }; + try { + await transport.start(); + } catch (error2) { + window.detach(); + throw error2; + } + return window; + } + /** + * Send one probe request and await its reply. Probe ids are strings, so they + * never collide with Protocol's numeric ids (e.g. on a shared stdio pipe). + */ + async exchange(buildRequest, timeoutMs) { + const id = `server-discover-probe-${++this._probeCounter}`; + return new Promise((resolve) => { + let settled = false; + const settle = (reply) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (this._pending?.id === id) this._pending = void 0; + resolve(reply); + }; + const timer = setTimeout(() => settle({ kind: "timeout" }), timeoutMs); + this._pending = { + id, + resolve: settle + }; + this._transport.send(buildRequest(id)).catch((error2) => settle({ + kind: "send-error", + error: error2 + })); + }); + } + /** Detach the window's handlers, restoring any the caller pre-set, leaving the transport's own `start` untouched. */ + detach() { + this._pending = void 0; + this._transport.onmessage = this._savedOnMessage; + this._transport.onerror = this._savedOnError; + if (this._closeDelivered && this._savedOnClose !== void 0) { + const saved = this._savedOnClose; + const transport = this._transport; + let spent = false; + const wrapper = () => { + if (!spent) { + spent = true; + return; + } + saved(); + }; + transport.onclose = wrapper; + pendingSpentCloseGuards.set(transport, () => { + if (transport.onclose === wrapper) transport.onclose = saved; + }); + } else this._transport.onclose = this._savedOnClose; + } + /** Detach the handlers and arm the one-shot `start()` pass-through for the `Protocol.connect()` handover. */ + release() { + this.detach(); + const transport = this._transport; + const originalStart = transport.start; + let armed = true; + transport.start = async function() { + if (armed) { + armed = false; + transport.start = originalStart; + return; + } + return originalStart.call(transport); + }; + } + }; + pendingSpentCloseGuards = /* @__PURE__ */ new WeakMap(); + LIST_CHANGED_EVICTIONS = { + "notifications/tools/list_changed": ["tools/list"], + "notifications/prompts/list_changed": ["prompts/list"], + "notifications/resources/list_changed": ["resources/list", "resources/templates/list"] + }; + DEFAULT_LIST_MAX_PAGES = 64; + Client = class extends Protocol { + _serverCapabilities; + _serverVersion; + _capabilities; + _instructions; + _jsonSchemaValidator; + /** + * The response-cache substrate. Owns the backing store, the per-method + * eviction-generation counter, the user-supplied/default flag, and the + * stamp-memoized derived `name → Tool` / `name → output-validator` + * indices — the cache-coordination state that used to live as separate + * private fields here. The internal aggregating walk writes one entry per + * list verb; `list_changed` evicts the matching method; + * `_resetConnectionState` resets the lot. {@linkcode callTool}'s + * output-schema validation reads the derived `outputValidator` index (the + * substrate's first production caller); the stacked SEP-2243 PR wires + * `Mcp-Param-*` mirroring through `toolDefinition` on top. + */ + _cache; + _defaultCacheTtlMs; + _listMaxPages; + _listChangedDebounceTimers = /* @__PURE__ */ new Map(); + /** + * The constructor `listChanged` configuration. Durable across reconnects: + * read fresh on every connect (legacy or modern), never consumed. + */ + _listChangedConfig; + _enforceStrictCapabilities; + _versionNegotiation; + _supportedProtocolVersionsOption; + _inputRequiredDriverConfig; + /** + * Active subscriptions/listen state, keyed by subscription id (= the + * listen request's JSON-RPC id verbatim). The id is a STRING from a + * Client-owned counter (`'listen:' + N`) — JSON-RPC permits string ids, + * and Protocol's numeric `_requestMessageId` counter only ever issues + * numbers, so listen ids cannot collide with ordinary request ids. + */ + _listenState = /* @__PURE__ */ new Map(); + _nextListenId = 0; + /** The auto-opened subscription backing ClientOptions.listChanged on a modern connection. */ + _autoOpenedSubscription; + /** Backing store for {@linkcode getDiscoverResult}. Per-connection. */ + _discoverResult; + /** + * Clears every per-connection field in one place. Called at the start of + * each fresh (non-resuming) connect and from `close()`, so a stale + * negotiated era / server identity / auto-opened subscription cannot + * survive a reconnect. + */ + _resetConnectionState() { + this._negotiatedProtocolVersion = void 0; + this._serverCapabilities = void 0; + this._serverVersion = void 0; + this._instructions = void 0; + this._discoverResult = void 0; + this._autoOpenedSubscription = void 0; + if (this._listenState.size > 0) { + const reason = new SdkError(SdkErrorCode.ConnectionClosed, "subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset"); + for (const entry of this._listenState.values()) entry.settle({ + cause: "remote", + error: reason + }); + } + this._listenState.clear(); + for (const timer of this._listChangedDebounceTimers.values()) clearTimeout(timer); + this._listChangedDebounceTimers.clear(); + this._cache.resetForReconnect(); + } + async close() { + try { + await super.close(); + } finally { + this._resetConnectionState(); + } + } + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + super(options); + this._clientInfo = _clientInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._enforceStrictCapabilities = options?.enforceStrictCapabilities ?? false; + this._versionNegotiation = options?.versionNegotiation; + this._supportedProtocolVersionsOption = options?.supportedProtocolVersions; + this._inputRequiredDriverConfig = resolveInputRequiredDriverConfig(options?.inputRequired); + this._cache = new ClientResponseCache(options?.responseCacheStore ?? new InMemoryResponseCacheStore(), options?.responseCacheStore !== void 0, (error2) => this._reportStoreError(error2), options?.cachePartition ?? ""); + this._defaultCacheTtlMs = options?.defaultCacheTtlMs ?? 0; + this._listMaxPages = options?.listMaxPages ?? DEFAULT_LIST_MAX_PAGES; + if (options?.listChanged) this._listChangedConfig = options.listChanged; + } + buildContext(ctx, _transportInfo) { + return ctx; + } + /** + * Era-keyed direction enforcement for inbound traffic on channels whose + * transport does not classify (e.g. stdio): the 2026-07-28 era has no + * server→client JSON-RPC request channel — server-to-client interactions + * are carried in-band in `input_required` results — and on stdio the + * client must never write JSON-RPC responses. An inbound request arriving + * on a connection that negotiated a modern era is therefore dropped + * (surfaced via `onerror`) rather than answered. Connections on a legacy + * era — and all responses and notifications — keep today's dispatch path. + */ + _shouldDropInbound(message2) { + if (this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion) && isJSONRPCRequest(message2)) return "drop"; + } + /** + * Per-request `_meta` envelope auto-emission (protocol revision 2026-07-28): + * on a connection that negotiated a modern era — auto-negotiated or pinned — + * every outgoing request and notification automatically carries the reserved + * protocol-version / client-info / client-capabilities `_meta` keys (the + * same envelope the connect-time `server/discover` probe sends). + * User-supplied `_meta` keys take precedence over the auto-attached ones. + * + * Legacy-era connections return `undefined`: the envelope seam is a no-op + * and outbound traffic is byte-identical to a 2025 client (the legacy + * `'auto'` fallback included). + */ + _outboundMetaEnvelope() { + const version2 = this._negotiatedProtocolVersion; + if (version2 === void 0) return void 0; + return this._wireCodec().outboundEnvelope({ + protocolVersion: version2, + clientInfo: this._clientInfo, + clientCapabilities: this._capabilities + }); + } + /** + * Wires the multi-round-trip auto-fulfilment engine (protocol revision + * 2026-07-28) into the response funnel: an `input_required` answer is + * fulfilled through the registered elicitation/sampling/roots handlers + * and the original request retried via `flow.retry`, up to + * `inputRequired.maxRounds` rounds. With auto-fulfilment disabled the + * response surfaces as a typed error steering to manual mode. + */ + _resolveNonCompleteResult(decoded, flow) { + if (!this._inputRequiredDriverConfig.autoFulfill) return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type 'input_required' for ${flow.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`, { + resultType: "input_required", + method: flow.request.method + })); + return runInputRequiredFlow({ + getRequestHandler: (method) => this._getRequestHandler(method), + buildContext: (baseCtx) => this.buildContext(baseCtx, void 0), + sessionId: this.transport?.sessionId + }, this._inputRequiredDriverConfig, decoded, flow); + } + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + _setupListChangedHandlers(config2) { + if (config2.tools && this._serverCapabilities?.tools?.listChanged) this._setupListChangedHandler("tools", "notifications/tools/list_changed", config2.tools, async () => { + return (await this.listTools(void 0, { cacheMode: "refresh" })).tools; + }); + if (config2.prompts && this._serverCapabilities?.prompts?.listChanged) this._setupListChangedHandler("prompts", "notifications/prompts/list_changed", config2.prompts, async () => { + return (await this.listPrompts(void 0, { cacheMode: "refresh" })).prompts; + }); + if (config2.resources && this._serverCapabilities?.resources?.listChanged) this._setupListChangedHandler("resources", "notifications/resources/list_changed", config2.resources, async () => { + return (await this.listResources(void 0, { cacheMode: "refresh" })).resources; + }); + } + /** + * 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 Error("Cannot register capabilities after connecting to transport"); + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Configure protocol version negotiation before connecting (equivalent to + * passing `versionNegotiation` at construction time). Can only be called + * before connecting to a transport. Passing `undefined` clears a previously + * configured negotiation, restoring the default `'legacy'` posture. + * + * See {@linkcode ClientOptions | ClientOptions.versionNegotiation} for the mode semantics. + */ + setVersionNegotiation(options) { + if (this.transport) throw new Error("Cannot configure version negotiation after connecting to transport"); + this._versionNegotiation = options; + } + /** + * Enforces client-side validation for `elicitation/create` and `sampling/createMessage` + * regardless of how the handler was registered. + */ + _wrapHandler(method, handler) { + if (method === "elicitation/create") return async (request, ctx) => { + const codec2 = codecForVersion(this._negotiatedProtocolVersion); + let validatedRequest = codec2.validateRequest("elicitation/create", request); + if (!validatedRequest.ok && validatedRequest.reason === "not-in-era") validatedRequest = codec2.validateInputRequest("elicitation/create", request); + if (!validatedRequest.ok) throw new ProtocolError(validatedRequest.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for elicitation/create in the resolved era" : `Invalid elicitation request: ${validatedRequest.message}`); + const { params } = validatedRequest.value; + params.mode = params.mode ?? "form"; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === "form" && !supportsFormMode) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Client does not support form-mode elicitation requests"); + if (params.mode === "url" && !supportsUrlMode) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests"); + const result = await handler(request, ctx); + let validationResult = codec2.validateResult("elicitation/create", result); + if (!validationResult.ok && validationResult.reason === "not-in-era") validationResult = codec2.validateInputResponse("elicitation/create", result); + if (!validationResult.ok) throw new ProtocolError(validationResult.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for elicitation/create in the resolved era" : `Invalid elicitation result: ${validationResult.message}`); + const validatedResult = validationResult.value; + const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0; + if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema && this._capabilities.elicitation?.form?.applyDefaults) try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } catch { + } + return validatedResult; + }; + if (method === "sampling/createMessage") return async (request, ctx) => { + const codec2 = codecForVersion(this._negotiatedProtocolVersion); + let validatedRequest = codec2.validateRequest("sampling/createMessage", request); + if (!validatedRequest.ok && validatedRequest.reason === "not-in-era") validatedRequest = codec2.validateInputRequest("sampling/createMessage", request); + if (!validatedRequest.ok) throw new ProtocolError(validatedRequest.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for sampling/createMessage in the resolved era" : `Invalid sampling request: ${validatedRequest.message}`); + const { params } = validatedRequest.value; + const result = await handler(request, ctx); + const hasTools = Boolean(params.tools || params.toolChoice); + let validatedResult = codec2.samplingResultVariant(hasTools, result); + if (!validatedResult.ok && validatedResult.reason === "not-in-era") validatedResult = codec2.validateInputResponse("sampling/createMessage", result); + if (!validatedResult.ok) throw new ProtocolError(validatedResult.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validatedResult.reason === "not-in-era" ? "No result schema for sampling/createMessage in the resolved era" : `Invalid sampling result: ${validatedResult.message}`); + return validatedResult.value; + }; + return handler; + } + assertCapability(capability, method) { + if (!this._serverCapabilities?.[capability]) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support ${capability} (required for ${method})`); + } + /** + * Connects to a server via the given transport and performs the MCP initialization handshake. + * + * @example Basic usage (stdio) + * ```ts source="./client.examples.ts#Client_connect_stdio" + * const client = new Client({ name: 'my-client', version: '1.0.0' }); + * const transport = new StdioClientTransport({ command: 'my-mcp-server' }); + * await client.connect(transport); + * ``` + * + * @example Streamable HTTP with SSE fallback + * ```ts source="./client.examples.ts#Client_connect_sseFallback" + * const baseUrl = new URL(url); + * + * try { + * // Try modern Streamable HTTP transport first + * const client = new Client({ name: 'my-client', version: '1.0.0' }); + * const transport = new StreamableHTTPClientTransport(baseUrl); + * await client.connect(transport); + * return { client, transport }; + * } catch { + * // Fall back to legacy SSE transport + * const client = new Client({ name: 'my-client', version: '1.0.0' }); + * const transport = new SSEClientTransport(baseUrl); + * await client.connect(transport); + * return { client, transport }; + * } + * ``` + */ + async connect(transport, options) { + if (options?.prior != null) return this._connectFromPrior(transport, validatePrior(options.prior), options); + const negotiation = resolveVersionNegotiation(this._versionNegotiation, this._supportedProtocolVersionsOption); + if (negotiation.kind !== "legacy") return this._connectNegotiated(transport, negotiation, options); + return this._connectPlainLegacy(transport, options); + } + /** + * Plain legacy connect — the pinned 2025 sequence, byte-untouched. The + * `mode: 'legacy'` connect body, shared with the `prior` legacy verdict. + */ + async _connectPlainLegacy(transport, options) { + await super.connect(transport); + if (transport.sessionId !== void 0) { + const negotiatedProtocolVersion = this._negotiatedProtocolVersion; + if (negotiatedProtocolVersion !== void 0) transport.setProtocolVersion?.(negotiatedProtocolVersion); + return; + } + this._resetConnectionState(); + await this._legacyHandshake(transport, options); + } + /** + * The 2025 `initialize` handshake — the body of the plain legacy connect and + * the `'auto'`-mode fallback path (same `initialize` body, zero 2026 headers; + * on the stdio sibling path it opens the session child's fresh pipe, in the + * in-place modes it rides the probed connection). Callers clear the negotiated protocol version before + * the handshake; its completion sets the negotiated (legacy) version. + */ + async _legacyHandshake(transport, options) { + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + try { + const offeredVersion = legacyVersions[0]; + if (offeredVersion === void 0) throw new SdkError(SdkErrorCode.EraNegotiationFailed, "Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version"); + const result = await this.request({ + method: "initialize", + params: { + protocolVersion: offeredVersion, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, options); + if (result === void 0) throw new Error(`Server sent invalid initialize result: ${result}`); + if (!legacyVersions.includes(result.protocolVersion)) throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + this._cache.setServerIdentity(this._deriveServerIdentity(transport)); + if (transport.setProtocolVersion) transport.setProtocolVersion(result.protocolVersion); + this._instructions = result.instructions; + await this.notification({ method: "notifications/initialized" }); + this._negotiatedProtocolVersion = result.protocolVersion; + if (this._listChangedConfig) this._setupListChangedHandlers(this._listChangedConfig); + } catch (error2) { + this.close(); + throw error2; + } + } + /** + * Negotiated connect (mode `'auto'` or `{ pin }`): probe with `server/discover` + * before the Protocol machinery attaches — on a disposable sibling process for + * the SDK's stdio transport, in place otherwise — then either establish the + * modern era or perform the plain legacy handshake. + */ + async _connectNegotiated(transport, negotiation, options) { + if (transport.sessionId !== void 0) { + await super.connect(transport); + const negotiatedProtocolVersion = this._negotiatedProtocolVersion; + if (negotiatedProtocolVersion !== void 0 && transport.setProtocolVersion) transport.setProtocolVersion(negotiatedProtocolVersion); + return; + } + this._resetConnectionState(); + let result; + try { + const transportKind = detectProbeTransportKind(transport); + const baseDeps = { + clientInfo: this._clientInfo, + capabilities: this._capabilities, + environment: detectProbeEnvironment(), + defaultTimeoutMs: options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC + }; + const stdioParams = transportKind === "stdio" ? readStdioServerParams(transport) : void 0; + result = stdioParams === void 0 ? await negotiateEra(negotiation, { + ...baseDeps, + transport, + transportKind + }) : await negotiateStdioViaSibling(negotiation, transport, stdioParams, baseDeps); + } catch (error2) { + await transport.close().catch(() => { + }); + disarmSpentCloseGuard(transport); + throw error2; + } + disarmSpentCloseGuard(transport); + await super.connect(transport); + if (result.era === "legacy") { + await this._legacyHandshake(transport, options); + return; + } + this._serverCapabilities = result.discover.capabilities; + this._serverVersion = serverInfoFromDiscover(result.discover); + this._cache.setServerIdentity(this._deriveServerIdentity(transport)); + this._instructions = result.discover.instructions; + this._discoverResult = result.discover; + this._negotiatedProtocolVersion = result.version; + if (transport.setProtocolVersion) transport.setProtocolVersion(result.version); + if (this._listChangedConfig) { + const config2 = this._listChangedConfig; + const advertised = this._serverCapabilities; + const effective = { + ...config2.tools && advertised?.tools?.listChanged && { tools: config2.tools }, + ...config2.prompts && advertised?.prompts?.listChanged && { prompts: config2.prompts }, + ...config2.resources && advertised?.resources?.listChanged && { resources: config2.resources } + }; + let handlersRegistered = true; + try { + this._setupListChangedHandlers(effective); + } catch (error2) { + handlersRegistered = false; + this.onerror?.(error2 instanceof Error ? error2 : new Error(String(error2))); + } + const filter = handlersRegistered ? { + ...effective.tools && { toolsListChanged: true }, + ...effective.prompts && { promptsListChanged: true }, + ...effective.resources && { resourcesListChanged: true } + } : {}; + if (Object.keys(filter).length > 0) { + const ackAbort = new AbortController(); + const onConnectAbort = () => ackAbort.abort(options?.signal?.reason); + if (options?.signal?.aborted) onConnectAbort(); + options?.signal?.addEventListener("abort", onConnectAbort); + try { + this._autoOpenedSubscription = await this.listen(filter, { + timeout: options?.timeout, + signal: ackAbort.signal + }); + } catch (error2) { + if (options?.signal?.aborted) { + await this.close().catch(() => { + }); + throw error2; + } + this.onerror?.(error2 instanceof Error ? error2 : new Error(String(error2))); + } finally { + options?.signal?.removeEventListener("abort", onConnectAbort); + } + } + } + } + /** + * Connect from a validated {@linkcode PriorDiscovery}: the modern arm + * adopts the `DiscoverResult` (zero round trips; `EraNegotiationFailed` + * on no 2026-07-28+ overlap), the legacy arm runs the plain legacy connect. + */ + async _connectFromPrior(transport, prior, options) { + if (prior.kind === "legacy") return this._connectPlainLegacy(transport, options); + const discover = prior.discover; + this._resetConnectionState(); + const explicit = this._supportedProtocolVersionsOption; + const version2 = (explicit && modernProtocolVersions(explicit).length > 0 ? modernProtocolVersions(explicit) : SUPPORTED_MODERN_PROTOCOL_VERSIONS).find((v) => discover.supportedVersions.includes(v)); + if (version2 === void 0) throw new SdkError(SdkErrorCode.EraNegotiationFailed, "connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback."); + await super.connect(transport); + this._discoverResult = discover; + this._serverCapabilities = discover.capabilities; + this._serverVersion = serverInfoFromDiscover(discover); + this._cache.setServerIdentity(this._deriveServerIdentity(transport)); + this._instructions = discover.instructions; + this._negotiatedProtocolVersion = version2; + transport.setProtocolVersion?.(version2); + if (this._listChangedConfig) try { + this._setupListChangedHandlers(this._listChangedConfig); + } catch (error2) { + this.onerror?.(error2 instanceof Error ? error2 : new Error(String(error2))); + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * The connected server's self-reported name and version, when it + * identified itself: required on the legacy `initialize` result; a spec + * SHOULD in the discover result's `_meta` on 2026-07-28, so a successful + * modern connect against an anonymous server leaves this `undefined`. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * The connected server's identity for response-cache partitioning. The + * `serverInfo` `name@version` pair when available (required on + * `initialize`; a SHOULD in the discover result's `_meta` since spec PR + * #3002); falls back to the transport's `sessionId`, then to a + * per-connection surrogate. The surrogate matters since #3002 made + * identity optional: without it, two identity-less servers reached over + * sessionId-less transports would share the cache's pre-connect `''` + * partition and read each other's entries — no stable identity means no + * cross-connection cache reuse. The value itself is server-controlled — + * the collision-safety of the storage partition comes from + * {@linkcode ClientResponseCache}'s JSON-array encoding around it, not + * from any character it does or does not contain. + */ + _deriveServerIdentity(transport) { + const v = this._serverVersion; + if (v !== void 0) return `${v.name}@${v.version}`; + return transport.sessionId ?? `anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * during the initialize handshake. When manually reconstructing a transport for reconnection, pass this + * value to the new transport so it continues sending the required `mcp-protocol-version` header. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * After initialization has completed, this returns the protocol era of the + * connection: `'modern'` when the connection negotiated a 2026-07-28+ + * revision (via `server/discover`), `'legacy'` for the 2025-era + * `initialize` handshake, or `undefined` before the connection is + * established. + */ + getProtocolEra() { + const version2 = this._negotiatedProtocolVersion; + if (version2 === void 0) return void 0; + return isModernProtocolVersion(version2) ? "modern" : "legacy"; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + /** + * The {@linkcode DiscoverResult} from the last `'auto'`/pinned probe, + * {@linkcode discover} call, or `connect({ prior })` that adopted a + * modern verdict (a legacy verdict leaves this `undefined` — there is no + * `DiscoverResult` on that path). Persistable via `JSON.stringify`; wrap + * as `{ kind: 'modern', discover }` and feed to {@linkcode ConnectOptions} + * `prior`. + */ + getDiscoverResult() { + return this._discoverResult; + } + assertCapabilityForMethod(method) { + switch (method) { + case "logging/setLevel": + if (!this._serverCapabilities?.logging) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._serverCapabilities?.prompts) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + case "resources/subscribe": + case "resources/unsubscribe": + if (!this._serverCapabilities?.resources) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resource subscriptions (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._serverCapabilities?.tools) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "completion/complete": + if (!this._serverCapabilities?.completions) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "initialize": + break; + case "server/discover": + break; + case "ping": + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/roots/list_changed": + if (!this._capabilities.roots?.listChanged) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support roots list changed notifications (required for ${method})`); + break; + case "notifications/initialized": + break; + case "notifications/cancelled": + break; + case "notifications/progress": + break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "sampling/createMessage": + if (!this._capabilities.sampling) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support sampling capability (required for ${method})`); + break; + case "elicitation/create": + if (!this._capabilities.elicitation) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation capability (required for ${method})`); + break; + case "roots/list": + if (!this._capabilities.roots) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support roots capability (required for ${method})`); + break; + case "ping": + break; + } + } + async ping(options) { + return this.request({ method: "ping" }, options); + } + /** + * Send `server/discover` (2026-07-28+) and record the result for + * {@linkcode getDiscoverResult}. + */ + async discover(options) { + const result = await this._requestWithSchema({ method: "server/discover" }, DiscoverResultSchema, options); + this._discoverResult = result; + return result; + } + /** Requests argument autocompletion suggestions from the server for a prompt or resource. */ + async complete(params, options) { + return this.request({ + method: "completion/complete", + params + }, options); + } + /** + * Sets the minimum severity level for log messages sent by the server. + * + * @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 setLoggingLevel(level, options) { + return this.request({ + method: "logging/setLevel", + params: { level } + }, options); + } + /** Retrieves a prompt by name from the server, passing the given arguments for template substitution. */ + async getPrompt(params, options) { + return this.request({ + method: "prompts/get", + params + }, options); + } + /** + * Lists available prompts. + * + * Called without a `cursor` (the common case), this walks every page and + * returns the complete aggregated list with no `nextCursor`; the + * aggregate is also written to the {@linkcode ResponseCacheStore}. Pass an + * explicit `{ cursor }` to fetch a single page and walk pagination + * yourself — the per-page path returns the server's raw page (with + * `nextCursor` for the next call) and does not write the response cache. + * The auto-aggregate path is capped by + * {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); the per-page path + * is not. + * + * Returns an empty list if the server does not advertise prompts capability + * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). + * + * @example + * ```ts source="./client.examples.ts#Client_listPrompts_pagination" + * // No cursor → all pages aggregated for you. + * const { prompts } = await client.listPrompts(); + * console.log( + * 'Available prompts:', + * prompts.map(p => p.name) + * ); + * ``` + */ + async listPrompts(params, options) { + if (!this._serverCapabilities?.prompts && !this._enforceStrictCapabilities) { + console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"); + return { prompts: [] }; + } + if (params?.cursor !== void 0) return this.request({ + method: "prompts/list", + params + }, options); + const hit = await this._serveFromCache("prompts/list", void 0, options); + if (hit !== void 0) return hit; + return this._listAllPages("prompts/list", params, options, (acc, page) => acc.prompts.push(...page.prompts)); + } + /** + * Lists available resources. + * + * Called without a `cursor` (the common case), this walks every page and + * returns the complete aggregated list with no `nextCursor`; the + * aggregate is also written to the {@linkcode ResponseCacheStore}. Pass an + * explicit `{ cursor }` to fetch a single page and walk pagination + * yourself — the per-page path returns the server's raw page (with + * `nextCursor` for the next call) and does not write the response cache. + * The auto-aggregate path is capped by + * {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); the per-page path + * is not. + * + * Returns an empty list if the server does not advertise resources capability + * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). + * + * @example + * ```ts source="./client.examples.ts#Client_listResources_pagination" + * // No cursor → all pages aggregated for you. + * const { resources } = await client.listResources(); + * console.log( + * 'Available resources:', + * resources.map(r => r.name) + * ); + * ``` + */ + async listResources(params, options) { + if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) { + console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"); + return { resources: [] }; + } + if (params?.cursor !== void 0) return this.request({ + method: "resources/list", + params + }, options); + const hit = await this._serveFromCache("resources/list", void 0, options); + if (hit !== void 0) return hit; + return this._listAllPages("resources/list", params, options, (acc, page) => acc.resources.push(...page.resources)); + } + /** + * Lists available resource URI templates for dynamic resources. + * + * Called without a `cursor`, this walks every page and returns the + * complete aggregated list with no `nextCursor`; the aggregate is + * also written to the {@linkcode ResponseCacheStore}. Pass an explicit + * `{ cursor }` to fetch a single page — see + * {@linkcode listResources | listResources()} for the per-page contract. + * + * Returns an empty list if the server does not advertise resources capability + * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). + */ + async listResourceTemplates(params, options) { + if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) { + console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"); + return { resourceTemplates: [] }; + } + if (params?.cursor !== void 0) return this.request({ + method: "resources/templates/list", + params + }, options); + const hit = await this._serveFromCache("resources/templates/list", void 0, options); + if (hit !== void 0) return hit; + return this._listAllPages("resources/templates/list", params, options, (acc, page) => acc.resourceTemplates.push(...page.resourceTemplates)); + } + /** + * Walk every page of a paginated list verb, aggregate, and write ONE + * entry to the response cache. Internal — backs the public `list*` + * methods' no-`cursor` auto-aggregate path. Page 1's result object is + * mutated in place (its items array is extended; `nextCursor` is + * cleared); page-1 metadata (`ttlMs`, `cacheScope`, `_meta`) is preserved. + * A `nextCursor` that repeats stops the walk (defence against a + * non-converging server, mcp.d's `drainList` guard); + * {@linkcode ClientOptions.listMaxPages} is a hard cap — hitting it + * throws, so a partial aggregate is never cached. The + * captured-generation guard skips the write when a `list_changed` landed + * mid-walk, so the eviction is never overwritten by a stale aggregate. + * `finalize` runs on the complete aggregate before the cache write — the + * SEP-2243 invalid-`x-mcp-header` exclusion hooks here so the cached + * `tools/list` entry is already filtered. + * + * The caller's `baseParams` (everything except `cursor`) is threaded into + * every page request — page 1 sends `{...baseParams}`, later pages + * `{...baseParams, cursor}` — so a typed, documented `_meta` (e.g. W3C + * trace context) supplied to the public `list*()` reaches every wire + * request the walk issues. + */ + async _listAllPages(method, baseParams, options, append, finalize2) { + const bypass = options?.cacheMode === "bypass"; + const generation = this._cache.captureGeneration(method); + const acc = await this.request({ + method, + ...baseParams && { params: { ...baseParams } } + }, options); + let cursor = acc.nextCursor; + const seen = /* @__PURE__ */ new Set(); + let pages = 1; + while (cursor !== void 0 && !seen.has(cursor)) { + if (this._listMaxPages !== 0 && pages >= this._listMaxPages) throw new SdkError(SdkErrorCode.ListPaginationExceeded, `${method}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`, { + method, + listMaxPages: this._listMaxPages + }); + seen.add(cursor); + const page = await this.request({ + method, + params: { + ...baseParams, + cursor + } + }, options); + append(acc, page); + cursor = page.nextCursor; + pages++; + } + delete acc.nextCursor; + finalize2?.(acc); + if (bypass) return acc; + await this._cache.write(method, acc, generation, this._freshness(acc)); + return acc; + } + /** + * Compute the {@linkcode ClientResponseCache.write} freshness payload from + * a cacheable result body. The single seam through which the client reads + * `ttlMs`/`cacheScope` (mcp.d's `cachedFetch` engine). The fields pass + * through the loose result schema, so they are read off the runtime body; + * a missing `ttlMs` falls back to + * {@linkcode ClientOptions | ClientOptions.defaultCacheTtlMs}; an explicit server-sent + * `ttlMs` (including `0` — the spec's "immediately stale") is honoured + * as-is. The default of `0` means `expiresAt === now()` ⇒ never served, + * only stored. A missing `cacheScope` is treated as `'private'` — the + * spec's `'public'` grant ("any client … MAY serve to any user") is too + * strong to infer by default, and matches this SDK's server-side stamp + * default. + */ + _freshness(result, params) { + const body = result; + const ttlMs = typeof body.ttlMs === "number" ? body.ttlMs : this._defaultCacheTtlMs; + const scope = body.cacheScope === "public" ? "public" : "private"; + return { + expiresAt: this._cache.now() + Math.min(Math.max(0, ttlMs), MAX_CACHE_TTL_MS), + scope, + params + }; + } + /** + * The cache-serving front of every cacheable verb (mcp.d's `cachedFetch` + * read half): under `cacheMode: 'use'` (the default), a fresh held entry + * is served and the round trip is skipped. `'refresh'` and `'bypass'` + * always fetch (the caller decides whether to write). Freshness and + * decoding live in {@linkcode ClientResponseCache.read}; every hit is + * freshly parsed, so the caller owns it outright. A custom store + * whose `get()` rejects is routed to `onerror` and treated as a miss — + * cache bookkeeping never blocks a request from reaching the wire. + */ + async _serveFromCache(method, params, options) { + if (options?.cacheMode === "bypass" || options?.cacheMode === "refresh") return void 0; + const hit = await this._cache.read(method, params).catch((error2) => void this._reportStoreError(error2)); + if (hit !== void 0) { + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)); + } + return hit.value; + } + } + /** Route a custom-store failure to `onerror` without aborting the surrounding dispatch. */ + _reportStoreError(e) { + this.onerror?.(e instanceof Error ? e : new Error(String(e))); + } + /** + * Compile a single tool's `outputSchema`. Passed as the compile callback to + * {@linkcode ClientResponseCache.outputValidator} so the cache class stays + * free of any validator-provider dependency, and called directly for the + * `options.toolDefinition` path of {@linkcode callTool} (a one-off + * caller-supplied definition is compiled in isolation and never enters the + * cache, so it cannot poison the listed tool of the same name). + * + * Returns `undefined` when the tool has no `outputSchema`, or a + * discriminated `{ok}` result otherwise. SEP-2106: ANY throw from the + * validator engine — unsupported `$schema` dialect, invalid `pattern` + * regex, unresolvable `$ref`, or any other engine error — is captured as + * `{ok: false, compileError}` so one bad schema does not poison the rest + * of the listing; `callTool()` surfaces it as an `InvalidParams` error + * before the request. The `{ok}` discriminator (not + * `compileError !== undefined`) means a custom provider that does + * `throw undefined` is still treated as a captured failure. + */ + _compileOutputValidator(tool) { + if (!tool.outputSchema) return void 0; + try { + return { + ok: true, + validator: this._jsonSchemaValidator.getValidator(tool.outputSchema) + }; + } catch (error2) { + return { + ok: false, + compileError: error2 + }; + } + } + /** + * Resolve the SEP-2243 `x-mcp-header` declaration scan for a tool name. + * + * The caller-supplied `toolDefinition` escape hatch wins; otherwise the + * cached `tools/list` entry (via the cache's `toolDefinition`) is the + * source. Freshness is the response cache's lifecycle: `list_changed` + * evicts, otherwise the held schema is the best information available + * regardless of age, and a stale schema is recovered through the + * `HEADER_MISMATCH` → evict-refetch-retry path in {@linkcode callTool}. + * On a miss the call proceeds without `Mcp-Param-*` headers (the spec's + * "client SHOULD send without custom headers" guidance) and relies on the + * same recovery. + */ + async _resolveXMcpHeaderScan(name, override) { + const tool = override ?? await this._cache.toolDefinition(name); + return tool === void 0 ? void 0 : scanXMcpHeaderDeclarations(tool.inputSchema); + } + /** + * Reads the contents of a resource by URI. + * + * Honours the result's `ttlMs`/`cacheScope` (SEP-2549): a still-fresh + * cached body for the same `uri` is returned without a round trip + * (`cacheMode: 'use'`, the default). The cache key is `{method, uri}` + * partitioned by the resolved scope — `'private'` (the default when the + * server omits the field) is stored under this client's + * {@linkcode ClientOptions | ClientOptions.cachePartition}, so a shared + * store cannot serve one principal's resource body to another. Unlike the + * list verbs, a result whose resolved TTL is ≤0 is **not** stored + * (`resources/read` has no derived index and the URI keyspace is + * unbounded). + */ + async readResource(params, options) { + const hit = await this._serveFromCache("resources/read", params.uri, options); + if (hit !== void 0) return hit; + const generation = this._cache.captureGeneration("resources/read", params.uri); + const result = await this.request({ + method: "resources/read", + params + }, options); + if (options?.cacheMode !== "bypass") { + const freshness = this._freshness(result, params.uri); + if (freshness.expiresAt > this._cache.now()) await this._cache.write("resources/read", result, generation, freshness); + else if (options?.cacheMode === "refresh") await this._cache.evictKey("resources/read", params.uri); + } + return result; + } + /** Subscribes to change notifications for a resource. The server must support resource subscriptions. */ + async subscribeResource(params, options) { + return this.request({ + method: "resources/subscribe", + params + }, options); + } + /** Unsubscribes from change notifications for a resource. */ + async unsubscribeResource(params, options) { + return this.request({ + method: "resources/unsubscribe", + params + }, options); + } + /** + * Opens a `subscriptions/listen` stream (protocol revision 2026-07-28). + * + * Resolves once the server's `notifications/subscriptions/acknowledged` + * arrives (the standard request timeout applies to this ack phase). Change + * notifications delivered on the stream are dispatched to the existing + * {@linkcode setNotificationHandler} registrations — the same handlers the + * 2025-era unsolicited notifications fire on a legacy connection — so + * `listen()` is era-transparent for consumers that already register those. + * + * `close()` tears the subscription down by aborting the listen request's + * `requestSignal` (closes the SSE stream where the transport honors it) + * AND sending `notifications/cancelled` referencing the listen request id + * — both, unconditionally, so any spec-compliant server on any transport + * sees the cancel. No automatic re-listen — call `listen()` again to + * re-establish. + * + * On a 2025-era connection this throws a typed + * {@linkcode SdkErrorCode.MethodNotSupportedByProtocolVersion} steering to + * `resources/subscribe` and `ClientOptions.listChanged` (the legacy + * unsolicited delivery model still applies there); no transparent shim. + */ + async listen(filter, options) { + if (this.transport === void 0) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); + const negotiated = this._negotiatedProtocolVersion; + if (negotiated === void 0 || !isModernProtocolVersion(negotiated)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${negotiated ?? "none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`, { + method: "subscriptions/listen", + protocolVersion: negotiated + }); + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = new AbortController(); + const listenId = `listen:${this._nextListenId++}`; + let state = "opening"; + let ackTimer; + let onCallerAbort; + let resolveOpening; + let rejectOpening; + const opening = new Promise((resolve, reject) => { + resolveOpening = resolve; + rejectOpening = reject; + }); + let resolveClosed; + const closed = new Promise((resolve) => { + resolveClosed = resolve; + }); + const settle = (outcome) => { + if (state === "closed") return; + const wasOpening = state === "opening"; + if (ackTimer !== void 0) { + clearTimeout(ackTimer); + ackTimer = void 0; + } + if ("ack" in outcome) { + state = "open"; + resolveOpening(outcome.ack); + return; + } + state = "closed"; + if (onCallerAbort !== void 0) options?.signal?.removeEventListener("abort", onCallerAbort); + this._listenState.delete(listenId); + requestAbort.abort(); + resolveClosed(outcome.cause); + if (wasOpening) rejectOpening(outcome.error ?? new SdkError(SdkErrorCode.ConnectionClosed, "subscriptions/listen closed before the server acknowledged")); + }; + const wireTeardown = async () => { + requestAbort.abort(); + await this.notification({ + method: "notifications/cancelled", + params: { requestId: listenId } + }).catch(() => { + }); + }; + const close = async () => { + if (state === "closed") return; + settle({ cause: "local" }); + await wireTeardown(); + }; + this._listenState.set(listenId, { settle }); + const ackTimeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + ackTimer = setTimeout(() => { + settle({ + cause: "remote", + error: new SdkError(SdkErrorCode.RequestTimeout, "subscriptions/listen ack timed out", { timeout: ackTimeout }) + }); + wireTeardown().catch(() => { + }); + }, ackTimeout); + if (options?.signal) { + const callerSignal = options.signal; + onCallerAbort = () => { + if (state === "closed") return; + const reason = callerSignal.reason; + settle({ + cause: "local", + error: reason instanceof Error ? reason : new Error(String(reason ?? "Aborted")) + }); + wireTeardown().catch(() => { + }); + }; + callerSignal.addEventListener("abort", onCallerAbort, { once: true }); + } + const jsonrpcRequest = { + jsonrpc: "2.0", + id: listenId, + method: "subscriptions/listen", + params: { + _meta: { ...this._outboundMetaEnvelope() }, + notifications: filter + } + }; + try { + await this.transport.send(jsonrpcRequest, { + requestSignal: requestAbort.signal, + onRequestStreamEnd: () => settle({ + cause: "remote", + error: /* @__PURE__ */ new Error("subscriptions/listen: stream ended") + }) + }); + } catch (error2) { + settle({ + cause: "remote", + error: error2 instanceof Error ? error2 : new Error(String(error2)) + }); + } + return { + honoredFilter: await opening, + close, + closed + }; + } + /** + * The subscription auto-opened by `ClientOptions.listChanged` on a modern + * connection — the listen filter is the intersection of the configured + * sub-options and the server-advertised `listChanged` capabilities. + * `undefined` on a legacy connection, before connect, or when that + * intersection is empty (auto-open skipped). Exposed so the consumer can + * `close()` it. + */ + get autoOpenedSubscription() { + return this._autoOpenedSubscription; + } + /** + * Transport-level demux for `subscriptions/listen` notifications, before + * any decoding/era-gating/handler dispatch. Consumes the leading + * `notifications/subscriptions/acknowledged` referencing a live + * subscription id (resolves the ack waiter) and an inbound + * `notifications/cancelled` referencing a live string-typed subscription + * id (server-side teardown on stdio). Change notifications carrying a + * subscription id pass through to the existing registered handlers via + * `super`. An unmatched ack/cancelled is NOT consumed: it reaches + * `setNotificationHandler` / `fallbackNotificationHandler` instead of + * being silently swallowed. + */ + _onnotification(raw, extra) { + const evicted = Object.hasOwn(LIST_CHANGED_EVICTIONS, raw.method) ? LIST_CHANGED_EVICTIONS[raw.method] : void 0; + if (raw.method === "notifications/resources/updated") { + const uri = raw.params?.uri; + if (typeof uri === "string") this._cache.evictKey("resources/read", uri); + } else if (evicted !== void 0) for (const method of evicted) this._cache.evict(method); + if (raw.method === "notifications/subscriptions/acknowledged") { + const subscriptionId = raw.params?._meta?.[SUBSCRIPTION_ID_META_KEY]; + const entry = typeof subscriptionId === "string" ? this._listenState.get(subscriptionId) : void 0; + if (entry !== void 0) { + const honored = this._wireCodec().validateNotification("notifications/subscriptions/acknowledged", raw); + entry.settle({ ack: honored.ok ? honored.value.params.notifications : {} }); + return; + } + } + if (raw.method === "notifications/cancelled") { + const cancelledId = raw.params?.requestId; + const entry = typeof cancelledId === "string" ? this._listenState.get(cancelledId) : void 0; + if (entry !== void 0) { + entry.settle({ + cause: "remote", + error: /* @__PURE__ */ new Error("subscriptions/listen: server cancelled the subscription") + }); + return; + } + } + super._onnotification(raw, extra); + } + /** + * Transport-level demux for `subscriptions/listen` responses. A JSON-RPC + * ERROR for the listen id is the server's pre-ack capacity/params + * rejection; a JSON-RPC RESULT for the listen id is the spec's + * `SubscriptionsListenResult` — the server's GRACEFUL-close signal (sent + * on shutdown). A string-id response that matches a live `_listenState` + * entry is consumed here (Protocol's `_responseHandlers` map is keyed by + * NUMBER and never holds a listen id, so passing a string-id response + * through would surface as "unknown message ID" via `onerror`). + */ + _onresponse(response) { + const id = response.id; + const entry = typeof id === "string" ? this._listenState.get(id) : void 0; + if (entry !== void 0) { + if (isJSONRPCErrorResponse(response)) entry.settle({ + cause: "remote", + error: ProtocolError.fromError(response.error.code, response.error.message, response.error.data) + }); + else entry.settle({ + cause: "graceful", + error: new SdkError(SdkErrorCode.ConnectionClosed, "subscriptions/listen: server closed the subscription gracefully before acknowledging") + }); + return; + } + super._onresponse(response); + } + /** + * Settle every live per-listen state machine on a transport-initiated + * close (the server dropping the connection on stdio/InMemory) before + * Protocol's `_onclose` tears the transport down. The base + * `_responseHandlers` settlement does not reach `_listenState` (listen + * ids are never registered there), so without this override a remote + * close would leave an in-flight `listen()` / open `McpSubscription` + * hanging. + */ + _onclose() { + if (this._listenState.size > 0) { + const reason = new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed"); + for (const entry of this._listenState.values()) entry.settle({ + cause: "remote", + error: reason + }); + this._listenState.clear(); + } + super._onclose(); + } + /** + * Calls a tool on the connected server and returns the result. Automatically validates structured output + * if the tool has an `outputSchema`. + * + * Tool results have two error surfaces: `result.isError` for tool-level failures (the tool ran but reported + * a problem), and thrown {@linkcode ProtocolError} for protocol-level failures or {@linkcode SdkError} for + * SDK-level issues (timeouts, missing capabilities). + * + * @example Basic usage + * ```ts source="./client.examples.ts#Client_callTool_basic" + * const result = await client.callTool({ + * name: 'calculate-bmi', + * arguments: { weightKg: 70, heightM: 1.75 } + * }); + * + * // Tool-level errors are returned in the result, not thrown + * if (result.isError) { + * console.error('Tool error:', result.content); + * return; + * } + * + * console.log(result.content); + * ``` + * + * @example Structured output + * ```ts source="./client.examples.ts#Client_callTool_structuredOutput" + * const result = await client.callTool({ + * name: 'calculate-bmi', + * arguments: { weightKg: 70, heightM: 1.75 } + * }); + * + * // Machine-readable output for the client application. SEP-2106: structuredContent is + * // `unknown` (any JSON value). Check for presence with `!== undefined` and narrow before use. + * if (result.structuredContent !== undefined) { + * const sc: unknown = result.structuredContent; // e.g. { bmi: 22.86 } + * if (typeof sc === 'object' && sc !== null && 'bmi' in sc) { + * console.log(sc.bmi); + * } + * } + * ``` + */ + async callTool(params, options) { + const mirroringActive = this.getProtocolEra() === "modern" && detectProbeEnvironment() !== "browser"; + const buildSendOptions = async () => { + if (!mirroringActive) return options; + let scan; + try { + scan = await this._resolveXMcpHeaderScan(params.name, options?.toolDefinition); + } catch (error2) { + this._reportStoreError(error2); + } + if (!scan?.valid || scan.declarations.length === 0) return options; + const paramHeaders = buildMcpParamHeaders(scan.declarations, params.arguments); + return Object.keys(paramHeaders).length === 0 ? options : { + ...options, + headers: { + ...options?.headers, + ...paramHeaders + } + }; + }; + let compiled = options?.toolDefinition === void 0 ? await this._cache.outputValidator(params.name, (tool) => this._compileOutputValidator(tool)).catch((error2) => void this._reportStoreError(error2)) : this._compileOutputValidator(options.toolDefinition); + const assertCompiled = () => { + if (compiled === void 0 || compiled.ok) return; + const err = compiled.compileError; + const message2 = (err instanceof Error ? err.message : String(err)).slice(0, 200); + throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool '${params.name}' has an invalid outputSchema: ${message2}`); + }; + assertCompiled(); + let result; + try { + result = await this.request({ + method: "tools/call", + params + }, await buildSendOptions()); + } catch (error2) { + const isHeaderMismatch = error2 instanceof ProtocolError && error2.code === HEADER_MISMATCH_ERROR_CODE; + if (!mirroringActive || !isHeaderMismatch || options?.toolDefinition !== void 0) throw error2; + const refreshOptions = { + signal: options?.signal, + timeout: options?.timeout, + cacheMode: "refresh" + }; + await this._cache.evict("tools/list"); + await this.listTools(void 0, refreshOptions).catch((error_) => this._reportStoreError(error_)); + compiled = await this._cache.outputValidator(params.name, (tool) => this._compileOutputValidator(tool)).catch((error_) => void this._reportStoreError(error_)); + assertCompiled(); + result = await this.request({ + method: "tools/call", + params + }, await buildSendOptions()); + } + const validator = compiled !== void 0 && compiled.ok ? compiled.validator : void 0; + if (validator) { + if (result.structuredContent === void 0 && !result.isError) throw new ProtocolError(ProtocolErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + if (result.structuredContent !== void 0 && !result.isError) try { + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } catch (error2) { + if (error2 instanceof ProtocolError) throw error2; + throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Failed to validate structured content: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + } + return result; + } + /** + * Lists available tools. + * + * Called without a `cursor` (the common case), this walks every page and + * returns the complete aggregated list with no `nextCursor`; the + * aggregate is also written to the {@linkcode ResponseCacheStore} (the + * source for {@linkcode callTool | callTool()}'s output-schema validation + * and SEP-2243 `Mcp-Param-*` header mirroring). Pass an explicit + * `{ cursor }` to fetch a single page and walk pagination yourself — the + * per-page path returns the server's raw page (with `nextCursor` for the + * next call) and does not write the response cache. The auto-aggregate + * path is capped by {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); + * the per-page path is not. + * + * Returns an empty list if the server does not advertise tools capability + * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). + * + * @example + * ```ts source="./client.examples.ts#Client_listTools_pagination" + * // No cursor → all pages aggregated for you. + * const { tools } = await client.listTools(); + * console.log( + * 'Available tools:', + * tools.map(t => t.name) + * ); + * ``` + */ + async listTools(params, options) { + if (!this._serverCapabilities?.tools && !this._enforceStrictCapabilities) { + console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"); + return { tools: [] }; + } + if (params?.cursor !== void 0) { + const page = await this.request({ + method: "tools/list", + params + }, options); + this._excludeInvalidXMcpHeaderTools(page); + return page; + } + const hit = await this._serveFromCache("tools/list", void 0, options); + if (hit !== void 0) return hit; + return this._listAllPages("tools/list", params, options, (acc, page) => acc.tools.push(...page.tools), (acc) => this._excludeInvalidXMcpHeaderTools(acc)); + } + /** + * SEP-2243 (protocol revision 2026-07-28): a Streamable HTTP client MUST + * exclude tool definitions whose `x-mcp-header` declarations violate the + * constraints, and SHOULD log a warning naming the tool and the reason. + * Applied to the CACHED aggregated `tools/list` result (so the entry + * mirroring reads never holds an unmirrorable tool) AND to every public + * per-page {@linkcode listTools | listTools()} return (the spec's MUST + * has no carve-out for paginated reads). The gate is era-only on + * non-stdio transports — `detectProbeTransportKind` cannot distinguish a + * real HTTP transport from in-memory/custom transports (it only + * positively recognizes stdio), and over-excluding on a non-HTTP modern + * connection is harmless: those transports never carry per-request + * headers, so an excluded tool would have been uncallable on a Streamable + * HTTP arm of the same server. Mutates `result.tools` in place. + */ + _excludeInvalidXMcpHeaderTools(result) { + if (this.getProtocolEra() !== "modern" || !this.transport || detectProbeTransportKind(this.transport) === "stdio") return; + const filtered = result.tools.filter((tool) => { + const scan = scanXMcpHeaderDeclarations(tool.inputSchema); + if (!scan.valid) { + console.warn(`[mcp-sdk] excluding tool '${tool.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${scan.reason}`); + return false; + } + return true; + }); + if (filtered.length !== result.tools.length) result.tools = filtered; + } + /** + * Set up a single list changed handler. + * @internal + */ + _setupListChangedHandler(listType, notificationMethod, options, fetcher) { + const parseResult = parseSchema(ListChangedOptionsBaseSchema, options); + if (!parseResult.success) throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); + if (typeof options.onChanged !== "function") throw new TypeError(`Invalid ${listType} listChanged options: onChanged must be a function`); + const { autoRefresh, debounceMs } = parseResult.data; + const { onChanged } = options; + const refresh = async () => { + if (!autoRefresh) { + onChanged(null, null); + return; + } + try { + onChanged(null, await fetcher()); + } catch (error2) { + onChanged(error2 instanceof Error ? error2 : new Error(String(error2)), null); + } + }; + const handler = () => { + if (debounceMs) { + const existingTimer = this._listChangedDebounceTimers.get(listType); + if (existingTimer) clearTimeout(existingTimer); + const timer = setTimeout(refresh, debounceMs); + this._listChangedDebounceTimers.set(listType, timer); + } else refresh(); + }; + this.setNotificationHandler(notificationMethod, handler); + } + /** + * Notifies the server that the client's root list has changed. Requires the `roots.listChanged` capability. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to passing paths via tool parameters, resource URIs, or configuration. + */ + async sendRootsListChanged() { + return this.notification({ method: "notifications/roots/list_changed" }); + } + }; + withOAuth = (provider, baseUrl) => (next) => { + return async (input, init) => { + const makeRequest = async () => { + const headers = new Headers(init?.headers); + const tokens = await provider.tokens(); + if (tokens) headers.set("Authorization", `Bearer ${tokens.access_token}`); + return await next(input, { + ...init, + headers + }); + }; + let response = await makeRequest(); + if (response.status === 401) try { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + const result = await auth(provider, { + serverUrl: baseUrl || (typeof input === "string" ? new URL(input).origin : input.origin), + resourceMetadataUrl, + scope, + fetchFn: next + }); + if (result === "REDIRECT") throw new UnauthorizedError("Authentication requires user authorization - redirect initiated"); + if (result !== "AUTHORIZED") throw new UnauthorizedError(`Authentication failed with result: ${result}`); + response = await makeRequest(); + } catch (error2) { + if (error2 instanceof UnauthorizedError) throw error2; + throw new UnauthorizedError(`Failed to re-authenticate: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + if (response.status === 401) throw new UnauthorizedError(`Authentication failed for ${typeof input === "string" ? input : input.toString()}`); + return response; + }; + }; + withLogging = (options = {}) => { + const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; + const defaultLogger = (input) => { + const { method, url: url2, status, statusText, duration: duration3, requestHeaders, responseHeaders, error: error2 } = input; + let message2 = error2 ? `HTTP ${method} ${url2} failed: ${error2.message} (${duration3}ms)` : `HTTP ${method} ${url2} ${status} ${statusText} (${duration3}ms)`; + if (includeRequestHeaders && requestHeaders) { + const reqHeaders = [...requestHeaders.entries()].map(([key, value]) => `${key}: ${value}`).join(", "); + message2 += ` + Request Headers: {${reqHeaders}}`; + } + if (includeResponseHeaders && responseHeaders) { + const resHeaders = [...responseHeaders.entries()].map(([key, value]) => `${key}: ${value}`).join(", "); + message2 += ` + Response Headers: {${resHeaders}}`; + } + if (error2 || status >= 400) console.error(message2); + else console.log(message2); + }; + const logFn = logger || defaultLogger; + return (next) => async (input, init) => { + const startTime = performance.now(); + const method = init?.method || "GET"; + const url2 = typeof input === "string" ? input : input.toString(); + const requestHeaders = includeRequestHeaders ? new Headers(init?.headers) : void 0; + try { + const response = await next(input, init); + const duration3 = performance.now() - startTime; + if (response.status >= statusLevel) logFn({ + method, + url: url2, + status: response.status, + statusText: response.statusText, + duration: duration3, + requestHeaders, + responseHeaders: includeResponseHeaders ? response.headers : void 0 + }); + return response; + } catch (error2) { + logFn({ + method, + url: url2, + status: 0, + statusText: "Network Error", + duration: performance.now() - startTime, + requestHeaders, + error: error2 + }); + throw error2; + } + }; + }; + applyMiddlewares = (...middleware) => { + return (next) => { + let handler = next; + for (const mw of middleware) handler = mw(handler); + return handler; + }; + }; + createMiddleware = (handler) => { + return (next) => (input, init) => handler(next, input, init); + }; + SseError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SseError" }); + } + 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, message2, event) { + super(`SSE error: ${message2}`); + this.code = code; + this.event = event; + stampErrorBrands(this, new.target); + } + }; + SSEClientTransport = class { + _eventSource; + _endpoint; + _abortController; + _url; + _resourceMetadataUrl; + _scope; + _eventSourceInit; + _requestInit; + _authProvider; + _oauthProvider; + _skipIssuerMetadataValidation; + _fetch; + _fetchWithInit; + _protocolVersion; + onclose; + onerror; + onmessage; + constructor(url2, opts) { + this._url = url2; + this._resourceMetadataUrl = void 0; + this._scope = void 0; + this._eventSourceInit = opts?.eventSourceInit; + this._requestInit = opts?.requestInit; + this._skipIssuerMetadataValidation = opts?.skipIssuerMetadataValidation; + if (isOAuthClientProvider(opts?.authProvider)) { + this._oauthProvider = opts.authProvider; + this._authProvider = adaptOAuthProvider(opts.authProvider, { skipIssuerMetadataValidation: opts.skipIssuerMetadataValidation }); + } else this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + } + _last401Response; + async _commonHeaders() { + const headers = {}; + const token = await this._authProvider?.token(); + if (token) headers["Authorization"] = `Bearer ${token}`; + if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion; + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + _startOrAuth() { + const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch; + return new Promise((resolve, reject) => { + this._eventSource = new EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url2, init) => { + const headers = await this._commonHeaders(); + headers.set("Accept", "text/event-stream"); + const response = await fetchImpl(url2, { + ...init, + headers + }); + if (response.status === 401) { + this._last401Response = response; + if (response.headers.has("www-authenticate")) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + } + return response; + } + }); + this._abortController = new AbortController(); + this._eventSource.onerror = (event) => { + if (event.code === 401 && this._authProvider) { + if (this._authProvider.onUnauthorized && this._last401Response) { + const response = this._last401Response; + this._last401Response = void 0; + this._eventSource?.close(); + this._authProvider.onUnauthorized({ + response, + serverUrl: this._url, + fetchFn: this._fetchWithInit + }).then(() => this._startOrAuth().then(resolve, reject), (error$2) => { + this.onerror?.(error$2); + reject(error$2); + }); + return; + } + const error$1 = new UnauthorizedError(); + reject(error$1); + this.onerror?.(error$1); + return; + } + const error2 = new SseError(event.code, event.message, event); + reject(error2); + this.onerror?.(error2); + }; + this._eventSource.onopen = () => { + }; + this._eventSource.addEventListener("endpoint", (event) => { + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } catch (error2) { + reject(error2); + this.onerror?.(error2); + this.close(); + return; + } + resolve(); + }); + this._eventSource.onmessage = (event) => { + const messageEvent = event; + let message2; + try { + message2 = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } catch (error2) { + this.onerror?.(error2); + return; + } + this.onmessage?.(message2); + }; + }); + } + async start() { + if (this._eventSource) throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically."); + return await this._startOrAuth(); + } + async finishAuth(codeOrParams, iss) { + if (!this._oauthProvider) throw new UnauthorizedError("finishAuth requires an OAuthClientProvider"); + const { authorizationCode, iss: issParam } = await resolveAuthorizationCallbackParams(codeOrParams, iss, this._oauthProvider, this._url, { + fetchFn: this._fetchWithInit, + resourceMetadataUrl: this._resourceMetadataUrl + }); + if (await auth(this._oauthProvider, { + serverUrl: this._url, + authorizationCode, + iss: issParam, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit, + skipIssuerMetadataValidation: this._skipIssuerMetadataValidation + }) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize"); + } + async close() { + this._abortController?.abort(); + this._eventSource?.close(); + this.onclose?.(); + } + async send(message2) { + return this._send(message2, false); + } + async _send(message2, isAuthRetry) { + if (!this._endpoint) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); + try { + const headers = await this._commonHeaders(); + headers.set("content-type", "application/json"); + const init = { + ...this._requestInit, + method: "POST", + headers, + body: JSON.stringify(message2), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._endpoint, init); + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + if (response.headers.has("www-authenticate")) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + if (this._authProvider.onUnauthorized && !isAuthRetry) { + await this._authProvider.onUnauthorized({ + response, + serverUrl: this._url, + fetchFn: this._fetchWithInit + }); + await response.text?.().catch(() => { + }); + return this._send(message2, true); + } + await response.text?.().catch(() => { + }); + if (isAuthRetry) throw new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, "Server returned 401 after re-authentication", { + status: 401, + statusText: response.statusText + }); + throw new UnauthorizedError(); + } + const text = await response.text?.().catch(() => null); + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + await response.text?.().catch(() => { + }); + } catch (error2) { + this.onerror?.(error2); + throw error2; + } + } + setProtocolVersion(version2) { + this._protocolVersion = version2; + } + }; + DEFAULT_MAX_STEP_UP_RETRIES = 1; + DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1e3, + maxReconnectionDelay: 3e4, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 + }; + RESERVED_REQUEST_HEADER_NAMES = /* @__PURE__ */ new Set([ + "authorization", + "content-type", + "mcp-protocol-version", + "mcp-method", + "mcp-name", + "mcp-session-id" + ]); + StreamableHTTPClientTransport = class { + _abortController; + _url; + _resourceMetadataUrl; + _scope; + _requestInit; + _authProvider; + _oauthProvider; + _skipIssuerMetadataValidation; + _fetch; + _fetchWithInit; + _sessionId; + _reconnectionOptions; + _protocolVersion; + _onInsufficientScope; + _maxStepUpRetries; + _serverRetryMs; + _reconnectionScheduler; + _cancelReconnection; + onclose; + onerror; + onmessage; + /** + * Streamable HTTP opens one POST (and SSE response stream) per outbound + * request and honors `TransportSendOptions.requestSignal`. On a 2026-era + * connection the protocol layer aborts that per-request stream as the + * spec cancellation signal instead of POSTing `notifications/cancelled`. + */ + hasPerRequestStream = true; + constructor(url2, opts) { + this._url = url2; + this._resourceMetadataUrl = void 0; + this._scope = void 0; + this._requestInit = opts?.requestInit; + this._skipIssuerMetadataValidation = opts?.skipIssuerMetadataValidation; + if (isOAuthClientProvider(opts?.authProvider)) { + this._oauthProvider = opts.authProvider; + this._authProvider = adaptOAuthProvider(opts.authProvider, { skipIssuerMetadataValidation: opts.skipIssuerMetadataValidation }); + } else this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + this._sessionId = opts?.sessionId; + this._protocolVersion = opts?.protocolVersion; + this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + this._reconnectionScheduler = opts?.reconnectionScheduler; + this._onInsufficientScope = opts?.onInsufficientScope ?? "reauthorize"; + this._maxStepUpRetries = Math.max(0, opts?.maxStepUpRetries ?? DEFAULT_MAX_STEP_UP_RETRIES); + } + /** + * SEP-2350 step-up: compute the union scope, decide whether refresh must be + * bypassed, and run {@linkcode auth}. Returns the auth result so the caller + * can decide whether to retry. Shared by the POST `_send` path and the GET + * `_startOrAuthSse` path so both apply the same `'throw'` short-circuit, + * the same superset-gated refresh bypass, and the same retry cap. + */ + async _stepUpAuthorize(challenge, stepUpRetries) { + if (this._onInsufficientScope === "throw") throw new InsufficientScopeError({ + requiredScope: challenge.scope, + resourceMetadataUrl: challenge.resourceMetadataUrl, + errorDescription: challenge.errorDescription + }); + if (!this._oauthProvider) throw new InsufficientScopeError({ + requiredScope: challenge.scope, + resourceMetadataUrl: challenge.resourceMetadataUrl, + errorDescription: challenge.errorDescription + }); + if (stepUpRetries >= this._maxStepUpRetries) throw new SdkHttpError(SdkErrorCode.ClientHttpForbidden, `Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`, { + status: 403, + statusText: challenge.statusText ?? "Forbidden", + text: challenge.text + }); + if (challenge.resourceMetadataUrl) this._resourceMetadataUrl = challenge.resourceMetadataUrl; + const tokens = await this._oauthProvider.tokens(); + const unionScope = computeScopeUnion(this._scope, tokens?.scope, challenge.scope); + this._scope = unionScope; + const forceReauthorization = isStrictScopeSuperset(unionScope, tokens?.scope); + return auth(this._oauthProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: unionScope, + forceReauthorization, + fetchFn: this._fetchWithInit, + skipIssuerMetadataValidation: this._skipIssuerMetadataValidation + }); + } + async _commonHeaders() { + const headers = {}; + const token = await this._authProvider?.token(); + if (token) headers["Authorization"] = `Bearer ${token}`; + if (this._sessionId) headers["mcp-session-id"] = this._sessionId; + if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion; + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + /** + * Body-derived per-request headers: when an outgoing request carries a + * protocol-version claim in its `_meta` envelope (the version negotiation + * probe is the first such sender), `MCP-Protocol-Version` and `Mcp-Method` + * derive from the message itself. The connection-level version slot is + * neither consulted nor mutated; messages without an envelope claim are + * untouched, so no 2026 header can appear on a legacy exchange. + */ + _applyBodyDerivedHeaders(headers, message2) { + if (Array.isArray(message2) || !isJSONRPCRequest(message2)) return; + const envelopeVersion = message2.params?._meta?.[PROTOCOL_VERSION_META_KEY]; + if (typeof envelopeVersion !== "string") return; + headers.set("mcp-protocol-version", envelopeVersion); + headers.set("mcp-method", message2.method); + const params = message2.params; + const nameHeader = message2.method === "resources/read" ? typeof params?.uri === "string" ? params.uri : void 0 : typeof params?.name === "string" ? params.name : void 0; + if (nameHeader !== void 0) headers.set("mcp-name", encodeMcpParamValue(nameHeader)); + } + /** + * `true` when the outbound message is a single request carrying a + * modern-era protocol-version envelope claim — the same predicate that + * gates body-derived `mcp-method`/`mcp-name` emission. Used to confine the + * 400-body-as-ProtocolError delivery to modern-era exchanges only. + */ + _isModernEnvelopedRequest(message2) { + if (Array.isArray(message2) || !isJSONRPCRequest(message2)) return false; + const v = message2.params?._meta?.[PROTOCOL_VERSION_META_KEY]; + return typeof v === "string" && isModernProtocolVersion(v); + } + async _startOrAuthSse(options, isAuthRetry = false, stepUpRetries = 0) { + const { resumptionToken, requestSignal } = options; + const isIntentionalAbort = () => this._abortController?.signal.aborted === true || requestSignal?.aborted === true; + try { + const headers = await this._commonHeaders(); + const types = [...headers.get("accept")?.split(",").map((s3) => s3.trim().toLowerCase()) ?? [], "text/event-stream"]; + headers.set("accept", [...new Set(types)].join(", ")); + if (resumptionToken) headers.set("last-event-id", resumptionToken); + const transportSignal = this._abortController?.signal; + const signal = requestSignal !== void 0 && transportSignal !== void 0 ? anySignal(transportSignal, requestSignal) : requestSignal ?? transportSignal; + const response = await (this._fetch ?? fetch)(this._url, { + ...this._requestInit, + method: "GET", + headers, + signal + }); + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + if (response.headers.has("www-authenticate")) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = computeScopeUnion(this._scope, scope); + } + if (this._authProvider.onUnauthorized && !isAuthRetry) { + await this._authProvider.onUnauthorized({ + response, + serverUrl: this._url, + fetchFn: this._fetchWithInit + }); + await response.text?.().catch(() => { + }); + return this._startOrAuthSse(options, true, stepUpRetries); + } + await response.text?.().catch(() => { + }); + if (isAuthRetry) throw new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, "Server returned 401 after re-authentication", { + status: 401, + statusText: response.statusText + }); + throw new UnauthorizedError(); + } + if (response.status === 403) { + const { resourceMetadataUrl, scope, error: error2, errorDescription } = extractWWWAuthenticateParams(response); + if (error2 === "insufficient_scope") { + const text = await response.text?.().catch(() => null); + if (await this._stepUpAuthorize({ + scope, + resourceMetadataUrl, + errorDescription, + statusText: response.statusText, + text + }, stepUpRetries) !== "AUTHORIZED") throw new UnauthorizedError(); + return this._startOrAuthSse(options, isAuthRetry, stepUpRetries + 1); + } + } + await response.text?.().catch(() => { + }); + if (response.status === 405) { + options.onRequestStreamEnd?.(); + return; + } + throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToOpenStream, `Failed to open SSE stream: ${response.statusText}`, { + status: response.status, + statusText: response.statusText + }); + } + this._handleSseStream(response.body, options, true); + } catch (error2) { + if (!isIntentionalAbort()) this.onerror?.(error2); + throw error2; + } + } + /** + * Calculates the next reconnection delay using a backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + if (this._serverRetryMs !== void 0) return this._serverRetryMs; + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + const maxRetries = this._reconnectionOptions.maxRetries; + if (attemptCount >= maxRetries) { + this.onerror?.(/* @__PURE__ */ new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + options.onRequestStreamEnd?.(); + return; + } + const delay = this._getNextReconnectionDelay(attemptCount); + const reconnect = () => { + this._cancelReconnection = void 0; + if (this._abortController?.signal.aborted || options.requestSignal?.aborted) return; + this._startOrAuthSse(options).catch((error2) => { + if (this._abortController?.signal.aborted || options.requestSignal?.aborted) return; + this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect SSE stream: ${error2 instanceof Error ? error2.message : String(error2)}`)); + try { + this._scheduleReconnection(options, attemptCount + 1); + } catch (scheduleError) { + this.onerror?.(scheduleError instanceof Error ? scheduleError : new Error(String(scheduleError))); + } + }); + }; + if (this._reconnectionScheduler) { + const cancel = this._reconnectionScheduler(reconnect, delay, attemptCount); + this._cancelReconnection = typeof cancel === "function" ? cancel : void 0; + } else { + const handle = setTimeout(reconnect, delay); + this._cancelReconnection = () => clearTimeout(handle); + } + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) { + options.onRequestStreamEnd?.(); + return; + } + const { onresumptiontoken, replayMessageId, requestSignal, onRequestStreamEnd } = options; + const isIntentionalAbort = () => this._abortController?.signal.aborted === true || requestSignal?.aborted === true; + let lastEventId; + let hasPrimingEvent = false; + let receivedResponse = false; + const processStream = async () => { + try { + const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ onRetry: (retryMs) => { + this._serverRetryMs = retryMs; + } })).getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) break; + if (event.id) { + lastEventId = event.id; + hasPrimingEvent = true; + onresumptiontoken?.(event.id); + } + if (!event.data) continue; + if (!event.event || event.event === "message") try { + const message2 = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if (isJSONRPCResultResponse(message2) || isJSONRPCErrorResponse(message2)) { + receivedResponse = true; + if (replayMessageId !== void 0) message2.id = replayMessageId; + } + this.onmessage?.(message2); + } catch (error2) { + this.onerror?.(error2); + } + } + if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !isIntentionalAbort()) this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId, + requestSignal, + onRequestStreamEnd + }, 0); + else if (!isIntentionalAbort()) onRequestStreamEnd?.(); + } catch (error2) { + if (isIntentionalAbort()) return; + this.onerror?.(/* @__PURE__ */ new Error(`SSE stream disconnected: ${error2}`)); + if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !isIntentionalAbort()) try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId, + requestSignal, + onRequestStreamEnd + }, 0); + } catch (error$1) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect: ${error$1 instanceof Error ? error$1.message : String(error$1)}`)); + onRequestStreamEnd?.(); + } + else onRequestStreamEnd?.(); + } + }; + processStream(); + } + async start() { + if (this._abortController) throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically."); + this._abortController = new AbortController(); + } + async finishAuth(codeOrParams, iss) { + if (!this._oauthProvider) throw new UnauthorizedError("finishAuth requires an OAuthClientProvider"); + const { authorizationCode, iss: issParam } = await resolveAuthorizationCallbackParams(codeOrParams, iss, this._oauthProvider, this._url, { + fetchFn: this._fetchWithInit, + resourceMetadataUrl: this._resourceMetadataUrl + }); + if (await auth(this._oauthProvider, { + serverUrl: this._url, + authorizationCode, + iss: issParam, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit, + skipIssuerMetadataValidation: this._skipIssuerMetadataValidation + }) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize"); + } + async close() { + try { + this._cancelReconnection?.(); + } finally { + this._cancelReconnection = void 0; + this._abortController?.abort(); + this.onclose?.(); + } + } + async send(message2, options) { + return this._send(message2, options, false); + } + async _send(message2, options, isAuthRetry, stepUpRetries = 0) { + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + this._startOrAuthSse({ + resumptionToken, + replayMessageId: isJSONRPCRequest(message2) ? message2.id : void 0, + requestSignal: options?.requestSignal + }).catch((error2) => this.onerror?.(error2)); + return; + } + const headers = await this._commonHeaders(); + this._applyBodyDerivedHeaders(headers, message2); + const isHandshake = Array.isArray(message2) ? message2.some((m) => isInitializeRequest(m)) : isInitializeRequest(message2); + if (isHandshake) headers.delete("mcp-session-id"); + if (options?.headers !== void 0) for (const [name, value] of Object.entries(options.headers)) { + if (RESERVED_REQUEST_HEADER_NAMES.has(name.toLowerCase())) continue; + headers.set(name, value); + } + headers.set("content-type", "application/json"); + const types = [ + ...headers.get("accept")?.split(",").map((s3) => s3.trim().toLowerCase()) ?? [], + "application/json", + "text/event-stream" + ]; + headers.set("accept", [...new Set(types)].join(", ")); + const transportSignal = this._abortController?.signal; + const signal = options?.requestSignal !== void 0 && transportSignal !== void 0 ? anySignal(transportSignal, options.requestSignal) : options?.requestSignal ?? transportSignal; + const init = { + ...this._requestInit, + method: "POST", + headers, + body: JSON.stringify(message2), + signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + if (isHandshake && response.ok) this._sessionId = response.headers.get("mcp-session-id") || void 0; + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + if (response.headers.has("www-authenticate")) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = computeScopeUnion(this._scope, scope); + } + if (this._authProvider.onUnauthorized && !isAuthRetry) { + await this._authProvider.onUnauthorized({ + response, + serverUrl: this._url, + fetchFn: this._fetchWithInit + }); + await response.text?.().catch(() => { + }); + return this._send(message2, options, true, stepUpRetries); + } + await response.text?.().catch(() => { + }); + if (isAuthRetry) throw new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, "Server returned 401 after re-authentication", { + status: 401, + statusText: response.statusText + }); + throw new UnauthorizedError(); + } + const text = await response.text?.().catch(() => null); + if (response.status === 403) { + const { resourceMetadataUrl, scope, error: error2, errorDescription } = extractWWWAuthenticateParams(response); + if (error2 === "insufficient_scope") { + if (await this._stepUpAuthorize({ + scope, + resourceMetadataUrl, + errorDescription, + statusText: response.statusText, + text + }, stepUpRetries) !== "AUTHORIZED") throw new UnauthorizedError(); + return this._send(message2, options, isAuthRetry, stepUpRetries + 1); + } + } + if (response.status === 400 && typeof text === "string" && this._isModernEnvelopedRequest(message2)) try { + const parsed = JSONRPCMessageSchema.parse(JSON.parse(text)); + const requests = (Array.isArray(message2) ? message2 : [message2]).filter((m) => isJSONRPCRequest(m)); + if (isJSONRPCErrorResponse(parsed) && requests.some((r) => r.id === parsed.id)) { + this.onmessage?.(parsed); + return; + } + } catch { + } + throw new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, `Error POSTing to endpoint: ${text}`, { + status: response.status, + statusText: response.statusText, + text + }); + } + if (response.status === 202) { + await response.text?.().catch(() => { + }); + if (isInitializedNotification(message2)) this._startOrAuthSse({ resumptionToken: void 0 }).catch((error2) => this.onerror?.(error2)); + return; + } + const hasRequests = (Array.isArray(message2) ? message2 : [message2]).some((msg) => "method" in msg && "id" in msg && msg.id !== void 0); + const contentType = response.headers.get("content-type"); + const responseMediaType = mediaTypeEssence(contentType); + if (hasRequests) if (responseMediaType === "text/event-stream") this._handleSseStream(response.body, { + onresumptiontoken, + requestSignal: options?.requestSignal, + onRequestStreamEnd: options?.onRequestStreamEnd + }, false); + else if (responseMediaType === "application/json") { + const data = await response.json(); + const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) this.onmessage?.(msg); + } else { + await response.text?.().catch(() => { + }); + throw new SdkError(SdkErrorCode.ClientHttpUnexpectedContent, `Unexpected content type: ${contentType}`, { contentType }); + } + else await response.text?.().catch(() => { + }); + } catch (error2) { + if (options?.requestSignal?.aborted !== true) this.onerror?.(error2); + throw error2; + } + } + get sessionId() { + return this._sessionId; + } + /** + * Terminates the current session by sending a `DELETE` request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP `DELETE` to the MCP endpoint with the `Mcp-Session-Id` header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP `405 Method Not Allowed`, indicating that + * the server does not allow clients to terminate sessions. + */ + async terminateSession() { + if (!this._sessionId) return; + try { + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: "DELETE", + headers, + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + await response.text?.().catch(() => { + }); + if (!response.ok && response.status !== 405) throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToTerminateSession, `Failed to terminate session: ${response.statusText}`, { + status: response.status, + statusText: response.statusText + }); + this._sessionId = void 0; + } catch (error2) { + this.onerror?.(error2); + throw error2; + } + } + setProtocolVersion(version2) { + this._protocolVersion = version2; + } + get protocolVersion() { + return this._protocolVersion; + } + /** + * Resume an SSE stream from a previous event ID. + * Opens a `GET` SSE connection with `Last-Event-ID` header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + async resumeStream(lastEventId, options) { + await this._startOrAuthSse({ + resumptionToken: lastEventId, + onresumptiontoken: options?.onresumptiontoken + }); + } + }; + } +}); // ../freya/packages/core/dist/domain/model/Agent.js -function createAgent(config, deploymentId) { +function createAgent(config2, deploymentId) { return { - id: config.id, - config, + id: config2.id, + config: config2, deploymentId, createdAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() @@ -27,11 +29377,11 @@ function createSession(id, agentId, userId, transportId) { metadata: {} }; } -function addMessage(session, message) { +function addMessage(session, message2) { return { ...session, - messages: [...session.messages, message], - turnCount: message.role === "assistant" ? session.turnCount + 1 : session.turnCount, + messages: [...session.messages, message2], + turnCount: message2.role === "assistant" ? session.turnCount + 1 : session.turnCount, updatedAt: /* @__PURE__ */ new Date() }; } @@ -66,9 +29416,9 @@ function createEvent(id, type, agentId, payload, sessionId) { // ../freya/packages/core/dist/domain/services/ContextBuilderService.js function buildContext(params) { - const { config, ontology, memories, messages, tools, ontologyRenderer, transport } = params; + const { config: config2, ontology, memories, messages, tools, ontologyRenderer, transport } = params; const parts = []; - parts.push(config.systemPrompt); + parts.push(config2.systemPrompt); if (transport) { parts.push(` @@ -227,8 +29577,8 @@ var HookExecutionError = class extends Error { phase; cause; constructor(hookName, phase, cause) { - const message = cause instanceof Error ? cause.message : String(cause); - super(`Hook "${hookName}" failed in phase "${phase}": ${message}`); + const message2 = cause instanceof Error ? cause.message : String(cause); + super(`Hook "${hookName}" failed in phase "${phase}": ${message2}`); this.hookName = hookName; this.phase = phase; this.cause = cause; @@ -813,11 +30163,11 @@ async function executeTurn(agent, sessionId, userMessage, deps, budget) { } catch (err) { if (!(err instanceof HookExecutionError)) throw err; - const message = err.message; + const message2 = err.message; annotationsBuf.push({ phase, key: "blocking.hook_exception", - value: message + value: message2 }); events.push({ id: crypto.randomUUID(), @@ -828,7 +30178,7 @@ async function executeTurn(agent, sessionId, userMessage, deps, budget) { payload: { key: "blocking.hook_exception", phase, - error: message + error: message2 } }); return { @@ -1233,15 +30583,15 @@ async function* executeStreamingTurn(agent, sessionId, userMessage, deps, budget } catch (err) { if (!(err instanceof HookExecutionError)) throw err; - const message = err.message; + const message2 = err.message; annotations.push({ phase, key: "streaming.hook_exception", - value: message + value: message2 }); events.push(annotationEvent(agent.id, sessionId, "streaming.hook_exception", { phase, - error: message + error: message2 })); return { payload, @@ -1698,25 +31048,25 @@ function createAgentRuntime(adapters, agents = /* @__PURE__ */ new Map()) { const ontologyRenderer = { render: renderOntologySimple }; - const registry = { + const registry2 = { async getAgent(agentId) { return agentMap.get(agentId) ?? null; }, async listAgents() { return Array.from(agentMap.values()); }, - async registerAgent(config, deploymentId) { - const agent = createAgent(config, deploymentId); + async registerAgent(config2, deploymentId) { + const agent = createAgent(config2, deploymentId); agentMap.set(agent.id, agent); return agent; } }; return { - async handleMessage({ agentId, sessionId, message, budget }) { + async handleMessage({ agentId, sessionId, message: message2, budget }) { const agent = agentMap.get(agentId); if (!agent) throw new Error(`Agent not found: ${agentId}`); - const result = await executeTurn(agent, sessionId, message, { + const result = await executeTurn(agent, sessionId, message2, { llm: adapters.llm, tools: adapters.toolExecutor, memory: adapters.memory, @@ -1734,11 +31084,11 @@ function createAgentRuntime(adapters, agents = /* @__PURE__ */ new Map()) { usage: result.usage }; }, - handleMessageStream({ agentId, sessionId, message, budget, hooks, signal }) { + handleMessageStream({ agentId, sessionId, message: message2, budget, hooks, signal }) { const agent = agentMap.get(agentId); if (!agent) throw new Error(`Agent not found: ${agentId}`); - return executeStreamingTurn(agent, sessionId, message, { + return executeStreamingTurn(agent, sessionId, message2, { llm: adapters.llm, tools: adapters.toolExecutor, memory: adapters.memory, @@ -1757,7 +31107,7 @@ function createAgentRuntime(adapters, agents = /* @__PURE__ */ new Map()) { async getAgent(agentId) { return agentMap.get(agentId) ?? null; }, - registry + registry: registry2 }; } function renderOntologySimple(ontology) { @@ -1836,8 +31186,8 @@ function toAnthropicTools(tools) { } var AnthropicLLM = class { config; - constructor(config) { - this.config = config; + constructor(config2) { + this.config = config2; } async complete(params) { const body = { @@ -1926,7 +31276,7 @@ var AnthropicLLM = class { const reader = response.body?.getReader(); if (!reader) throw new Error("No response body for streaming"); - const decoder = new TextDecoder(); + const decoder2 = new TextDecoder(); let buffer = ""; let inputTokens = 0; let outputTokens = 0; @@ -1956,7 +31306,7 @@ var AnthropicLLM = class { const { done, value } = await reader.read(); if (done) break; - buffer += decoder.decode(value, { stream: true }); + buffer += decoder2.decode(value, { stream: true }); const lines = buffer.split("\n"); buffer = lines.pop() || ""; for (const line of lines) { @@ -2087,7 +31437,7 @@ var FakeEmbedding = class { for (let i = 0; i < text.length; i++) { vec[i % vec.length] += text.charCodeAt(i) / 1e3; } - const magnitude = Math.sqrt(vec.reduce((s2, v) => s2 + v * v, 0)); + const magnitude = Math.sqrt(vec.reduce((s3, v) => s3 + v * v, 0)); return magnitude > 0 ? vec.map((v) => v / magnitude) : vec; } async embedBatch(texts) { @@ -2222,24 +31572,24 @@ var InMemorySessionRepository = class { this.sessions.set(session.id, session); } async findByUser(userId, agentId, limit) { - const matches2 = Array.from(this.sessions.values()).filter((s2) => s2.userId === userId && s2.agentId === agentId).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); + const matches2 = Array.from(this.sessions.values()).filter((s3) => s3.userId === userId && s3.agentId === agentId).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); return limit ? matches2.slice(0, limit) : matches2; } async findByUserLightweight(userId, agentId, limit) { - const matches2 = Array.from(this.sessions.values()).filter((s2) => s2.userId === userId && s2.agentId === agentId).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()); + const matches2 = Array.from(this.sessions.values()).filter((s3) => s3.userId === userId && s3.agentId === agentId).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()); const limited = limit ? matches2.slice(0, limit) : matches2; - return limited.map((s2) => { - const firstUserMsg = s2.messages.find((m) => m.role === "user"); - const lastMsg = s2.messages.length > 0 ? s2.messages[s2.messages.length - 1] : void 0; + return limited.map((s3) => { + const firstUserMsg = s3.messages.find((m) => m.role === "user"); + const lastMsg = s3.messages.length > 0 ? s3.messages[s3.messages.length - 1] : void 0; return { - id: s2.id, - agentId: s2.agentId, - userId: s2.userId, - status: s2.status, - turnCount: s2.turnCount, - messageCount: s2.messages.length, - createdAt: s2.createdAt, - updatedAt: s2.updatedAt, + id: s3.id, + agentId: s3.agentId, + userId: s3.userId, + status: s3.status, + turnCount: s3.turnCount, + messageCount: s3.messages.length, + createdAt: s3.createdAt, + updatedAt: s3.updatedAt, firstMessage: firstUserMsg ? firstUserMsg.content.substring(0, 100) : void 0, lastMessage: lastMsg ? lastMsg.content.substring(0, 100) : void 0 }; @@ -2465,6 +31815,242 @@ function parseOntologyYaml(id, raw) { }; } +// ../freya/packages/mcp-client/dist/mcp-client-tool-executor.js +var NAME_MAX = 64; +var PROXY_LIST_MAX = 40; +function sanitizeName(raw) { + return raw.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, NAME_MAX); +} +var s = (v) => typeof v === "string" ? v.toLowerCase() : ""; +var McpClientToolExecutor = class { + servers; + scopePrefix; + mode; + clientFactory; + // One connected client per server, created lazily and reused across turns + // on a warm instance. `connecting` de-dupes concurrent connects. + clients = /* @__PURE__ */ new Map(); + connecting = /* @__PURE__ */ new Map(); + // Cached tools/list per server (per warm instance). + toolCache = /* @__PURE__ */ new Map(); + // namespaced tool name -> route, rebuilt on each discover. + routes = /* @__PURE__ */ new Map(); + constructor(config2) { + this.servers = new Map(config2.servers.map((server) => [server.id, server])); + this.scopePrefix = config2.scopePrefix ?? "mcp"; + this.mode = config2.mode ?? "direct"; + this.clientFactory = config2.clientFactory ?? createSdkClient; + } + /** Resolve a `mcp:` scope to its server, or null if not ours. */ + serverForScope(scope) { + const prefix = `${this.scopePrefix}:`; + if (!scope.startsWith(prefix)) + return null; + return this.servers.get(scope.slice(prefix.length)) ?? null; + } + async getClient(server) { + const existing = this.clients.get(server.id); + if (existing) + return existing; + const inFlight = this.connecting.get(server.id); + if (inFlight) + return inFlight; + const p = (async () => { + const client = this.clientFactory(server); + await client.connect(); + this.clients.set(server.id, client); + this.connecting.delete(server.id); + return client; + })().catch((e) => { + this.connecting.delete(server.id); + throw e; + }); + this.connecting.set(server.id, p); + return p; + } + /** Connect (if needed) and return the server's tools, cached per instance. */ + async fetchRawTools(server) { + const cached2 = this.toolCache.get(server.id); + if (cached2) + return cached2; + const client = await this.getClient(server); + const listed = await client.listTools(); + const tools = listed.tools ?? []; + this.toolCache.set(server.id, tools); + return tools; + } + async discoverTools(scope) { + const server = this.serverForScope(scope); + if (!server) + return []; + return this.mode === "proxy" ? this.discoverProxy(server, scope) : this.discoverDirect(server, scope); + } + /** Proxy mode: two small tools, no network at discovery time. */ + discoverProxy(server, scope) { + const listName = sanitizeName(`${server.id}__list_tools`); + const callName = sanitizeName(`${server.id}__call_tool`); + this.routes.set(listName, { serverId: server.id, proxy: "list" }); + this.routes.set(callName, { serverId: server.id, proxy: "call" }); + return [ + { + name: listName, + description: `List or search the tools available from the "${server.id}" MCP server. Returns each tool's name, description, and input schema. Call this to discover what "${server.id}" can do before using ${callName}.`, + inputSchema: { + type: "object", + properties: { + query: { + type: "string", + description: "Optional filter over tool name/description." + } + }, + additionalProperties: false + }, + source: scope, + requiresApproval: false, + permissionScope: `${scope}:list` + }, + { + name: callName, + description: `Invoke a tool on the "${server.id}" MCP server. Use ${listName} first to find the exact tool name and its required arguments.`, + inputSchema: { + type: "object", + properties: { + tool: { type: "string", description: `Tool name from ${listName}.` }, + arguments: { + type: "object", + description: "Arguments object matching that tool's input schema." + } + }, + required: ["tool"], + additionalProperties: false + }, + source: scope, + requiresApproval: false, + permissionScope: `${scope}:call` + } + ]; + } + /** Direct mode: fan every server tool out as its own definition. */ + async discoverDirect(server, scope) { + let tools; + try { + tools = await this.fetchRawTools(server); + } catch (e) { + console.log(`mcp-client: discover failed for ${server.id}:`, e instanceof Error ? e.message : String(e)); + return []; + } + const defs = []; + const used = /* @__PURE__ */ new Set(); + for (const tool of tools) { + let name = sanitizeName(`${server.id}__${tool.name}`); + if (used.has(name)) { + const base = name.slice(0, NAME_MAX - 3); + let i = 1; + while (used.has(`${base}_${i}`)) + i++; + name = `${base}_${i}`; + } + used.add(name); + this.routes.set(name, { serverId: server.id, toolName: tool.name }); + defs.push({ + name, + description: tool.description ?? `${tool.name} (via ${server.id})`, + inputSchema: tool.inputSchema ?? { type: "object", properties: {} }, + source: scope, + requiresApproval: false, + permissionScope: `${scope}:call` + }); + } + return defs; + } + async execute(call) { + const start = Date.now(); + const done = (output, status, error2) => ({ + callId: call.id, + toolName: call.toolName, + output, + status, + ...error2 ? { error: error2 } : {}, + durationMs: Date.now() - start, + timestamp: /* @__PURE__ */ new Date() + }); + const route = this.routes.get(call.toolName); + if (!route) + return done(null, "error", `unknown MCP tool: ${call.toolName}`); + const server = this.servers.get(route.serverId); + if (!server) + return done(null, "error", `unknown MCP server: ${route.serverId}`); + const input = call.input ?? {}; + try { + if (route.proxy === "list") { + const query = typeof input.query === "string" ? input.query : ""; + const tools = (await this.fetchRawTools(server)).filter((t) => !query || s(t.name).includes(s(query)) || s(t.description).includes(s(query))).slice(0, PROXY_LIST_MAX).map((t) => ({ + tool: t.name, + description: t.description ?? "", + inputSchema: t.inputSchema ?? { type: "object" } + })); + return done({ server: server.id, count: tools.length, tools }, "success"); + } + const toolName = route.proxy === "call" ? typeof input.tool === "string" ? input.tool : "" : route.toolName ?? ""; + if (!toolName) { + return done(null, "error", `no tool name provided for ${call.toolName}`); + } + const args = route.proxy === "call" ? input.arguments ?? {} : input; + const client = await this.getClient(server); + const result = await client.callTool({ name: toolName, arguments: args }); + const text = (result.content ?? []).filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n").trim(); + const output = text || result.content || null; + return done(output, result.isError ? "error" : "success"); + } catch (e) { + return done(null, "error", e instanceof Error ? e.message : String(e)); + } + } + /** Close all open MCP connections (best-effort). */ + async close() { + for (const client of this.clients.values()) { + try { + await client.close?.(); + } catch { + } + } + this.clients.clear(); + } +}; +function createSdkClient(server) { + let ready = null; + const init = async () => { + const { Client: Client2, StreamableHTTPClientTransport: StreamableHTTPClientTransport2 } = await Promise.resolve().then(() => (init_dist3(), dist_exports)); + const client = new Client2({ name: "freya-mcp-client", version: "0.1.0" }); + const transport = new StreamableHTTPClientTransport2(new URL(server.url), server.headers ? { requestInit: { headers: server.headers } } : void 0); + await client.connect(transport); + return { + listTools: () => client.listTools(), + callTool: (a) => client.callTool(a), + close: () => client.close() + }; + }; + return { + async connect() { + ready = init(); + await ready; + }, + async listTools() { + if (!ready) + ready = init(); + return (await ready).listTools(); + }, + async callTool(a) { + if (!ready) + ready = init(); + return (await ready).callTool(a); + }, + async close() { + if (ready) + await (await ready).close(); + } + }; +} + // website/tools/freya-vendor/entry.mjs var AGENT_ID = "frigg-web"; var TRANSPORT = "netlify-web"; @@ -2525,8 +32111,8 @@ var FRIGG_ONTOLOGY = { } }; var activeData = { adrs: [], apis: [], categories: [], builtCount: 0 }; -var s = (v) => typeof v === "string" ? v.toLowerCase() : ""; -var matches = (hay, q) => !q || s(hay).includes(s(q)); +var s2 = (v) => typeof v === "string" ? v.toLowerCase() : ""; +var matches = (hay, q) => !q || s2(hay).includes(s2(q)); var RoadmapTools = class { async discoverTools(scope) { if (scope !== "roadmap") return []; @@ -2574,12 +32160,12 @@ var RoadmapTools = class { } async execute(call) { const start = Date.now(); - const done = (output, status = "success", error) => ({ + const done = (output, status = "success", error2) => ({ callId: call.id, toolName: call.toolName, output, status, - error, + error: error2, durationMs: Date.now() - start, timestamp: /* @__PURE__ */ new Date() }); @@ -2595,7 +32181,7 @@ var RoadmapTools = class { } if (call.toolName === "search_adrs") { const hits = activeData.adrs.filter( - (a) => (matches(a.title, input.query) || matches(a.summary, input.query) || matches(a.theme, input.query)) && (!input.status || s(a.status) === s(input.status)) + (a) => (matches(a.title, input.query) || matches(a.summary, input.query) || matches(a.theme, input.query)) && (!input.status || s2(a.status) === s2(input.status)) ); return done({ total: hits.length, @@ -2611,7 +32197,7 @@ var RoadmapTools = class { } if (call.toolName === "search_apis") { const hits = activeData.apis.filter( - (a) => (matches(a.name, input.query) || matches(a.provider, input.query) || matches(a.description, input.query) || Array.isArray(a.tags) && a.tags.some((t) => matches(t, input.query))) && (!input.category || s(a.category) === s(input.category)) && (input.built === void 0 || Boolean(a.built) === Boolean(input.built)) + (a) => (matches(a.name, input.query) || matches(a.provider, input.query) || matches(a.description, input.query) || Array.isArray(a.tags) && a.tags.some((t) => matches(t, input.query))) && (!input.category || s2(a.category) === s2(input.category)) && (input.built === void 0 || Boolean(a.built) === Boolean(input.built)) ); return done({ total: hits.length, @@ -2634,14 +32220,70 @@ var RoadmapTools = class { } } }; +function mcpServersFromEnv() { + const servers = []; + if (process.env.CONTEXT7_API_KEY) { + servers.push({ + id: "frigg-docs", + url: process.env.CONTEXT7_MCP_URL || "https://mcp.context7.com/mcp", + headers: { CONTEXT7_API_KEY: process.env.CONTEXT7_API_KEY } + }); + } + const ghToken = process.env.GITHUB_MCP_TOKEN; + if (ghToken) { + servers.push({ + id: "frigg-repo", + url: process.env.GITHUB_MCP_URL || "https://api.githubcopilot.com/mcp/", + headers: { Authorization: `Bearer ${ghToken}` } + }); + } + return servers; +} +var CompositeToolExecutor = class { + constructor(executors) { + this.executors = executors; + this.owner = /* @__PURE__ */ new Map(); + } + async discoverTools(scope) { + for (const ex of this.executors) { + const defs = await ex.discoverTools(scope); + if (defs && defs.length) { + for (const d of defs) this.owner.set(d.name, ex); + return defs; + } + } + return []; + } + async execute(call) { + const ex = this.owner.get(call.toolName); + if (ex) return ex.execute(call); + return { + callId: call.id, + toolName: call.toolName, + output: null, + status: "error", + error: `no executor for tool: ${call.toolName}`, + durationMs: 0, + timestamp: /* @__PURE__ */ new Date() + }; + } +}; var runtime = null; var sessionsRepo = null; var registered = false; +var mcpScopes = []; function getRuntime() { if (runtime) return runtime; sessionsRepo = new InMemorySessionRepository(); const apiKey = process.env.ANTHROPIC_API_KEY || ""; const baseUrl = process.env.ANTHROPIC_BASE_URL || void 0; + const executors = [new RoadmapTools()]; + const mcpServers = mcpServersFromEnv(); + if (mcpServers.length) { + executors.push(new McpClientToolExecutor({ servers: mcpServers, mode: "proxy" })); + mcpScopes = mcpServers.map((sv) => `mcp:${sv.id}`); + } + const toolExecutor = new CompositeToolExecutor(executors); runtime = createAgentRuntime({ llm: new AnthropicLLM({ apiKey, @@ -2649,7 +32291,7 @@ function getRuntime() { defaultModel: process.env.ASSISTANT_MODEL || "claude-opus-4-8", maxTokens: 900 }), - toolExecutor: new RoadmapTools(), + toolExecutor, memory: new InMemoryMemoryRepository(), ontologyRepo: (() => { const repo = new InMemoryOntologyRepository(); @@ -2671,7 +32313,7 @@ async function ensureAgent(rt, systemPrompt, model) { systemPrompt, ontologyScopes: ["frigg"], memoryNamespaces: ["default"], - toolScopes: ["roadmap"], + toolScopes: ["roadmap", ...mcpScopes], routines: [], delegationTargets: [], modelId: model || process.env.ASSISTANT_MODEL || "claude-opus-4-8", diff --git a/website/tools/freya-vendor/entry.mjs b/website/tools/freya-vendor/entry.mjs index 6bac20114..073d2ec5e 100644 --- a/website/tools/freya-vendor/entry.mjs +++ b/website/tools/freya-vendor/entry.mjs @@ -24,6 +24,7 @@ import { createSession, addMessage, } from '@freyaframework/core'; +import { McpClientToolExecutor } from '@freyaframework/mcp-client'; const AGENT_ID = 'frigg-web'; const TRANSPORT = 'netlify-web'; @@ -225,15 +226,93 @@ class RoadmapTools { } } +/** + * Configure the MCP servers the assistant can reach, from env. Each is offered + * only when its credential is present, so the widget degrades gracefully: + * - frigg-docs → Context7 (semantic docs), pinned to the next branch via the + * repo's context7.json. Needs CONTEXT7_API_KEY. + * - frigg-repo → GitHub's MCP server (branch-accurate file/code on next). + * Needs GITHUB_MCP_TOKEN (a read-only token); URL overridable via GITHUB_MCP_URL. + */ +function mcpServersFromEnv() { + const servers = []; + if (process.env.CONTEXT7_API_KEY) { + servers.push({ + id: 'frigg-docs', + url: process.env.CONTEXT7_MCP_URL || 'https://mcp.context7.com/mcp', + headers: { CONTEXT7_API_KEY: process.env.CONTEXT7_API_KEY }, + }); + } + // Dedicated var only — do NOT fall back to an ambient GITHUB_TOKEN, which is + // commonly present in host/CI envs and would half-activate this server with a + // wrong-scoped token. + const ghToken = process.env.GITHUB_MCP_TOKEN; + if (ghToken) { + servers.push({ + id: 'frigg-repo', + url: process.env.GITHUB_MCP_URL || 'https://api.githubcopilot.com/mcp/', + headers: { Authorization: `Bearer ${ghToken}` }, + }); + } + return servers; +} + +/** + * Fans discovery/execution across sub-executors (roadmap tools + MCP client). + * Each sub-executor returns [] for scopes it doesn't own, so exactly one claims + * a given scope; the owning executor for each discovered tool is remembered so + * execute() routes straight back to it. + */ +class CompositeToolExecutor { + constructor(executors) { + this.executors = executors; + this.owner = new Map(); + } + async discoverTools(scope) { + for (const ex of this.executors) { + const defs = await ex.discoverTools(scope); + if (defs && defs.length) { + for (const d of defs) this.owner.set(d.name, ex); + return defs; + } + } + return []; + } + async execute(call) { + const ex = this.owner.get(call.toolName); + if (ex) return ex.execute(call); + return { + callId: call.id, + toolName: call.toolName, + output: null, + status: 'error', + error: `no executor for tool: ${call.toolName}`, + durationMs: 0, + timestamp: new Date(), + }; + } +} + let runtime = null; let sessionsRepo = null; let registered = false; +let mcpScopes = []; function getRuntime() { if (runtime) return runtime; sessionsRepo = new InMemorySessionRepository(); const apiKey = process.env.ANTHROPIC_API_KEY || ''; const baseUrl = process.env.ANTHROPIC_BASE_URL || undefined; + + // Roadmap tools always; MCP servers (Context7 docs, GitHub repo) when keyed. + const executors = [new RoadmapTools()]; + const mcpServers = mcpServersFromEnv(); + if (mcpServers.length) { + executors.push(new McpClientToolExecutor({ servers: mcpServers, mode: 'proxy' })); + mcpScopes = mcpServers.map((sv) => `mcp:${sv.id}`); + } + const toolExecutor = new CompositeToolExecutor(executors); + runtime = createAgentRuntime({ llm: new AnthropicLLM({ apiKey, @@ -241,7 +320,7 @@ function getRuntime() { defaultModel: process.env.ASSISTANT_MODEL || 'claude-opus-4-8', maxTokens: 900, }), - toolExecutor: new RoadmapTools(), + toolExecutor, memory: new InMemoryMemoryRepository(), ontologyRepo: (() => { const repo = new InMemoryOntologyRepository(); @@ -264,7 +343,7 @@ async function ensureAgent(rt, systemPrompt, model) { systemPrompt, ontologyScopes: ['frigg'], memoryNamespaces: ['default'], - toolScopes: ['roadmap'], + toolScopes: ['roadmap', ...mcpScopes], routines: [], delegationTargets: [], modelId: model || process.env.ASSISTANT_MODEL || 'claude-opus-4-8', From d1c6222f6f7b0a9702f5f90fec9d387846091e26 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 24 Jul 2026 13:35:59 +0000 Subject: [PATCH 2/2] Minify the vendored Freya bundle The bundle is a generated, Sonar-excluded artifact, and the MCP SDK it inlines (@modelcontextprotocol/client + zod + jose) is large. Enabling esbuild minify cuts the shipped file 1.25 MB -> 572 KB (~159 KB gzipped on the wire) with no behavior change; verified the MCP tool wiring still loads and is offered. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_018ixfrejnfZWd8TPZamZYdv --- .../friggframework-api/lib/freya-runtime.mjs | 32377 +--------------- website/tools/freya-vendor/build.mjs | 4 + 2 files changed, 51 insertions(+), 32330 deletions(-) diff --git a/website/friggframework-api/lib/freya-runtime.mjs b/website/friggframework-api/lib/freya-runtime.mjs index 8c5c975e7..5062c2d68 100644 --- a/website/friggframework-api/lib/freya-runtime.mjs +++ b/website/friggframework-api/lib/freya-runtime.mjs @@ -1,32356 +1,73 @@ // GENERATED — vendored Freya runtime. Do not edit by hand. // Regenerate via website/tools/freya-vendor/build.mjs. -var __defProp = Object.defineProperty; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; - -// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/chunk-Br0eD_fh.mjs -var __create, __defProp2, __getOwnPropDesc, __getOwnPropNames2, __getProtoOf, __hasOwnProp, __commonJSMin, __exportAll, __copyProps, __toESM; -var init_chunk_Br0eD_fh = __esm({ - "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/chunk-Br0eD_fh.mjs"() { - __create = Object.create; - __defProp2 = Object.defineProperty; - __getOwnPropDesc = Object.getOwnPropertyDescriptor; - __getOwnPropNames2 = Object.getOwnPropertyNames; - __getProtoOf = Object.getPrototypeOf; - __hasOwnProp = Object.prototype.hasOwnProperty; - __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); - __exportAll = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp2(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp2(target, Symbol.toStringTag, { value: "Module" }); - } - return target; - }; - __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames2(from), i = 0, n = keys.length, key; i < n; i++) { - key = keys[i]; - if (!__hasOwnProp.call(to, key) && key !== except) { - __defProp2(to, key, { - get: ((k) => from[k]).bind(null, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - } - } - return to; - }; - __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { - value: mod, - enumerable: true - }) : target, mod)); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a2; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a2 = inst._zod).deferred ?? (_a2.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - 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 _; -} -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} -var NEVER, $ZodAsyncError, $ZodEncodeError, globalConfig; -var init_core = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"() { - NEVER = Object.freeze({ - status: "aborted" - }); - $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } - }; - $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } - }; - globalConfig = {}; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js -var util_exports = {}; -__export(util_exports, { - BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, - Class: () => Class, - NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, - aborted: () => aborted, - allowsEval: () => allowsEval, - assert: () => assert, - assertEqual: () => assertEqual, - assertIs: () => assertIs, - assertNever: () => assertNever, - assertNotEqual: () => assertNotEqual, - assignProp: () => assignProp, - base64ToUint8Array: () => base64ToUint8Array, - base64urlToUint8Array: () => base64urlToUint8Array, - cached: () => cached, - captureStackTrace: () => captureStackTrace, - cleanEnum: () => cleanEnum, - cleanRegex: () => cleanRegex, - clone: () => clone, - cloneDef: () => cloneDef, - createTransparentProxy: () => createTransparentProxy, - defineLazy: () => defineLazy, - esc: () => esc, - escapeRegex: () => escapeRegex2, - extend: () => extend, - finalizeIssue: () => finalizeIssue, - floatSafeRemainder: () => floatSafeRemainder, - getElementAtPath: () => getElementAtPath, - getEnumValues: () => getEnumValues, - getLengthableOrigin: () => getLengthableOrigin, - getParsedType: () => getParsedType, - getSizableOrigin: () => getSizableOrigin, - hexToUint8Array: () => hexToUint8Array, - isObject: () => isObject, - isPlainObject: () => isPlainObject, - issue: () => issue, - joinValues: () => joinValues, - jsonStringifyReplacer: () => jsonStringifyReplacer, - merge: () => merge, - mergeDefs: () => mergeDefs, - normalizeParams: () => normalizeParams, - nullish: () => nullish, - numKeys: () => numKeys, - objectClone: () => objectClone, - omit: () => omit, - optionalKeys: () => optionalKeys, - parsedType: () => parsedType, - partial: () => partial, - pick: () => pick, - prefixIssues: () => prefixIssues, - primitiveTypes: () => primitiveTypes, - promiseAllObject: () => promiseAllObject, - propertyKeyTypes: () => propertyKeyTypes, - randomString: () => randomString, - required: () => required, - safeExtend: () => safeExtend, - shallowClone: () => shallowClone, - slugify: () => slugify, - stringifyPrimitive: () => stringifyPrimitive, - uint8ArrayToBase64: () => uint8ArrayToBase64, - uint8ArrayToBase64url: () => uint8ArrayToBase64url, - uint8ArrayToHex: () => uint8ArrayToHex, - unwrapMessage: () => unwrapMessage -}); -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -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(array2, separator = "|") { - return array2.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - } - }; -} -function nullish(input) { - return input === null || input === void 0; -} -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 valDecCount = (val.toString().split(".")[1] || "").length; - const stepString = step.toString(); - let stepDecCount = (stepString.split(".")[1] || "").length; - if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { - const match = stepString.match(/\d?e-(\d?)/); - if (match?.[1]) { - stepDecCount = Number.parseInt(match[1]); - } - } - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -function defineLazy(object2, key, getter) { - let value = void 0; - Object.defineProperty(object2, key, { - get() { - if (value === EVALUATING) { - return void 0; - } - if (value === void 0) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object2, key, { - value: v - // configurable: true, - }); - }, - 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 esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); -} -function isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -function isPlainObject(o) { - if (isObject(o) === false) - return false; - const ctor = o.constructor; - if (ctor === void 0) - return true; - if (typeof ctor !== "function") - return true; - const prot = ctor.prototype; - if (isObject(prot) === false) - return false; - 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]; - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -function escapeRegex2(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -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 !== void 0) { - if (params?.error !== void 0) - 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 === "optional" && shape[k]._zod.optout === "optional"; - }); -} -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 (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - 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 in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - 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) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { - 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); - 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); - return _shape; - } - }); - return clone(schema, def); -} -function merge(a, b) { - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: [] - // delete existing checks - }); - return clone(a, def); -} -function partial(Class2, schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".partial() 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 in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone(schema, def); -} -function required(Class2, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone(schema, def); -} -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; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a2; - (_a2 = iss).path ?? (_a2.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message2) { - return typeof message2 === "string" ? message2 : message2?.message; -} -function finalizeIssue(iss, ctx, config2) { - const full = { ...iss, path: iss.path ?? [] }; - if (!iss.message) { - const message2 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; - full.message = message2; - } - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; - } - return full; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - if (input instanceof File) - return "file"; - return "unknown"; -} -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 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 Number.isNaN(Number.parseInt(k, 10)); - }).map((el) => el[1]); -} -function base64ToUint8Array(base643) { - const binaryString = atob(base643); - 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(base64url3) { - const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - base643.length % 4) % 4); - return base64ToUint8Array(base643 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex3) { - const cleanHex = hex3.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(""); -} -var EVALUATING, captureStackTrace, allowsEval, getParsedType, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; -var init_util = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"() { - EVALUATING = /* @__PURE__ */ Symbol("evaluating"); - captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { - }; - allowsEval = cached(() => { - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } catch (_) { - return false; - } - }); - 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"; - } - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } - }; - propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); - primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); - NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-34028234663852886e22, 34028234663852886e22], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE] - }; - BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], - uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] - }; - Class = class { - constructor(..._args) { - } - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js -function flattenError(error2, mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error2.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error2, mapper = (issue2) => issue2.message) { - const fieldErrors = { _errors: [] }; - const processError = (error3) => { - for (const issue2 of error3.issues) { - if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues) => processError({ issues })); - } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }); - } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(error2); - return fieldErrors; -} -var initializer, $ZodError, $ZodRealError; -var init_errors = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js"() { - init_core(); - init_util(); - initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false - }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false - }); - }; - $ZodError = $constructor("$ZodError", initializer); - $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js -var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, _decode, _encodeAsync, _decodeAsync, _safeEncode, _safeDecode, _safeEncodeAsync, _safeDecodeAsync; -var init_parse = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"() { - init_core(); - init_errors(); - init_util(); - _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? Object.assign(_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, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; - }; - parse = /* @__PURE__ */ _parse($ZodRealError); - _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_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, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; - }; - parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); - _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, config()))) - } : { success: true, data: result.value }; - }; - safeParse = /* @__PURE__ */ _safeParse($ZodRealError); - _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_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, config()))) - } : { success: true, data: result.value }; - }; - safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); - _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); - }; - _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); - }; - _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); - }; - _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); - }; - _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); - }; - _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); - }; - _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); - }; - _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js -var regexes_exports = {}; -__export(regexes_exports, { - base64: () => base64, - base64url: () => base64url, - bigint: () => bigint, - boolean: () => boolean, - browserEmail: () => browserEmail, - cidrv4: () => cidrv4, - cidrv6: () => cidrv6, - cuid: () => cuid, - cuid2: () => cuid2, - date: () => date, - datetime: () => datetime, - domain: () => domain, - duration: () => duration, - e164: () => e164, - email: () => email, - emoji: () => emoji, - extendedDuration: () => extendedDuration, - guid: () => guid, - hex: () => hex, - hostname: () => hostname, - html5Email: () => html5Email, - idnEmail: () => idnEmail, - integer: () => integer, - ipv4: () => ipv4, - ipv6: () => ipv6, - ksuid: () => ksuid, - lowercase: () => lowercase, - mac: () => mac, - md5_base64: () => md5_base64, - md5_base64url: () => md5_base64url, - md5_hex: () => md5_hex, - nanoid: () => nanoid, - null: () => _null, - number: () => number, - rfc5322Email: () => rfc5322Email, - sha1_base64: () => sha1_base64, - sha1_base64url: () => sha1_base64url, - sha1_hex: () => sha1_hex, - sha256_base64: () => sha256_base64, - sha256_base64url: () => sha256_base64url, - sha256_hex: () => sha256_hex, - sha384_base64: () => sha384_base64, - sha384_base64url: () => sha384_base64url, - sha384_hex: () => sha384_hex, - sha512_base64: () => sha512_base64, - sha512_base64url: () => sha512_base64url, - sha512_hex: () => sha512_hex, - string: () => string, - time: () => time, - ulid: () => ulid, - undefined: () => _undefined, - unicodeEmail: () => unicodeEmail, - uppercase: () => uppercase, - uuid: () => uuid, - uuid4: () => uuid4, - uuid6: () => uuid6, - uuid7: () => uuid7, - xid: () => xid -}); -function emoji() { - return new RegExp(_emoji, "u"); -} -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}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -function datetime(args) { - const time3 = timeSource({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) - opts.push(""); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time3}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; -var init_regexes = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"() { - init_util(); - cuid = /^[cC][^\s-]{8,}$/; - cuid2 = /^[0-9a-z]+$/; - ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; - xid = /^[0-9a-vA-V]{20}$/; - ksuid = /^[A-Za-z0-9]{27}$/; - nanoid = /^[a-zA-Z0-9_-]{21}$/; - duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; - 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)?)??$/; - 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})$/; - uuid = (version2) => { - if (!version2) - 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}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); - }; - uuid4 = /* @__PURE__ */ uuid(4); - uuid6 = /* @__PURE__ */ uuid(6); - uuid7 = /* @__PURE__ */ uuid(7); - email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; - 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])?)*$/; - 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,}))$/; - unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; - idnEmail = unicodeEmail; - 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])?)*$/; - _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; - 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])$/; - 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}|:))$/; - mac = (delimiter) => { - const escapedDelim = escapeRegex2(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); - }; - 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])$/; - cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; - base64url = /^[A-Za-z0-9_-]*$/; - 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])?)*\.?$/; - domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; - e164 = /^\+[1-9]\d{6,14}$/; - 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])))`; - date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); - string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); - }; - bigint = /^-?\d+n?$/; - integer = /^-?\d+$/; - number = /^-?\d+(?:\.\d+)?$/; - boolean = /^(?:true|false)$/i; - _null = /^null$/i; - _undefined = /^undefined$/i; - lowercase = /^[^A-Z]*$/; - uppercase = /^[^a-z]*$/; - hex = /^[0-9a-fA-F]*$/; - md5_hex = /^[0-9a-fA-F]{32}$/; - md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); - md5_base64url = /* @__PURE__ */ fixedBase64url(22); - sha1_hex = /^[0-9a-fA-F]{40}$/; - sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); - sha1_base64url = /* @__PURE__ */ fixedBase64url(27); - sha256_hex = /^[0-9a-fA-F]{64}$/; - sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); - sha256_base64url = /* @__PURE__ */ fixedBase64url(43); - sha384_hex = /^[0-9a-fA-F]{96}$/; - sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); - sha384_base64url = /* @__PURE__ */ fixedBase64url(64); - sha512_hex = /^[0-9a-fA-F]{128}$/; - sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); - sha512_base64url = /* @__PURE__ */ fixedBase64url(86); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...prefixIssues(property, result.issues)); - } -} -var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite; -var init_checks = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js"() { - init_core(); - init_regexes(); - init_util(); - $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { - var _a2; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a2 = inst._zod).onattach ?? (_a2.onattach = []); - }); - numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date" - }; - $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._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, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._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, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a2; - (_a2 = inst2._zod.bag).multipleOf ?? (_a2.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" ? 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 - }); - }; - }); - $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); - 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((inst2) => { - const bag = inst2._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)) { - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst - }); - return; - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - 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 { - 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 - }); - } - }; - }); - $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); - const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._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, - 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 - }); - } - }; - }); - $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { - var _a2; - $ZodCheck.init(inst, def); - (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._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: getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { - var _a2; - $ZodCheck.init(inst, def); - (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._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: getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a2; - $ZodCheck.init(inst, def); - (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._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: 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 - }); - }; - }); - $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a2; - $ZodCheck.init(inst, def); - (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - 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 - }); - }; - }); - $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a2; - $ZodCheck.init(inst, def); - (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - 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 - }); - }; - }); - $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a2; - $ZodCheck.init(inst, def); - (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - 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 - }); - }; - }); - $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a2, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a2 = inst._zod).check ?? (_a2.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 = () => { - }); - }); - $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 - }); - }; - }); - $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); - }); - $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); - }); - $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex2(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 - }); - }; - }); - $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex2(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 - }); - }; - }); - $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex2(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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 = /* @__PURE__ */ $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((result2) => handleCheckPropertyResult(result2, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; - }); - $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._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 - }); - }; - }); - $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; - }); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js -var Doc; -var init_doc = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js"() { - Doc = class { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) - this.args = args; - } - 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 args = this?.args; - const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js -var version; -var init_versions = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js"() { - version = { - major: 4, - minor: 3, - patch: 6 - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js -function isValidBase64(data) { - if (data === "") - return true; - if (data.length % 4 !== 0) - return false; - try { - atob(data); - return true; - } catch { - return false; - } -} -function isValidBase64URL(data) { - if (!base64url.test(data)) - return false; - const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); - const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); - return isValidBase64(padded); -} -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - 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; - } -} -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handlePropertyResult(result, final, key, input, isOptionalOut) { - if (result.issues.length) { - if (isOptionalOut && !(key in input)) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (result.value === void 0) { - if (key in input) { - final.value[key] = void 0; - } - } else { - final.value[key] = result.value; - } -} -function normalizeDef(def) { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - keys, - 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 isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (keySet.has(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((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); - } else { - handlePropertyResult(r, payload, key, input, isOptionalOut); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -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, config()))) - }); - return final; -} -function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; - return final; - } - if (successes.length === 0) { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - }); - } else { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false - }); - } - return final; -} -function mergeValues(a, 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 }; - for (const key of sharedKeys) { - const sharedValue = 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 = 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) { - const unrecKeys = /* @__PURE__ */ new Map(); - let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { - unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } - } else { - result.issues.push(iss); - } - } - for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } else { - result.issues.push(iss); - } - } - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); - } - if (aborted(result)) - return result; - const merged = mergeValues(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, keyResult.issues)); - } else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }); - } - } - if (valueResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, valueResult.issues)); - } else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key, - issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -function handleOptionalResult(result, input) { - if (result.issues.length && input === void 0) { - return { issues: [], value: void 0 }; - } - return result; -} -function handleDefaultResult(payload, def) { - if (payload.value === void 0) { - payload.value = def.defaultValue; - } - return payload; -} -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === void 0) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst - }); - } - return payload; -} -function handlePipeResult(left, next, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - 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) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -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(issue(_iss)); - } -} -var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom; -var init_schemas = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js"() { - init_checks(); - init_core(); - init_doc(); - init_parse(); - init_regexes(); - init_util(); - init_versions(); - init_util(); - $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { - var _a2; - inst ?? (inst = {}); - inst._zod.def = def; - inst._zod.bag = inst._zod.bag || {}; - inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - (_a2 = inst._zod).deferred ?? (_a2.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } else { - const runChecks = (payload, checks2, ctx) => { - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks2) { - if (ch._zod.def.when) { - 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; - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, 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") { - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary2) => { - return handleCanaryResult(canary2, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result2) => runChecks(result2, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } - defineLazy(inst, "~standard", () => ({ - validate: (value) => { - try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); - } - }, - vendor: "zod", - version: 1 - })); - }); - $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } catch (_2) { - } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; - }); - $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); - }); - $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); - }); - $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 === void 0) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); - }); - $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); - }); - $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - const trimmed = payload.value.trim(); - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.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) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - } - if (def.normalize) { - payload.value = url2.href; - } else { - payload.value = trimmed; - } - return; - } catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); - }); - $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); - $ZodStringFormat.init(inst, def); - }); - $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); - }); - $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); - }); - $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); - }); - $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); - }); - $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); - }); - $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - }); - $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date); - $ZodStringFormat.init(inst, def); - }); - $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time(def)); - $ZodStringFormat.init(inst, def); - }); - $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); - }); - $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; - }); - $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; - }); - $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); - }); - $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = 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 - }); - }; - }); - $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = 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 - }); - }; - }); - $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); - }); - $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 - }); - }; - }); - $ZodCustomStringFormat = /* @__PURE__ */ $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 - }); - }; - }); - $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) ? "Infinity" : void 0 : void 0; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...received ? { received } : {} - }); - return payload; - }; - }); - $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); - }); - $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = 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; - }; - }); - $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = 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; - }; - }); - $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { - $ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); - }); - $ZodSymbol = /* @__PURE__ */ $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; - }; - }); - $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _undefined; - inst._zod.values = /* @__PURE__ */ new Set([void 0]); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - 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; - }; - }); - $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = /* @__PURE__ */ 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; - }; - }); - $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; - }); - $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; - }); - $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; - }; - }); - $ZodVoid = /* @__PURE__ */ $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; - }; - }); - $ZodDate = /* @__PURE__ */ $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; - }; - }); - $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - 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 = 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((result2) => handleArrayResult(result2, payload, i))); - } else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; - }); - $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { - $ZodType.init(inst, def); - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); - } - const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); - for (const v of field.values) - propValues[key].add(v); - } - } - return propValues; - }); - const isObject3 = isObject; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = {}; - const proms = []; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); - } else { - handlePropertyResult(r, payload, key, input, isOptionalOut); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; - }); - $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = cached(() => normalizeDef(def)); - const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = /* @__PURE__ */ Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { - const id = ids[key]; - const k = esc(key); - const schema = shape[key]; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); - if (isOptionalOut) { - doc.write(` - if (${id}.issues.length) { +var Vk=Object.defineProperty;var q=(e,t)=>()=>(e&&(t=e(e=0)),t);var nr=(e,t)=>{for(var r in t)Vk(e,r,{get:t[r],enumerable:!0})};var iE,sc,aE,sE,cE,uE,H,Zy,lE,cc,cp=q(()=>{iE=Object.create,sc=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,sE=Object.getOwnPropertyNames,cE=Object.getPrototypeOf,uE=Object.prototype.hasOwnProperty,H=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Zy=(e,t)=>{let r={};for(var n in e)sc(r,n,{get:e[n],enumerable:!0});return t&&sc(r,Symbol.toStringTag,{value:"Module"}),r},lE=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var o=sE(t),i=0,a=o.length,s;it[c]).bind(null,s),enumerable:!(n=aE(t,s))||n.enumerable});return e},cc=(e,t,r)=>(r=e!=null?iE(cE(e)):{},lE(t||!e||!e.__esModule?sc(r,"default",{value:e,enumerable:!0}):r,e))});function C(e,t,r){function n(s,c){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,c);let u=a.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}function lt(e){return e&&Object.assign(uc,e),uc}var up,ir,En,uc,yo=q(()=>{up=Object.freeze({status:"aborted"});ir=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},En=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},uc={}});var G={};nr(G,{BIGINT_FORMAT_RANGES:()=>vp,Class:()=>dp,NUMBER_FORMAT_RANGES:()=>yp,aborted:()=>Kr,allowsEval:()=>fp,assert:()=>hE,assertEqual:()=>dE,assertIs:()=>mE,assertNever:()=>fE,assertNotEqual:()=>pE,assignProp:()=>Lr,base64ToUint8Array:()=>Gy,base64urlToUint8Array:()=>CE,cached:()=>_o,captureStackTrace:()=>dc,cleanEnum:()=>TE,cleanRegex:()=>Bi,clone:()=>At,cloneDef:()=>yE,createTransparentProxy:()=>wE,defineLazy:()=>Ie,esc:()=>lc,escapeRegex:()=>qt,extend:()=>EE,finalizeIssue:()=>Rt,floatSafeRemainder:()=>pp,getElementAtPath:()=>vE,getEnumValues:()=>Wi,getLengthableOrigin:()=>Yi,getParsedType:()=>$E,getSizableOrigin:()=>Xi,hexToUint8Array:()=>OE,isObject:()=>Rn,isPlainObject:()=>Vr,issue:()=>So,joinValues:()=>ge,jsonStringifyReplacer:()=>vo,merge:()=>xE,mergeDefs:()=>Sr,normalizeParams:()=>X,nullish:()=>qr,numKeys:()=>bE,objectClone:()=>gE,omit:()=>kE,optionalKeys:()=>gp,parsedType:()=>Se,partial:()=>IE,pick:()=>zE,prefixIssues:()=>Ot,primitiveTypes:()=>hp,promiseAllObject:()=>_E,propertyKeyTypes:()=>Gi,randomString:()=>SE,required:()=>PE,safeExtend:()=>RE,shallowClone:()=>By,slugify:()=>mp,stringifyPrimitive:()=>ye,uint8ArrayToBase64:()=>Xy,uint8ArrayToBase64url:()=>AE,uint8ArrayToHex:()=>NE,unwrapMessage:()=>Zi});function dE(e){return e}function pE(e){return e}function mE(e){}function fE(e){throw new Error("Unexpected value in exhaustive check")}function hE(e){}function Wi(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ge(e,t="|"){return e.map(r=>ye(r)).join(t)}function vo(e,t){return typeof t=="bigint"?t.toString():t}function _o(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function qr(e){return e==null}function Bi(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function pp(e,t){let r=(e.toString().split(".")[1]||"").length,n=t.toString(),o=(n.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(n)){let c=n.match(/\d?e-(\d?)/);c?.[1]&&(o=Number.parseInt(c[1]))}let i=r>o?r:o,a=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return a%s/10**i}function Ie(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Wy)return n===void 0&&(n=Wy,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function gE(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Lr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Sr(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function yE(e){return Sr(e._zod.def)}function vE(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function _E(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;it};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function wE(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ye(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function gp(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function zE(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Sr(e._zod.def,{get shape(){let a={};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(a[s]=r.shape[s])}return Lr(this,"shape",a),a},checks:[]});return At(e,i)}function kE(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Sr(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete a[s]}return Lr(this,"shape",a),a},checks:[]});return At(e,i)}function EE(e,t){if(!Vr(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Sr(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Lr(this,"shape",i),i}});return At(e,o)}function RE(e,t){if(!Vr(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Sr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lr(this,"shape",n),n}});return At(e,r)}function xE(e,t){let r=Sr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Lr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return At(e,r)}function IE(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let a=Sr(t._zod.def,{get shape(){let s=t._zod.def.shape,c={...s};if(r)for(let u in r){if(!(u in s))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=e?new e({type:"optional",innerType:s[u]}):s[u])}else for(let u in s)c[u]=e?new e({type:"optional",innerType:s[u]}):s[u];return Lr(this,"shape",c),c},checks:[]});return At(t,a)}function PE(e,t,r){let n=Sr(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new e({type:"nonoptional",innerType:o[a]}))}else for(let a in o)i[a]=new e({type:"nonoptional",innerType:o[a]});return Lr(this,"shape",i),i}});return At(t,n)}function Kr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Zi(e){return typeof e=="string"?e:e?.message}function Rt(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Zi(e.inst?._zod.def?.error?.(e))??Zi(t?.error?.(e))??Zi(r.customError?.(e))??Zi(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Xi(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Yi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Se(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function So(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function TE(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Gy(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;nt.toString(16).padStart(2,"0")).join("")}var Wy,dc,fp,$E,Gi,hp,yp,vp,dp,de=q(()=>{Wy=Symbol("evaluating");dc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};fp=_o(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});$E=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Gi=new Set(["string","number","symbol"]),hp=new Set(["string","number","bigint","boolean","symbol","undefined"]);yp={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},vp={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};dp=class{constructor(...t){}}});function _p(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Sp(e,t=r=>r.message){let r={_errors:[]},n=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)r._errors.push(t(i));else{let a=r,s=0;for(;s{yo();de();Yy=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},pc=C("$ZodError",Yy),Qi=C("$ZodError",Yy,{Parent:Error})});var ea,$p,ta,wp,ra,Qy,na,ev,tv,rv,nv,ov,iv,av,sv,cv,zp=q(()=>{yo();bp();de();ea=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new ir;if(a.issues.length){let s=new(o?.Err??e)(a.issues.map(c=>Rt(c,i,lt())));throw dc(s,o?.callee),s}return a.value},$p=ea(Qi),ta=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??e)(a.issues.map(c=>Rt(c,i,lt())));throw dc(s,o?.callee),s}return a.value},wp=ta(Qi),ra=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ir;return i.issues.length?{success:!1,error:new(e??pc)(i.issues.map(a=>Rt(a,o,lt())))}:{success:!0,data:i.value}},Qy=ra(Qi),na=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>Rt(a,o,lt())))}:{success:!0,data:i.value}},ev=na(Qi),tv=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ea(e)(t,r,o)},rv=e=>(t,r,n)=>ea(e)(t,r,n),nv=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ta(e)(t,r,o)},ov=e=>async(t,r,n)=>ta(e)(t,r,n),iv=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ra(e)(t,r,o)},av=e=>(t,r,n)=>ra(e)(t,r,n),sv=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return na(e)(t,r,o)},cv=e=>async(t,r,n)=>na(e)(t,r,n)});var ar={};nr(ar,{base64:()=>qp,base64url:()=>mc,bigint:()=>Hp,boolean:()=>Wp,browserEmail:()=>JE,cidrv4:()=>Mp,cidrv6:()=>Dp,cuid:()=>kp,cuid2:()=>Ep,date:()=>Vp,datetime:()=>Jp,domain:()=>ZE,duration:()=>Tp,e164:()=>Lp,email:()=>Ap,emoji:()=>Op,extendedDuration:()=>UE,guid:()=>Cp,hex:()=>WE,hostname:()=>HE,html5Email:()=>LE,idnEmail:()=>KE,integer:()=>Zp,ipv4:()=>Np,ipv6:()=>jp,ksuid:()=>Ip,lowercase:()=>Xp,mac:()=>Up,md5_base64:()=>GE,md5_base64url:()=>XE,md5_hex:()=>BE,nanoid:()=>Pp,null:()=>Bp,number:()=>fc,rfc5322Email:()=>VE,sha1_base64:()=>QE,sha1_base64url:()=>eR,sha1_hex:()=>YE,sha256_base64:()=>rR,sha256_base64url:()=>nR,sha256_hex:()=>tR,sha384_base64:()=>iR,sha384_base64url:()=>aR,sha384_hex:()=>oR,sha512_base64:()=>cR,sha512_base64url:()=>uR,sha512_hex:()=>sR,string:()=>Fp,time:()=>Kp,ulid:()=>Rp,undefined:()=>Gp,unicodeEmail:()=>uv,uppercase:()=>Yp,uuid:()=>xn,uuid4:()=>ME,uuid6:()=>DE,uuid7:()=>qE,xid:()=>xp});function Op(){return new RegExp(FE,"u")}function dv(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Kp(e){return new RegExp(`^${dv(e)}$`)}function Jp(e){let t=dv({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${lv}T(?:${n})$`)}function oa(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function ia(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var kp,Ep,Rp,xp,Ip,Pp,Tp,UE,Cp,xn,ME,DE,qE,Ap,LE,VE,uv,KE,JE,FE,Np,jp,Up,Mp,Dp,qp,mc,HE,ZE,Lp,lv,Vp,Fp,Hp,Zp,fc,Wp,Bp,Gp,Xp,Yp,WE,BE,GE,XE,YE,QE,eR,tR,rR,nR,oR,iR,aR,sR,cR,uR,hc=q(()=>{de();kp=/^[cC][^\s-]{8,}$/,Ep=/^[0-9a-z]+$/,Rp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xp=/^[0-9a-vA-V]{20}$/,Ip=/^[A-Za-z0-9]{27}$/,Pp=/^[a-zA-Z0-9_-]{21}$/,Tp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,UE=/^[-+]?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)?)??$/,Cp=/^([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})$/,xn=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ME=xn(4),DE=xn(6),qE=xn(7),Ap=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,LE=/^[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])?)*$/,VE=/^(([^<>()\[\]\\.,;:\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,}))$/,uv=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,KE=uv,JE=/^[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])?)*$/,FE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Np=/^(?:(?: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])$/,jp=/^(([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}|:))$/,Up=e=>{let t=qt(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Mp=/^((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])$/,Dp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mc=/^[A-Za-z0-9_-]*$/,HE=/^(?=.{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])?)*\.?$/,ZE=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Lp=/^\+[1-9]\d{6,14}$/,lv="(?:(?:\\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])))",Vp=new RegExp(`^${lv}$`);Fp=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Hp=/^-?\d+n?$/,Zp=/^-?\d+$/,fc=/^-?\d+(?:\.\d+)?$/,Wp=/^(?:true|false)$/i,Bp=/^null$/i,Gp=/^undefined$/i,Xp=/^[^A-Z]*$/,Yp=/^[^a-z]*$/,WE=/^[0-9a-fA-F]*$/;BE=/^[0-9a-fA-F]{32}$/,GE=oa(22,"=="),XE=ia(22),YE=/^[0-9a-fA-F]{40}$/,QE=oa(27,"="),eR=ia(27),tR=/^[0-9a-fA-F]{64}$/,rR=oa(43,"="),nR=ia(43),oR=/^[0-9a-fA-F]{96}$/,iR=oa(64,""),aR=ia(64),sR=/^[0-9a-fA-F]{128}$/,cR=oa(86,"=="),uR=ia(86)});function pv(e,t,r){e.issues.length&&t.issues.push(...Ot(r,e.issues))}var Je,mv,Qp,em,fv,hv,gv,yv,vv,_v,Sv,bv,$v,aa,wv,zv,kv,Ev,Rv,xv,Iv,Pv,Tv,gc=q(()=>{yo();hc();de();Je=C("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),mv={number:"number",bigint:"bigint",object:"date"},Qp=C("$ZodCheckLessThan",(e,t)=>{Je.init(e,t);let r=mv[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?n.value<=t.value:n.value{Je.init(e,t);let r=mv[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),fv=C("$ZodCheckMultipleOf",(e,t)=>{Je.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):pp(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),hv=C("$ZodCheckNumberFormat",(e,t)=>{Je.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=yp[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=o,s.maximum=i,r&&(s.pattern=Zp)}),e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}si&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),gv=C("$ZodCheckBigIntFormat",(e,t)=>{Je.init(e,t);let[r,n]=vp[t.format];e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{let i=o.value;in&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),yv=C("$ZodCheckMaxSize",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{let o=n.value;o.size<=t.maximum||n.issues.push({origin:Xi(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vv=C("$ZodCheckMinSize",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:Xi(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),_v=C("$ZodCheckSizeEquals",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,i=o.size;if(i===t.size)return;let a=i>t.size;n.issues.push({origin:Xi(o),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Sv=C("$ZodCheckMaxLength",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{let o=n.value;if(o.length<=t.maximum)return;let a=Yi(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),bv=C("$ZodCheckMinLength",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let a=Yi(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$v=C("$ZodCheckLengthEquals",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let a=Yi(o),s=i>t.length;n.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),aa=C("$ZodCheckStringFormat",(e,t)=>{var r,n;Je.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),wv=C("$ZodCheckRegex",(e,t)=>{aa.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zv=C("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Xp),aa.init(e,t)}),kv=C("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Yp),aa.init(e,t)}),Ev=C("$ZodCheckIncludes",(e,t)=>{Je.init(e,t);let r=qt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Rv=C("$ZodCheckStartsWith",(e,t)=>{Je.init(e,t);let r=new RegExp(`^${qt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),xv=C("$ZodCheckEndsWith",(e,t)=>{Je.init(e,t);let r=new RegExp(`.*${qt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});Iv=C("$ZodCheckProperty",(e,t)=>{Je.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>pv(o,r,t.property));pv(n,r,t.property)}}),Pv=C("$ZodCheckMimeType",(e,t)=>{Je.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),Tv=C("$ZodCheckOverwrite",(e,t)=>{Je.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var yc,tm=q(()=>{yc=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(` +`).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(` +`))}}});var Av,rm=q(()=>{Av={major:4,minor:3,patch:6}});function d_(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function lR(e){if(!mc.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return d_(r)}function dR(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}function Ov(e,t,r){e.issues.length&&t.issues.push(...Ot(r,e.issues)),t.value[r]=e.value}function $c(e,t,r,n,o){if(e.issues.length){if(o&&!(r in n))return;t.issues.push(...Ot(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function x_(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=gp(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function I_(e,t,r,n,o,i){let a=[],s=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optout==="optional";for(let d in t){if(s.has(d))continue;if(u==="never"){a.push(d);continue}let m=c.run({value:t[d],issues:[]},n);m instanceof Promise?e.push(m.then(v=>$c(v,r,d,t,l))):$c(m,r,d,t,l)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function Nv(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!Kr(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>Rt(a,n,lt())))}),t)}function jv(e,t,r,n){let o=e.filter(i=>i.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>Rt(a,n,lt())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function nm(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Vr(e)&&Vr(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let a=nm(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;ns.l&&s.r).map(([s])=>s);if(i.length&&o&&e.issues.push({...o,keys:i}),Kr(e))return e;let a=nm(t.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function vc(e,t,r){e.issues.length&&t.issues.push(...Ot(r,e.issues)),t.value[r]=e.value}function Mv(e,t,r,n,o,i,a){e.issues.length&&(Gi.has(typeof n)?r.issues.push(...Ot(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map(s=>Rt(s,a,lt()))})),t.issues.length&&(Gi.has(typeof n)?r.issues.push(...Ot(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:t.issues.map(s=>Rt(s,a,lt()))})),r.value.set(e.value,t.value)}function Dv(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function qv(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}function Lv(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function Vv(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function _c(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}function Sc(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(i=>bc(e,i,t.out,r)):bc(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(i=>bc(e,i,t.in,r)):bc(e,o,t.in,r)}}function bc(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}function Kv(e){return e.value=Object.freeze(e.value),e}function Jv(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(So(o))}}var we,bo,Ve,Fv,Hv,Zv,Wv,Bv,Gv,Xv,Yv,Qv,e_,t_,r_,n_,o_,i_,a_,s_,c_,u_,l_,p_,m_,f_,h_,g_,om,y_,wc,im,v_,__,S_,b_,$_,w_,z_,k_,E_,R_,pR,P_,zc,T_,C_,A_,am,O_,N_,j_,U_,M_,D_,q_,sm,L_,V_,K_,J_,F_,H_,Z_,W_,B_,kc,G_,X_,Y_,Q_,eS,tS,cm=q(()=>{gc();yo();tm();zp();hc();de();rm();de();we=C("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Av;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,s,c)=>{let u=Kr(a),l;for(let d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(u)continue;let m=a.issues.length,v=d._zod.check(a);if(v instanceof Promise&&c?.async===!1)throw new ir;if(l||v instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await v,a.issues.length!==m&&(u||(u=Kr(a,m)))});else{if(a.issues.length===m)continue;u||(u=Kr(a,m))}}return l?l.then(()=>a):a},i=(a,s,c)=>{if(Kr(a))return a.aborted=!0,a;let u=o(s,n,c);if(u instanceof Promise){if(c.async===!1)throw new ir;return u.then(l=>e._zod.parse(l,c))}return e._zod.parse(u,c)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return u instanceof Promise?u.then(l=>i(l,a,s)):i(u,a,s)}let c=e._zod.parse(a,s);if(c instanceof Promise){if(s.async===!1)throw new ir;return c.then(u=>o(u,n,s))}return o(c,n,s)}}Ie(e,"~standard",()=>({validate:o=>{try{let i=Qy(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return ev(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),bo=C("$ZodString",(e,t)=>{we.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Fp(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Ve=C("$ZodStringFormat",(e,t)=>{aa.init(e,t),bo.init(e,t)}),Fv=C("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Cp),Ve.init(e,t)}),Hv=C("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=xn(n))}else t.pattern??(t.pattern=xn());Ve.init(e,t)}),Zv=C("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ap),Ve.init(e,t)}),Wv=C("$ZodURL",(e,t)=>{Ve.init(e,t),e._zod.check=r=>{try{let n=r.value.trim(),o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Bv=C("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Op()),Ve.init(e,t)}),Gv=C("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Pp),Ve.init(e,t)}),Xv=C("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=kp),Ve.init(e,t)}),Yv=C("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ep),Ve.init(e,t)}),Qv=C("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Rp),Ve.init(e,t)}),e_=C("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xp),Ve.init(e,t)}),t_=C("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ip),Ve.init(e,t)}),r_=C("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Jp(t)),Ve.init(e,t)}),n_=C("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Vp),Ve.init(e,t)}),o_=C("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Kp(t)),Ve.init(e,t)}),i_=C("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Tp),Ve.init(e,t)}),a_=C("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Np),Ve.init(e,t),e._zod.bag.format="ipv4"}),s_=C("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=jp),Ve.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),c_=C("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Up(t.delimiter)),Ve.init(e,t),e._zod.bag.format="mac"}),u_=C("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Mp),Ve.init(e,t)}),l_=C("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Dp),Ve.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});p_=C("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=qp),Ve.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{d_(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});m_=C("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mc),Ve.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{lR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),f_=C("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Lp),Ve.init(e,t)});h_=C("$ZodJWT",(e,t)=>{Ve.init(e,t),e._zod.check=r=>{dR(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),g_=C("$ZodCustomStringFormat",(e,t)=>{Ve.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),om=C("$ZodNumber",(e,t)=>{we.init(e,t),e._zod.pattern=e._zod.bag.pattern??fc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),y_=C("$ZodNumberFormat",(e,t)=>{hv.init(e,t),om.init(e,t)}),wc=C("$ZodBoolean",(e,t)=>{we.init(e,t),e._zod.pattern=Wp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),im=C("$ZodBigInt",(e,t)=>{we.init(e,t),e._zod.pattern=Hp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),v_=C("$ZodBigIntFormat",(e,t)=>{gv.init(e,t),im.init(e,t)}),__=C("$ZodSymbol",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),S_=C("$ZodUndefined",(e,t)=>{we.init(e,t),e._zod.pattern=Gp,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),b_=C("$ZodNull",(e,t)=>{we.init(e,t),e._zod.pattern=Bp,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),$_=C("$ZodAny",(e,t)=>{we.init(e,t),e._zod.parse=r=>r}),w_=C("$ZodUnknown",(e,t)=>{we.init(e,t),e._zod.parse=r=>r}),z_=C("$ZodNever",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),k_=C("$ZodVoid",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),E_=C("$ZodDate",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});R_=C("$ZodArray",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let a=0;aOv(u,r,a))):Ov(c,r,a)}return i.length?Promise.all(i).then(()=>r):r}});pR=C("$ZodObject",(e,t)=>{if(we.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...s};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=_o(()=>x_(t));Ie(e._zod,"propValues",()=>{let s=t.shape,c={};for(let u in s){let l=s[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let o=Rn,i=t.catchall,a;e._zod.parse=(s,c)=>{a??(a=n.value);let u=s.value;if(!o(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),s;s.value={};let l=[],d=a.shape;for(let m of a.keys){let v=d[m],g=v._zod.optout==="optional",h=v._zod.run({value:u[m],issues:[]},c);h instanceof Promise?l.push(h.then(f=>$c(f,s,m,u,g))):$c(h,s,m,u,g)}return i?I_(l,u,s,c,n.value,e):l.length?Promise.all(l).then(()=>s):s}}),P_=C("$ZodObjectJIT",(e,t)=>{pR.init(e,t);let r=e._zod.parse,n=_o(()=>x_(t)),o=m=>{let v=new yc(["shape","payload","ctx"]),g=n.value,h=_=>{let $=lc(_);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};v.write("const input = payload.value;");let f=Object.create(null),y=0;for(let _ of g.keys)f[_]=`key_${y++}`;v.write("const newResult = {};");for(let _ of g.keys){let $=f[_],k=lc(_),b=m[_]?._zod?.optout==="optional";v.write(`const ${$} = ${h(_)};`),b?v.write(` + if (${$}.issues.length) { if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } } - if (${id}.value === undefined) { + if (${$}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { - newResult[${k}] = ${id}.value; + newResult[${k}] = ${$}.value; } - `); - } else { - doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + `):v.write(` + if (${$}.issues.length) { + payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } - if (${id}.value === undefined) { + if (${$}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { - newResult[${k}] = ${id}.value; + newResult[${k}] = ${$}.value; } - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject3 = isObject; - const jit = !globalConfig.jitless; - const allowsEval2 = allowsEval; - const fastEnabled = jit && allowsEval2.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject3(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - 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); - }; - }); - $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return void 0; - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return void 0; - }); - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - 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((results2) => { - return handleUnionResults(results2, payload, inst, ctx); - }); - }; - }); - $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - 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((results2) => { - return handleExclusiveUnionResults(results2, payload, inst, ctx); - }); - }; - }); - $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - const disc = cached(() => { - const opts = def.options; - const map2 = /* @__PURE__ */ 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 (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); - } - } - return map2; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!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); - } - if (def.unionFallback) { - return _super(payload, ctx); - } - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - input, - path: [def.discriminator], - inst - }); - return payload; - }; - }); - $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(([left2, right2]) => { - return handleIntersectionResults(payload, left2, right2); - }); - } - return handleIntersectionResults(payload, left, right); - }; - }); - $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - 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 = []; - const proms = []; - const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); - const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; - if (!def.rest) { - const tooBig = input.length > items.length; - const tooSmall = input.length < optStart - 1; - if (tooBig || tooSmall) { - payload.issues.push({ - ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, - input, - inst, - origin: "array" - }); - return payload; - } - } - let i = -1; - for (const item of items) { - i++; - if (i >= input.length) { - if (i >= optStart) - continue; - } - const result = item._zod.run({ - value: input[i], - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); - } else { - handleTupleResult(result, payload, i); - } - } - if (def.rest) { - 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((result2) => handleTupleResult(result2, payload, i))); - } else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - 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) { - payload.value = {}; - const recordKeys = /* @__PURE__ */ 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); - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues(key, result2.issues)); - } - payload.value[key] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized - }); - } - } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - 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"); - } - 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") { - payload.value[key] = input[key]; - } else { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - } - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues(key, result2.issues)); - } - payload.value[keyResult.value] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; - }); - $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - 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 = /* @__PURE__ */ 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, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, 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; - }; - }); - $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - 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 = /* @__PURE__ */ 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((result2) => handleSetResult(result2, payload))); - } else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex2(o) : o.toString()).join("|")})$`); - 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; - }; - }); - $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } - const values = new Set(def.values); - inst._zod.values = values; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex2(o) : o ? escapeRegex2(o.toString()) : String(o)).join("|")})$`); - 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; - }; - }); - $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - 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((output2) => { - payload.value = output2; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; - }); - $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, payload.value)); - return handleOptionalResult(result, payload.value); - } - if (payload.value === void 0) { - return payload; - } - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { - $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === void 0) { - payload.value = def.defaultValue; - return payload; - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleDefaultResult(result2, def)); - } - return handleDefaultResult(result, def); - }; - }); - $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === void 0) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleNonOptionalResult(result2, inst)); - } - return handleNonOptionalResult(result, inst); - }; - }); - $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; - }); - $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - 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((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - } - return payload; - }; - }); - $ZodNaN = /* @__PURE__ */ $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; - }; - }); - $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => 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((right2) => handlePipeResult(right2, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left2) => handlePipeResult(left2, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; - }); - $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => 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((left2) => handleCodecAResult(left2, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right2) => handleCodecAResult(right2, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; - }); - $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => 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); - }; - }); - $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { - 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 || primitiveTypes.has(typeof part)) { - regexParts.push(escapeRegex2(`${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; - }; - }); - $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - inst._def = def; - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - return 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; - }; - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return 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; - }; - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst - }); - return payload; - } - 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; - }); - $ZodPromise = /* @__PURE__ */ $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)); - }; - }); - $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "innerType", () => def.getter()); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; - }); - $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((r2) => handleRefineResult(r2, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; - }); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js -var init_ar = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js -var init_az = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js -var init_be = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js -var init_bg = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js -var init_ca = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js -var init_cs = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js -var init_da = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js -var init_de = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js -function en_default() { - return { - localeError: error() - }; -} -var error; -var init_en = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"() { - init_util(); - 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", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN" - // All other type names omitted - they fall back to raw values via ?? operator - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - 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] ?? issue2.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue2.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue2.origin}`; - case "invalid_union": - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue2.origin}`; - default: - return `Invalid input`; - } - }; - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js -var init_eo = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js -var init_es = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js -var init_fa = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js -var init_fi = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js -var init_fr = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js -var init_fr_CA = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js -var init_he = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js -var init_hu = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js -var init_hy = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js -var init_id = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js -var init_is = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js -var init_it = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js -var init_ja = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js -var init_ka = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js -var init_km = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js -var init_kh = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"() { - init_km(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js -var init_ko = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js -var init_lt = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js -var init_mk = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js -var init_ms = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js -var init_nl = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js -var init_no = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js -var init_ota = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js -var init_ps = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js -var init_pl = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js -var init_pt = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js -var init_ru = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js -var init_sl = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js -var init_sv = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js -var init_ta = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js -var init_th = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js -var init_tr = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js -var init_uk = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js -var init_ua = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"() { - init_uk(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js -var init_ur = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js -var init_uz = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js -var init_vi = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js -var init_zh_CN = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js -var init_zh_TW = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js -var init_yo = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"() { - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js -var init_locales = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"() { - init_ar(); - init_az(); - init_be(); - init_bg(); - init_ca(); - init_cs(); - init_da(); - init_de(); - init_en(); - init_eo(); - init_es(); - init_fa(); - init_fi(); - init_fr(); - init_fr_CA(); - init_he(); - init_hu(); - init_hy(); - init_id(); - init_is(); - init_it(); - init_ja(); - init_ka(); - init_kh(); - init_km(); - init_ko(); - init_lt(); - init_mk(); - init_ms(); - init_nl(); - init_no(); - init_ota(); - init_ps(); - init_pl(); - init_pt(); - init_ru(); - init_sl(); - init_sv(); - init_ta(); - init_th(); - init_tr(); - init_ua(); - init_uk(); - init_ur(); - init_uz(); - init_vi(); - init_zh_CN(); - init_zh_TW(); - init_yo(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js -function registry() { - return new $ZodRegistry(); -} -var _a, $ZodRegistry, globalRegistry; -var init_registries = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"() { - $ZodRegistry = class { - constructor() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - } - add(schema, ..._meta) { - const meta3 = _meta[0]; - this._map.set(schema, meta3); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - this._idmap.set(meta3.id, schema); - } - return this; - } - clear() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - return this; - } - remove(schema) { - const meta3 = this._map.get(schema); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - this._idmap.delete(meta3.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - const p = schema._zod.parent; - if (p) { - const pm = { ...this.get(p) ?? {} }; - delete pm.id; - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : void 0; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } - }; - (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); - globalRegistry = globalThis.__zod_globalRegistry; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js -// @__NO_SIDE_EFFECTS__ -function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class2, params) { - return new Class2({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class2, params) { - return new Class2({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class2, params) { - return new Class2({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _emoji2(Class2, params) { - return new Class2({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class2, params) { - return new Class2({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid(Class2, params) { - return new Class2({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class2, params) { - return new Class2({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class2, params) { - return new Class2({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class2, params) { - return new Class2({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class2, params) { - return new Class2({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class2, params) { - return new Class2({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class2, params) { - return new Class2({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class2, params) { - return new Class2({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class2, params) { - return new Class2({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class2, params) { - return new Class2({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class2, params) { - return new Class2({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class2, params) { - return new Class2({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class2, params) { - return new Class2({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class2, params) { - return new Class2({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class2, params) { - return new Class2({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class2, params) { - return new Class2({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class2, params) { - return new Class2({ - type: "boolean", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class2, params) { - return new Class2({ - type: "boolean", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class2, params) { - return new Class2({ - type: "bigint", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class2, params) { - return new Class2({ - type: "bigint", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class2, params) { - return new Class2({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class2, params) { - return new Class2({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class2, params) { - return new Class2({ - type: "symbol", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _undefined2(Class2, params) { - return new Class2({ - type: "undefined", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _null2(Class2, params) { - return new Class2({ - type: "null", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class2) { - return new Class2({ - type: "any" - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class2) { - return new Class2({ - type: "unknown" - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class2, params) { - return new Class2({ - type: "never", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class2, params) { - return new Class2({ - type: "void", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class2, params) { - return new Class2({ - type: "date", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class2, params) { - return new Class2({ - type: "date", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class2, params) { - return new Class2({ - type: "nan", - ...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 /* @__PURE__ */ _gt(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return /* @__PURE__ */ _lt(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return /* @__PURE__ */ _lte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return /* @__PURE__ */ _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 $ZodCheckMaxSize({ - check: "max_size", - ...normalizeParams(params), - maximum - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new $ZodCheckMinSize({ - check: "min_size", - ...normalizeParams(params), - minimum - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new $ZodCheckSizeEquals({ - check: "size_equals", - ...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 $ZodCheckProperty({ - check: "property", - property, - schema, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new $ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx - }); -} -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); -} -// @__NO_SIDE_EFFECTS__ -function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); -} -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); -} -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); -} -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class2, element, params) { - return new Class2({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class2, params) { - return new Class2({ - type: "file", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class2, fn, _params) { - const norm = normalizeParams(_params); - norm.abort ?? (norm.abort = true); - const schema = new Class2({ - type: "custom", - check: "custom", - fn, - ...norm - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _refine(Class2, fn, _params) { - const schema = new Class2({ - type: "custom", - check: "custom", - fn, - ...normalizeParams(_params) - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn) { - const ch = /* @__PURE__ */ _check((payload) => { - payload.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload.issues.push(issue(issue2, payload.value, ch._zod.def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(issue(_issue)); - } - }; - return fn(payload.value, payload); - }); - 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 = () => { - }; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function 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 = () => { - }; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = 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 ?? $ZodCodec; - const _Boolean = Classes.Boolean ?? $ZodBoolean; - const _String = Classes.String ?? $ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec2 = 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: codec2, - continue: false - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } else { - return falsyArray[0] || "false"; - } - }), - error: params.error - }); - return codec2; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class2, format, fnOrRegex, _params = {}) { - const params = normalizeParams(_params); - const def = { - ...normalizeParams(_params), - 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 Class2(def); - return inst; -} -var init_api = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"() { - init_checks(); - init_registries(); - init_schemas(); - init_util(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js -function initializeContext(params) { - 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: /* @__PURE__ */ new Map(), - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - external: params?.external ?? void 0 - }; -} -function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a2; - const def = schema._zod.def; - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; - ctx.seen.set(schema, result); - 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) { - if (!result.ref) - result.ref = parent; - process2(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - const meta3 = ctx.metadataRegistry.get(schema); - if (meta3) - Object.assign(result.schema, meta3); - if (ctx.io === "input" && isTransforming(schema)) { - delete result.schema.examples; - delete result.schema.default; - } - if (ctx.io === "input" && result.schema._prefault) - (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault); - delete result.schema._prefault; - const _result = ctx.seen.get(schema); - return _result.schema; -} -function extractDefs(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const idToSchema = /* @__PURE__ */ 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]); - } - } - const makeURI = (entry) => { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; - const uriGenerator = ctx.external.uri ?? ((id2) => id2); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) - seen.defId = defId; - const schema2 = seen.schema; - for (const key in schema2) { - delete schema2[key]; - } - schema2.$ref = ref; - }; - 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("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); - } - } - } - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (schema === entry[0]) { - extractToDef(entry); - continue; - } - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - if (seen.cycle) { - extractToDef(entry); - continue; - } - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - continue; - } - } - } -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - if (seen.ref === null) - return; - const schema2 = seen.def ?? seen.schema; - const _cached = { ...schema2 }; - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - schema2.allOf = schema2.allOf ?? []; - schema2.allOf.push(refSchema); - } else { - Object.assign(schema2, refSchema); - } - Object.assign(schema2, _cached); - const isParentRef = zodSchema._zod.parent === ref; - if (isParentRef) { - for (const key in schema2) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema2[key]; - } - } - } - if (refSchema.$ref && refSeen.def) { - for (const key in schema2) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { - delete schema2[key]; - } - } - } - } - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema2.$ref = parentSeen.schema.$ref; - if (parentSeen.def) { - for (const key in schema2) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema2[key]; - } - } - } - } - } - ctx.override({ - zodSchema, - jsonSchema: schema2, - path: seen.path ?? [] - }); - }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - 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") { - } else { - } - 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); - } - Object.assign(result, root.def ?? root.schema); - const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; - } - } - if (ctx.external) { - } else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } else { - result.definitions = defs; - } - } - } - try { - 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: /* @__PURE__ */ 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") { - 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") { - 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; -} -var createToJSONSchemaMethod, createStandardJSONSchemaMethod; -var init_to_json_schema = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"() { - init_registries(); - createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - process2(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); - }; - createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; - const ctx2 = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - for (const entry of registry2._idmap.entries()) { - const [_, schema] = entry; - process2(schema, ctx2); - } - const schemas = {}; - const external = { - registry: registry2, - uri: params?.uri, - defs - }; - ctx2.external = external; - for (const entry of registry2._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx2, schema); - schemas[key] = finalize(ctx2, schema); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs - }; - } - return { schemas }; - } - const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} -var formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors; -var init_json_schema_processors = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"() { - init_to_json_schema(); - init_util(); - formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "" - // do not set - }; - stringProcessor = (schema, ctx, _json, _params) => { - const json2 = _json; - json2.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; - if (typeof minimum === "number") - json2.minLength = minimum; - if (typeof maximum === "number") - json2.maxLength = maximum; - if (format) { - json2.format = formatMap[format] ?? format; - if (json2.format === "") - delete json2.format; - if (format === "time") { - delete json2.format; - } - } - if (contentEncoding) - json2.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json2.pattern = regexes[0].source; - else if (regexes.length > 1) { - json2.allOf = [ - ...regexes.map((regex) => ({ - ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, - pattern: regex.source - })) - ]; - } - } - }; - numberProcessor = (schema, ctx, _json, _params) => { - const json2 = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json2.type = "integer"; - else - json2.type = "number"; - if (typeof exclusiveMinimum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json2.minimum = exclusiveMinimum; - json2.exclusiveMinimum = true; - } else { - json2.exclusiveMinimum = exclusiveMinimum; - } - } - if (typeof minimum === "number") { - json2.minimum = minimum; - if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { - if (exclusiveMinimum >= minimum) - delete json2.minimum; - else - delete json2.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json2.maximum = exclusiveMaximum; - json2.exclusiveMaximum = true; - } else { - json2.exclusiveMaximum = exclusiveMaximum; - } - } - if (typeof maximum === "number") { - json2.maximum = maximum; - if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { - if (exclusiveMaximum <= maximum) - delete json2.maximum; - else - delete json2.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json2.multipleOf = multipleOf; - }; - booleanProcessor = (_schema, _ctx, json2, _params) => { - json2.type = "boolean"; - }; - bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } - }; - symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } - }; - nullProcessor = (_schema, ctx, json2, _params) => { - if (ctx.target === "openapi-3.0") { - json2.type = "string"; - json2.nullable = true; - json2.enum = [null]; - } else { - json2.type = "null"; - } - }; - undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } - }; - voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } - }; - neverProcessor = (_schema, _ctx, json2, _params) => { - json2.not = {}; - }; - anyProcessor = (_schema, _ctx, _json, _params) => { - }; - unknownProcessor = (_schema, _ctx, _json, _params) => { - }; - dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } - }; - enumProcessor = (schema, _ctx, json2, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - if (values.every((v) => typeof v === "number")) - json2.type = "number"; - if (values.every((v) => typeof v === "string")) - json2.type = "string"; - json2.enum = values; - }; - literalProcessor = (schema, ctx, json2, _params) => { - const def = schema._zod.def; - const vals = []; - for (const val of def.values) { - if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } - } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } - } else { - vals.push(val); - } - } - if (vals.length === 0) { - } else if (vals.length === 1) { - const val = vals[0]; - json2.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json2.enum = [val]; - } else { - json2.const = val; - } - } else { - if (vals.every((v) => typeof v === "number")) - json2.type = "number"; - if (vals.every((v) => typeof v === "string")) - json2.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json2.type = "boolean"; - if (vals.every((v) => v === null)) - json2.type = "null"; - json2.enum = vals; - } - }; - nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } - }; - templateLiteralProcessor = (schema, _ctx, json2, _params) => { - const _json = json2; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; - }; - fileProcessor = (schema, _ctx, json2, _params) => { - const _json = json2; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== void 0) - file2.minLength = minimum; - if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } else { - Object.assign(_json, file2); - } - }; - successProcessor = (_schema, _ctx, json2, _params) => { - json2.type = "boolean"; - }; - customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } - }; - functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } - }; - transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } - }; - mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } - }; - setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } - }; - arrayProcessor = (schema, ctx, _json, params) => { - const json2 = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - json2.type = "array"; - json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); - }; - objectProcessor = (schema, ctx, _json, params) => { - const json2 = _json; - const def = schema._zod.def; - json2.type = "object"; - json2.properties = {}; - const shape = def.shape; - for (const key in shape) { - json2.properties[key] = process2(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key] - }); - } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; - } - })); - if (requiredKeys.size > 0) { - json2.required = Array.from(requiredKeys); - } - if (def.catchall?._zod.def.type === "never") { - json2.additionalProperties = false; - } else if (!def.catchall) { - if (ctx.io === "output") - json2.additionalProperties = false; - } else if (def.catchall) { - json2.additionalProperties = process2(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - }; - unionProcessor = (schema, ctx, json2, params) => { - const def = schema._zod.def; - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process2(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] - })); - if (isExclusive) { - json2.oneOf = options; - } else { - json2.anyOf = options; - } - }; - intersectionProcessor = (schema, ctx, json2, params) => { - const def = schema._zod.def; - const a = process2(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0] - }); - const b = process2(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] - ]; - json2.allOf = allOf; - }; - tupleProcessor = (schema, ctx, _json, params) => { - const json2 = _json; - const def = schema._zod.def; - json2.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) => process2(x, ctx, { - ...params, - path: [...params.path, prefixPath, i] - })); - const rest = def.rest ? process2(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] - }) : null; - if (ctx.target === "draft-2020-12") { - json2.prefixItems = prefixItems; - if (rest) { - json2.items = rest; - } - } else if (ctx.target === "openapi-3.0") { - json2.items = { - anyOf: prefixItems - }; - if (rest) { - json2.items.anyOf.push(rest); - } - json2.minItems = prefixItems.length; - if (!rest) { - json2.maxItems = prefixItems.length; - } - } else { - json2.items = prefixItems; - if (rest) { - json2.additionalItems = rest; - } - } - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - }; - recordProcessor = (schema, ctx, _json, params) => { - const json2 = _json; - const def = schema._zod.def; - json2.type = "object"; - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"] - }); - json2.patternProperties = {}; - for (const pattern of patterns) { - json2.patternProperties[pattern.source] = valueSchema; - } - } else { - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json2.propertyNames = process2(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"] - }); - } - json2.additionalProperties = process2(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - const keyValues = keyType._zod.values; - if (keyValues) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json2.required = validKeyValues; - } - } - }; - nullableProcessor = (schema, ctx, json2, params) => { - const def = schema._zod.def; - const inner = process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json2.nullable = true; - } else { - json2.anyOf = [inner, { type: "null" }]; - } - }; - nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - }; - defaultProcessor = (schema, ctx, json2, params) => { - const def = schema._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json2.default = JSON.parse(JSON.stringify(def.defaultValue)); - }; - prefaultProcessor = (schema, ctx, json2, params) => { - const def = schema._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io === "input") - json2._prefault = JSON.parse(JSON.stringify(def.defaultValue)); - }; - catchProcessor = (schema, ctx, json2, params) => { - const def = schema._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(void 0); - } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - json2.default = catchValue; - }; - pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; - process2(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; - }; - readonlyProcessor = (schema, ctx, json2, params) => { - const def = schema._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json2.readOnly = true; - }; - promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - }; - optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - }; - lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - process2(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; - }; - 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 - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js -var init_json_schema_generator = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"() { - init_json_schema_processors(); - init_to_json_schema(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js -var init_json_schema = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"() { - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js -var init_core2 = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"() { - init_core(); - init_parse(); - init_errors(); - init_schemas(); - init_checks(); - init_versions(); - init_util(); - init_regexes(); - init_locales(); - init_registries(); - init_doc(); - init_api(); - init_to_json_schema(); - init_json_schema_processors(); - init_json_schema_generator(); - init_json_schema(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js -var checks_exports2 = {}; -__export(checks_exports2, { - endsWith: () => _endsWith, - gt: () => _gt, - gte: () => _gte, - includes: () => _includes, - length: () => _length, - lowercase: () => _lowercase, - lt: () => _lt, - lte: () => _lte, - maxLength: () => _maxLength, - maxSize: () => _maxSize, - mime: () => _mime, - minLength: () => _minLength, - minSize: () => _minSize, - multipleOf: () => _multipleOf, - negative: () => _negative, - nonnegative: () => _nonnegative, - nonpositive: () => _nonpositive, - normalize: () => _normalize, - overwrite: () => _overwrite, - positive: () => _positive, - property: () => _property, - regex: () => _regex, - size: () => _size, - slugify: () => _slugify, - startsWith: () => _startsWith, - toLowerCase: () => _toLowerCase, - toUpperCase: () => _toUpperCase, - trim: () => _trim, - uppercase: () => _uppercase -}); -var init_checks2 = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"() { - init_core2(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -function date2(params) { - return _isoDate(ZodISODate, params); -} -function time2(params) { - return _isoTime(ZodISOTime, params); -} -function duration2(params) { - return _isoDuration(ZodISODuration, params); -} -var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration; -var init_iso = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"() { - init_core2(); - init_schemas2(); - ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); - }); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js -var initializer2, ZodError, ZodRealError; -var init_errors2 = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"() { - init_core2(); - init_core2(); - init_util(); - initializer2 = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues2) => { - inst.issues.push(...issues2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, - } - }); - }; - ZodError = $constructor("ZodError", initializer2); - ZodRealError = $constructor("ZodError", initializer2, { - Parent: Error - }); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js -var parse2, parseAsync2, safeParse2, safeParseAsync2, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync; -var init_parse2 = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"() { - init_core2(); - init_errors2(); - parse2 = /* @__PURE__ */ _parse(ZodRealError); - parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); - safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); - safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); - encode = /* @__PURE__ */ _encode(ZodRealError); - decode = /* @__PURE__ */ _decode(ZodRealError); - encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); - decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); - safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); - safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); - safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); - safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js -var schemas_exports2 = {}; -__export(schemas_exports2, { - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBase64: () => ZodBase64, - ZodBase64URL: () => ZodBase64URL, - ZodBigInt: () => ZodBigInt, - ZodBigIntFormat: () => ZodBigIntFormat, - ZodBoolean: () => ZodBoolean, - ZodCIDRv4: () => ZodCIDRv4, - ZodCIDRv6: () => ZodCIDRv6, - ZodCUID: () => ZodCUID, - ZodCUID2: () => ZodCUID2, - ZodCatch: () => ZodCatch, - ZodCodec: () => ZodCodec, - ZodCustom: () => ZodCustom, - ZodCustomStringFormat: () => ZodCustomStringFormat, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodE164: () => ZodE164, - ZodEmail: () => ZodEmail, - ZodEmoji: () => ZodEmoji, - ZodEnum: () => ZodEnum, - ZodExactOptional: () => ZodExactOptional, - ZodFile: () => ZodFile, - ZodFunction: () => ZodFunction, - ZodGUID: () => ZodGUID, - ZodIPv4: () => ZodIPv4, - ZodIPv6: () => ZodIPv6, - ZodIntersection: () => ZodIntersection, - ZodJWT: () => ZodJWT, - ZodKSUID: () => ZodKSUID, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMAC: () => ZodMAC, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNanoID: () => ZodNanoID, - ZodNever: () => ZodNever, - ZodNonOptional: () => ZodNonOptional, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodNumberFormat: () => ZodNumberFormat, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodPipe: () => ZodPipe, - ZodPrefault: () => ZodPrefault, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodStringFormat: () => ZodStringFormat, - ZodSuccess: () => ZodSuccess, - ZodSymbol: () => ZodSymbol, - ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodTransform: () => ZodTransform, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodULID: () => ZodULID, - ZodURL: () => ZodURL, - ZodUUID: () => ZodUUID, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - ZodXID: () => ZodXID, - ZodXor: () => ZodXor, - _ZodString: () => _ZodString, - _default: () => _default, - _function: () => _function, - any: () => any, - array: () => array, - base64: () => base642, - base64url: () => base64url2, - bigint: () => bigint2, - boolean: () => boolean2, - catch: () => _catch, - check: () => check, - cidrv4: () => cidrv42, - cidrv6: () => cidrv62, - codec: () => codec, - cuid: () => cuid3, - cuid2: () => cuid22, - custom: () => custom, - date: () => date3, - describe: () => describe2, - discriminatedUnion: () => discriminatedUnion, - e164: () => e1642, - email: () => email2, - emoji: () => emoji2, - enum: () => _enum, - exactOptional: () => exactOptional, - file: () => file, - float32: () => float32, - float64: () => float64, - function: () => _function, - guid: () => guid2, - hash: () => hash, - hex: () => hex2, - hostname: () => hostname2, - httpUrl: () => httpUrl, - instanceof: () => _instanceof, - int: () => int, - int32: () => int32, - int64: () => int64, - intersection: () => intersection, - ipv4: () => ipv42, - ipv6: () => ipv62, - json: () => json, - jwt: () => jwt, - keyof: () => keyof, - ksuid: () => ksuid2, - lazy: () => lazy, - literal: () => literal, - looseObject: () => looseObject, - looseRecord: () => looseRecord, - mac: () => mac2, - map: () => map, - meta: () => meta2, - nan: () => nan, - nanoid: () => nanoid2, - nativeEnum: () => nativeEnum, - never: () => never, - nonoptional: () => nonoptional, - null: () => _null3, - nullable: () => nullable, - nullish: () => nullish2, - number: () => number2, - object: () => object, - optional: () => optional, - partialRecord: () => partialRecord, - pipe: () => pipe, - prefault: () => prefault, - preprocess: () => preprocess, - promise: () => promise, - readonly: () => readonly, - record: () => record, - refine: () => refine, - set: () => set, - strictObject: () => strictObject, - string: () => string2, - stringFormat: () => stringFormat, - stringbool: () => stringbool, - success: () => success, - superRefine: () => superRefine, - symbol: () => symbol, - templateLiteral: () => templateLiteral, - transform: () => transform, - tuple: () => tuple, - uint32: () => uint32, - uint64: () => uint64, - ulid: () => ulid2, - undefined: () => _undefined3, - union: () => union, - unknown: () => unknown, - url: () => url, - uuid: () => uuid2, - uuidv4: () => uuidv4, - uuidv6: () => uuidv6, - uuidv7: () => uuidv7, - void: () => _void2, - xid: () => xid2, - xor: () => xor -}); -function string2(params) { - return _string(ZodString, params); -} -function email2(params) { - return _email(ZodEmail, params); -} -function guid2(params) { - return _guid(ZodGUID, params); -} -function uuid2(params) { - return _uuid(ZodUUID, params); -} -function uuidv4(params) { - return _uuidv4(ZodUUID, params); -} -function uuidv6(params) { - return _uuidv6(ZodUUID, params); -} -function uuidv7(params) { - return _uuidv7(ZodUUID, params); -} -function url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return _url(ZodURL, { - protocol: /^https?$/, - hostname: regexes_exports.domain, - ...util_exports.normalizeParams(params) - }); -} -function emoji2(params) { - return _emoji2(ZodEmoji, params); -} -function nanoid2(params) { - return _nanoid(ZodNanoID, params); -} -function cuid3(params) { - return _cuid(ZodCUID, params); -} -function cuid22(params) { - return _cuid2(ZodCUID2, params); -} -function ulid2(params) { - return _ulid(ZodULID, params); -} -function xid2(params) { - return _xid(ZodXID, params); -} -function ksuid2(params) { - return _ksuid(ZodKSUID, params); -} -function ipv42(params) { - return _ipv4(ZodIPv4, params); -} -function mac2(params) { - return _mac(ZodMAC, params); -} -function ipv62(params) { - return _ipv6(ZodIPv6, params); -} -function cidrv42(params) { - return _cidrv4(ZodCIDRv4, params); -} -function cidrv62(params) { - return _cidrv6(ZodCIDRv6, params); -} -function base642(params) { - return _base64(ZodBase64, params); -} -function base64url2(params) { - return _base64url(ZodBase64URL, params); -} -function e1642(params) { - return _e164(ZodE164, params); -} -function jwt(params) { - return _jwt(ZodJWT, params); -} -function stringFormat(format, fnOrRegex, _params = {}) { - return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); -} -function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); -} -function hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = regexes_exports[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return _stringFormat(ZodCustomStringFormat, format, regex, params); -} -function number2(params) { - return _number(ZodNumber, params); -} -function int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return _float32(ZodNumberFormat, params); -} -function float64(params) { - return _float64(ZodNumberFormat, params); -} -function int32(params) { - return _int32(ZodNumberFormat, params); -} -function uint32(params) { - return _uint32(ZodNumberFormat, params); -} -function boolean2(params) { - return _boolean(ZodBoolean, params); -} -function bigint2(params) { - return _bigint(ZodBigInt, params); -} -function int64(params) { - return _int64(ZodBigIntFormat, params); -} -function uint64(params) { - return _uint64(ZodBigIntFormat, params); -} -function symbol(params) { - return _symbol(ZodSymbol, params); -} -function _undefined3(params) { - return _undefined2(ZodUndefined, params); -} -function _null3(params) { - return _null2(ZodNull, params); -} -function any() { - return _any(ZodAny); -} -function unknown() { - return _unknown(ZodUnknown); -} -function never(params) { - return _never(ZodNever, params); -} -function _void2(params) { - return _void(ZodVoid, params); -} -function date3(params) { - return _date(ZodDate, params); -} -function array(element, params) { - return _array(ZodArray, element, params); -} -function keyof(schema) { - const shape = schema._zod.def.shape; - return _enum(Object.keys(shape)); -} -function object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...util_exports.normalizeParams(params) - }; - return new ZodObject(def); -} -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util_exports.normalizeParams(params) - }); -} -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...util_exports.normalizeParams(params) - }); -} -function union(options, params) { - return new ZodUnion({ - type: "union", - options, - ...util_exports.normalizeParams(params) - }); -} -function xor(options, params) { - return new ZodXor({ - type: "union", - options, - inclusive: false, - ...util_exports.normalizeParams(params) - }); -} -function discriminatedUnion(discriminator, options, params) { - return new ZodDiscriminatedUnion({ - type: "union", - options, - discriminator, - ...util_exports.normalizeParams(params) - }); -} -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left, - right - }); -} -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items, - rest, - ...util_exports.normalizeParams(params) - }); -} -function record(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = void 0; - return new ZodRecord({ - type: "record", - keyType: k, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType, - mode: "loose", - ...util_exports.normalizeParams(params) - }); -} -function map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function set(valueType, params) { - return new ZodSet({ - type: "set", - valueType, - ...util_exports.normalizeParams(params) - }); -} -function _enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...util_exports.normalizeParams(params) - }); -} -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util_exports.normalizeParams(params) - }); -} -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util_exports.normalizeParams(params) - }); -} -function file(params) { - return _file(ZodFile, params); -} -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn - }); -} -function optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType - }); -} -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType - }); -} -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType - }); -} -function nullish2(innerType) { - return optional(nullable(innerType)); -} -function _default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); - } - }); -} -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); - } - }); -} -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType, - ...util_exports.normalizeParams(params) - }); -} -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType - }); -} -function _catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); -} -function nan(params) { - return _nan(ZodNaN, params); -} -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out - // ...util.normalizeParams(params), - }); -} -function codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out, - transform: params.decode, - reverseTransform: params.encode - }); -} -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType - }); -} -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util_exports.normalizeParams(params) - }); -} -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter - }); -} -function promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType - }); -} -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), - output: params?.output ?? unknown() - }); -} -function check(fn) { - const ch = new $ZodCheck({ - check: "custom" - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return _custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -function superRefine(fn) { - return _superRefine(fn); -} -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util_exports.normalizeParams(params) - }); - inst._zod.bag.Class = cls; - 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; -} -function json(params) { - const jsonSchema = lazy(() => { - return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); - }); - return jsonSchema; -} -function preprocess(fn, schema) { - return pipe(transform(fn), schema); -} -var ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodXor, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodCodec, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodFunction, ZodCustom, describe2, meta2, stringbool; -var init_schemas2 = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"() { - init_core2(); - init_core2(); - init_json_schema_processors(); - init_to_json_schema(); - init_checks2(); - init_iso(); - init_parse2(); - ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); - inst.def = def; - inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.check = (...checks) => { - return inst.clone(util_exports.mergeDefs(def, { - checks: [ - ...def.checks ?? [], - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { - parent: true - }); - }; - inst.with = inst.check; - inst.clone = (def2, params) => clone(inst, def2, params); - inst.brand = () => inst; - inst.register = ((reg, meta3) => { - reg.add(inst, meta3); - return inst; - }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode(inst, data, params); - inst.decode = (data, params) => decode(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params); - inst.safeEncode = (data, params) => safeEncode(inst, data, params); - inst.safeDecode = (data, params) => safeDecode(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params); - inst.refine = (check3, params) => inst.check(refine(check3, params)); - inst.superRefine = (refinement) => inst.check(superRefine(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite(fn)); - inst.optional = () => optional(inst); - inst.exactOptional = () => exactOptional(inst); - inst.nullable = () => nullable(inst); - inst.nullish = () => optional(nullable(inst)); - inst.nonoptional = (params) => nonoptional(inst, params); - inst.array = () => array(inst); - inst.or = (arg) => union([inst, arg]); - inst.and = (arg) => intersection(inst, arg); - inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def2) => _default(inst, def2); - inst.prefault = (def2) => prefault(inst, def2); - inst.catch = (params) => _catch(inst, params); - inst.pipe = (target) => pipe(inst, target); - inst.readonly = () => readonly(inst); - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry.add(cl, { description }); - return cl; - }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry.get(inst); - } - const cl = inst.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }; - inst.isOptional = () => inst.safeParse(void 0).success; - inst.isNullable = () => inst.safeParse(null).success; - inst.apply = (fn) => fn(inst); - return inst; - }); - _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - inst.regex = (...args) => inst.check(_regex(...args)); - inst.includes = (...args) => inst.check(_includes(...args)); - inst.startsWith = (...args) => inst.check(_startsWith(...args)); - inst.endsWith = (...args) => inst.check(_endsWith(...args)); - inst.min = (...args) => inst.check(_minLength(...args)); - inst.max = (...args) => inst.check(_maxLength(...args)); - inst.length = (...args) => inst.check(_length(...args)); - inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); - inst.lowercase = (params) => inst.check(_lowercase(params)); - inst.uppercase = (params) => inst.check(_uppercase(params)); - inst.trim = () => inst.check(_trim()); - inst.normalize = (...args) => inst.check(_normalize(...args)); - inst.toLowerCase = () => inst.check(_toLowerCase()); - inst.toUpperCase = () => inst.check(_toUpperCase()); - inst.slugify = () => inst.check(_slugify()); - }); - ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); - }); - ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); - }); - ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { - $ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { - $ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.int = (params) => inst.check(int(params)); - inst.safe = (params) => inst.check(int(params)); - inst.positive = (params) => inst.check(_gt(0, params)); - inst.nonnegative = (params) => inst.check(_gte(0, params)); - inst.negative = (params) => inst.check(_lt(0, params)); - inst.nonpositive = (params) => inst.check(_lte(0, params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - inst.step = (value, params) => inst.check(_multipleOf(value, params)); - inst.finite = () => inst; - 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; - }); - ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); - }); - ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); - }); - ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; - }); - ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { - $ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); - }); - ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { - $ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); - }); - ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { - $ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); - }); - ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); - }); - ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); - }); - ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); - }); - ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); - }); - ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { - $ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); - }); - ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_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; - }); - ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); - inst.length = (len, params) => inst.check(_length(len, params)); - inst.unwrap = () => inst.element; - }); - ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); - inst.extend = (incoming) => { - return util_exports.extend(inst, incoming); - }; - inst.safeExtend = (incoming) => { - return util_exports.safeExtend(inst, incoming); - }; - inst.merge = (other) => util_exports.merge(inst, other); - inst.pick = (mask) => util_exports.pick(inst, mask); - inst.omit = (mask) => util_exports.omit(inst, mask); - inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); - inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); - }); - ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); - inst.options = def.options; - }); - ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - $ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); - inst.options = def.options; - }); - ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); - }); - ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); - }); - ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { - $ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); - }); - ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - }); - ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { - $ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); - }); - ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { - $ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); - }); - ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, 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: [], - ...util_exports.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: [], - ...util_exports.normalizeParams(params), - entries: newEntries - }); - }; - }); - ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, 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]; - } - }); - }); - ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { - $ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); - inst.min = (size, params) => inst.check(_minSize(size, params)); - inst.max = (size, params) => inst.check(_maxSize(size, params)); - inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); - }); - ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload.issues.push(util_exports.issue(issue2, payload.value, def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - payload.issues.push(util_exports.issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - return payload; - }); - } - payload.value = output; - return payload; - }; - }); - ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; - }); - ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { - $ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; - }); - ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { - $ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); - }); - ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); - inst.in = def.in; - inst.out = def.out; - }); - ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - $ZodCodec.init(inst, def); - }); - ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { - $ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); - }); - ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.getter(); - }); - ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { - $ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { - $ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); - }); - ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); - }); - describe2 = describe; - meta2 = meta; - stringbool = (...args) => _stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString - }, ...args); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js -var ZodIssueCode, ZodFirstPartyTypeKind; -var init_compat = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"() { - init_core2(); - init_core2(); - 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" - }; - /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { - })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js -var z; -var init_from_json_schema = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"() { - init_registries(); - init_checks2(); - init_iso(); - init_schemas2(); - z = { - ...schemas_exports2, - ...checks_exports2, - iso: iso_exports - }; - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js -var coerce_exports = {}; -__export(coerce_exports, { - bigint: () => bigint3, - boolean: () => boolean3, - date: () => date4, - number: () => number3, - string: () => string3 -}); -function string3(params) { - return _coercedString(ZodString, params); -} -function number3(params) { - return _coercedNumber(ZodNumber, params); -} -function boolean3(params) { - return _coercedBoolean(ZodBoolean, params); -} -function bigint3(params) { - return _coercedBigint(ZodBigInt, params); -} -function date4(params) { - return _coercedDate(ZodDate, params); -} -var init_coerce = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"() { - init_core2(); - init_schemas2(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js -var init_external = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"() { - init_core2(); - init_schemas2(); - init_checks2(); - init_errors2(); - init_parse2(); - init_compat(); - init_core2(); - init_en(); - init_core2(); - init_json_schema_processors(); - init_from_json_schema(); - init_locales(); - init_iso(); - init_iso(); - init_coerce(); - config(en_default()); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js -var init_classic = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js"() { - init_external(); - init_external(); - } -}); - -// ../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/index.js -var init_v4 = __esm({ - "../freya/node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/index.js"() { - init_classic(); - init_classic(); - } -}); - -// ../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs -var LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, PROTOCOL_VERSION_META_KEY, CLIENT_INFO_META_KEY, SERVER_INFO_META_KEY, CLIENT_CAPABILITIES_META_KEY, SUBSCRIPTION_ID_META_KEY, LOG_LEVEL_META_KEY, TRACEPARENT_META_KEY, TRACESTATE_META_KEY, BAGGAGE_META_KEY, JSONRPC_VERSION, PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR, JSONValueSchema, JSONObjectSchema, JSONArraySchema, ProgressTokenSchema, CursorSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultMetaObjectSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, DiscoverRequestSchema, DiscoverResultSchema, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, SubscriptionFilterSchema, SubscriptionsListenRequestParamsSchema, SubscriptionsListenRequestSchema, SubscriptionsAcknowledgedNotificationParamsSchema, SubscriptionsAcknowledgedNotificationSchema, SubscriptionsListenResultMetaSchema, SubscriptionsListenResultSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, TaskCreationParamsSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, SafeUrlSchema, OAuthProtectedResourceMetadataSchema, OAuthMetadataSchema, OpenIdProviderMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, OAuthTokensSchema, IdJagTokenExchangeResponseSchema, OAuthErrorResponseSchema, OptionalSafeUrlSchema, OAuthClientMetadataSchema, OAuthClientInformationSchema, OAuthClientInformationFullSchema, OAuthClientRegistrationErrorSchema, OAuthTokenRevocationRequestSchema; -var init_auth_CUe6YdwF = __esm({ - "../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs"() { - init_v4(); - LATEST_PROTOCOL_VERSION = "2025-11-25"; - DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; - SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-06-18", - "2025-03-26", - "2024-11-05", - "2024-10-07" - ]; - RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; - PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; - CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; - SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; - CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; - SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; - LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; - TRACEPARENT_META_KEY = "traceparent"; - TRACESTATE_META_KEY = "tracestate"; - BAGGAGE_META_KEY = "baggage"; - JSONRPC_VERSION = "2.0"; - PARSE_ERROR = -32700; - INVALID_REQUEST = -32600; - METHOD_NOT_FOUND = -32601; - INVALID_PARAMS = -32602; - INTERNAL_ERROR = -32603; - JSONValueSchema = lazy(() => union([ - string2(), - number2(), - boolean2(), - _null3(), - record(string2(), JSONValueSchema), - array(JSONValueSchema) - ])); - JSONObjectSchema = record(string2(), JSONValueSchema); - JSONArraySchema = array(JSONValueSchema); - ProgressTokenSchema = union([string2(), number2().int()]); - CursorSchema = string2(); - TaskMetadataSchema = object({ ttl: number2().optional() }); - RelatedTaskMetadataSchema = object({ taskId: string2() }); - RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() - }); - BaseRequestParamsSchema = object({ _meta: RequestMetaSchema.optional() }); - TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); - RequestSchema = object({ - method: string2(), - params: BaseRequestParamsSchema.loose().optional() - }); - NotificationsParamsSchema = object({ _meta: RequestMetaSchema.optional() }); - NotificationSchema = object({ - method: string2(), - params: NotificationsParamsSchema.loose().optional() - }); - ResultMetaObjectSchema = looseObject({ get [SERVER_INFO_META_KEY]() { - return ImplementationSchema.optional().catch(void 0); - } }); - ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); - RequestIdSchema = union([string2(), number2().int()]); - JSONRPCRequestSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape - }).strict(); - JSONRPCNotificationSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape - }).strict(); - JSONRPCResultResponseSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema - }).strict(); - JSONRPCErrorResponseSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: object({ - code: number2().int(), - message: string2(), - data: unknown().optional() - }) - }).strict(); - JSONRPCMessageSchema = union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema - ]); - JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); - EmptyResultSchema = ResultSchema.strict(); - CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: string2().optional() - }); - CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema - }); - IconSchema = object({ - src: string2(), - mimeType: string2().optional(), - sizes: array(string2()).optional(), - theme: _enum(["light", "dark"]).optional() - }); - IconsSchema = object({ icons: array(IconSchema).optional() }); - BaseMetadataSchema = object({ - name: string2(), - title: string2().optional() - }); - ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: string2(), - websiteUrl: string2().optional(), - description: string2().optional() - }); - FormElicitationCapabilitySchema = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema); - ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() - }), JSONObjectSchema.optional())); - ClientTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() - }).optional() - }); - ServerTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() - }); - ClientCapabilitiesSchema = object({ - experimental: record(string2(), JSONObjectSchema).optional(), - sampling: object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: object({ listChanged: boolean2().optional() }).optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: record(string2(), JSONObjectSchema).optional() - }); - InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: string2(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema - }); - InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema - }); - ServerCapabilitiesSchema = object({ - experimental: record(string2(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: object({ listChanged: boolean2().optional() }).optional(), - resources: object({ - subscribe: boolean2().optional(), - listChanged: boolean2().optional() - }).optional(), - tools: object({ listChanged: boolean2().optional() }).optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: record(string2(), JSONObjectSchema).optional() - }); - InitializeResultSchema = ResultSchema.extend({ - protocolVersion: string2(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: string2().optional() - }); - InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() - }); - DiscoverRequestSchema = RequestSchema.extend({ - method: literal("server/discover"), - params: BaseRequestParamsSchema.optional() - }); - DiscoverResultSchema = ResultSchema.extend({ - supportedVersions: array(string2()), - capabilities: ServerCapabilitiesSchema, - instructions: string2().optional() - }); - PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() - }); - ProgressSchema = object({ - progress: number2(), - total: optional(number2()), - message: optional(string2()) - }); - ProgressNotificationParamsSchema = object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema - }); - ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema - }); - PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); - PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); - PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); - ResourceContentsSchema = object({ - uri: string2(), - mimeType: optional(string2()), - _meta: record(string2(), unknown()).optional() - }); - TextResourceContentsSchema = ResourceContentsSchema.extend({ text: string2() }); - Base64Schema = string2().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: Base64Schema }); - RoleSchema = _enum(["user", "assistant"]); - AnnotationsSchema = object({ - audience: array(RoleSchema).optional(), - priority: number2().min(0).max(1).optional(), - lastModified: iso_exports.datetime({ offset: true }).optional() - }); - ResourceSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: string2(), - description: optional(string2()), - mimeType: optional(string2()), - size: optional(number2()), - annotations: AnnotationsSchema.optional(), - _meta: optional(looseObject({})) - }); - ResourceTemplateSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: string2(), - description: optional(string2()), - mimeType: optional(string2()), - annotations: AnnotationsSchema.optional(), - _meta: optional(looseObject({})) - }); - ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); - ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); - ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); - ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); - ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: string2() }); - ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; - ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema - }); - ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); - ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() - }); - SubscribeRequestParamsSchema = ResourceRequestParamsSchema; - SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema - }); - UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; - UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema - }); - SubscriptionFilterSchema = object({ - toolsListChanged: boolean2().optional(), - promptsListChanged: boolean2().optional(), - resourcesListChanged: boolean2().optional(), - resourceSubscriptions: array(string2()).optional() - }); - SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); - SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: literal("subscriptions/listen"), - params: SubscriptionsListenRequestParamsSchema - }); - SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); - SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/subscriptions/acknowledged"), - params: SubscriptionsAcknowledgedNotificationParamsSchema - }); - SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); - SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); - ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: string2() }); - ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema - }); - PromptArgumentSchema = object({ - name: string2(), - description: optional(string2()), - required: optional(boolean2()) - }); - PromptSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: optional(string2()), - arguments: optional(array(PromptArgumentSchema)), - _meta: optional(looseObject({})) - }); - ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); - ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); - GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: string2(), - arguments: record(string2(), string2()).optional() - }); - GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema - }); - TextContentSchema = object({ - type: literal("text"), - text: string2(), - annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() - }); - ImageContentSchema = object({ - type: literal("image"), - data: Base64Schema, - mimeType: string2(), - annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() - }); - AudioContentSchema = object({ - type: literal("audio"), - data: Base64Schema, - mimeType: string2(), - annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() - }); - ToolUseContentSchema = object({ - type: literal("tool_use"), - name: string2(), - id: string2(), - input: record(string2(), unknown()), - _meta: record(string2(), unknown()).optional() - }); - EmbeddedResourceSchema = object({ - type: literal("resource"), - resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() - }); - ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); - ContentBlockSchema = union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema - ]); - PromptMessageSchema = object({ - role: RoleSchema, - content: ContentBlockSchema - }); - GetPromptResultSchema = ResultSchema.extend({ - description: string2().optional(), - messages: array(PromptMessageSchema) - }); - PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() - }); - ToolAnnotationsSchema = object({ - title: string2().optional(), - readOnlyHint: boolean2().optional(), - destructiveHint: boolean2().optional(), - idempotentHint: boolean2().optional(), - openWorldHint: boolean2().optional() - }); - ToolExecutionSchema = object({ taskSupport: _enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - ToolSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: string2().optional(), - inputSchema: object({ - type: literal("object"), - properties: record(string2(), JSONValueSchema).optional(), - required: array(string2()).optional() - }).catchall(unknown()), - outputSchema: looseObject({ $schema: string2().optional() }).optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: record(string2(), unknown()).optional() - }); - ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); - ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); - CallToolResultSchema = ResultSchema.extend({ - content: array(ContentBlockSchema).default([]), - structuredContent: unknown().optional(), - isError: boolean2().optional() - }); - CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); - CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - name: string2(), - arguments: record(string2(), unknown()).optional() - }); - CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema - }); - ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() - }); - ListChangedOptionsBaseSchema = object({ - autoRefresh: boolean2().default(true), - debounceMs: number2().int().nonnegative().default(300) - }); - LoggingLevelSchema = _enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); - SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema - }); - LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: string2().optional(), - data: unknown() - }); - LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema - }); - ModelHintSchema = object({ name: string2().optional() }); - ModelPreferencesSchema = object({ - hints: array(ModelHintSchema).optional(), - costPriority: number2().min(0).max(1).optional(), - speedPriority: number2().min(0).max(1).optional(), - intelligencePriority: number2().min(0).max(1).optional() - }); - ToolChoiceSchema = object({ mode: _enum([ - "auto", - "required", - "none" - ]).optional() }); - ToolResultContentSchema = object({ - type: literal("tool_result"), - toolUseId: string2().describe("The unique identifier for the corresponding tool call."), - content: array(ContentBlockSchema), - structuredContent: unknown().optional(), - isError: boolean2().optional(), - _meta: record(string2(), unknown()).optional() - }); - SamplingContentSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema - ]); - SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema - ]); - SamplingMessageSchema = object({ - role: RoleSchema, - content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), - _meta: record(string2(), unknown()).optional() - }); - CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - messages: array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: string2().optional(), - includeContext: _enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: number2().optional(), - maxTokens: number2().int(), - stopSequences: array(string2()).optional(), - metadata: JSONObjectSchema.optional(), - tools: array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() - }); - CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema - }); - CreateMessageResultSchema = ResultSchema.extend({ - model: string2(), - stopReason: optional(_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(string2())), - role: RoleSchema, - content: SamplingContentSchema - }); - CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: string2(), - stopReason: optional(_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(string2())), - role: RoleSchema, - content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) - }); - BooleanSchemaSchema = object({ - type: literal("boolean"), - title: string2().optional(), - description: string2().optional(), - default: boolean2().optional() - }); - StringSchemaSchema = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - minLength: number2().optional(), - maxLength: number2().optional(), - format: _enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: string2().optional() - }); - NumberSchemaSchema = object({ - type: _enum(["number", "integer"]), - title: string2().optional(), - description: string2().optional(), - minimum: number2().optional(), - maximum: number2().optional(), - default: number2().optional() - }); - UntitledSingleSelectEnumSchemaSchema = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - default: string2().optional() - }); - TitledSingleSelectEnumSchemaSchema = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - oneOf: array(object({ - const: string2(), - title: string2() - })), - default: string2().optional() - }); - LegacyTitledEnumSchemaSchema = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - enumNames: array(string2()).optional(), - default: string2().optional() - }); - SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); - UntitledMultiSelectEnumSchemaSchema = object({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object({ - type: literal("string"), - enum: array(string2()) - }), - default: array(string2()).optional() - }); - TitledMultiSelectEnumSchemaSchema = object({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object({ anyOf: array(object({ - const: string2(), - title: string2() - })) }), - default: array(string2()).optional() - }); - MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); - EnumSchemaSchema = union([ - LegacyTitledEnumSchemaSchema, - SingleSelectEnumSchemaSchema, - MultiSelectEnumSchemaSchema - ]); - PrimitiveSchemaDefinitionSchema = union([ - EnumSchemaSchema, - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema - ]); - ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - mode: literal("form").optional(), - message: string2(), - requestedSchema: object({ - type: literal("object"), - properties: record(string2(), PrimitiveSchemaDefinitionSchema), - required: array(string2()).optional() - }).catchall(unknown()) - }); - ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - mode: literal("url"), - message: string2(), - elicitationId: string2(), - url: string2().url() - }); - ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); - ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema - }); - ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: string2() }); - ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema - }); - ElicitResultSchema = ResultSchema.extend({ - action: _enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([ - string2(), - number2(), - boolean2(), - array(string2()) - ])).optional()) - }); - ResourceTemplateReferenceSchema = object({ - type: literal("ref/resource"), - uri: string2() - }); - PromptReferenceSchema = object({ - type: literal("ref/prompt"), - name: string2() - }); - CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: object({ - name: string2(), - value: string2() - }), - context: object({ arguments: record(string2(), string2()).optional() }).optional() - }); - CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema - }); - CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: array(string2()).max(100), - total: optional(number2().int()), - hasMore: optional(boolean2()) - }) }); - RootSchema = object({ - uri: string2().startsWith("file://"), - name: string2().optional(), - _meta: record(string2(), unknown()).optional() - }); - ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() - }); - ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); - RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() - }); - TaskCreationParamsSchema = looseObject({ - ttl: number2().optional(), - pollInterval: number2().optional() - }); - TaskStatusSchema = _enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - TaskSchema = object({ - taskId: string2(), - status: TaskStatusSchema, - ttl: union([number2(), _null3()]), - createdAt: string2(), - lastUpdatedAt: string2(), - pollInterval: optional(number2()), - statusMessage: optional(string2()) - }); - CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); - TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); - TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema - }); - GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ taskId: string2() }) - }); - GetTaskResultSchema = ResultSchema.merge(TaskSchema); - GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ taskId: string2() }) - }); - GetTaskPayloadResultSchema = ResultSchema.loose(); - ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); - ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); - CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ taskId: string2() }) - }); - CancelTaskResultSchema = ResultSchema.merge(TaskSchema); - ClientRequestSchema = union([ - PingRequestSchema, - InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema - ]); - ClientNotificationSchema = union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema - ]); - ClientResultSchema = union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema - ]); - ServerRequestSchema = union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema - ]); - ServerNotificationSchema = union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema - ]); - ServerResultSchema = union([ - EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema, - SubscriptionsListenResultSchema - ]); - SafeUrlSchema = url().superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: "URL must be parseable", - fatal: true - }); - return NEVER; - } - }).refine((url2) => { - const u = new URL(url2); - return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; - }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); - OAuthProtectedResourceMetadataSchema = looseObject({ - resource: string2().url(), - authorization_servers: array(SafeUrlSchema).optional(), - jwks_uri: string2().url().optional(), - scopes_supported: array(string2()).optional(), - bearer_methods_supported: array(string2()).optional(), - resource_signing_alg_values_supported: array(string2()).optional(), - resource_name: string2().optional(), - resource_documentation: string2().optional(), - resource_policy_uri: string2().url().optional(), - resource_tos_uri: string2().url().optional(), - tls_client_certificate_bound_access_tokens: boolean2().optional(), - authorization_details_types_supported: array(string2()).optional(), - dpop_signing_alg_values_supported: array(string2()).optional(), - dpop_bound_access_tokens_required: boolean2().optional() - }); - OAuthMetadataSchema = looseObject({ - issuer: string2(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: array(string2()).optional(), - response_types_supported: array(string2()), - response_modes_supported: array(string2()).optional(), - grant_types_supported: array(string2()).optional(), - token_endpoint_auth_methods_supported: array(string2()).optional(), - token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: array(string2()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), - introspection_endpoint: string2().optional(), - introspection_endpoint_auth_methods_supported: array(string2()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), - code_challenge_methods_supported: array(string2()).optional(), - client_id_metadata_document_supported: boolean2().optional(), - authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0) - }); - OpenIdProviderMetadataSchema = looseObject({ - issuer: string2(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: array(string2()).optional(), - response_types_supported: array(string2()), - response_modes_supported: array(string2()).optional(), - grant_types_supported: array(string2()).optional(), - acr_values_supported: array(string2()).optional(), - subject_types_supported: array(string2()), - id_token_signing_alg_values_supported: array(string2()), - id_token_encryption_alg_values_supported: array(string2()).optional(), - id_token_encryption_enc_values_supported: array(string2()).optional(), - userinfo_signing_alg_values_supported: array(string2()).optional(), - userinfo_encryption_alg_values_supported: array(string2()).optional(), - userinfo_encryption_enc_values_supported: array(string2()).optional(), - request_object_signing_alg_values_supported: array(string2()).optional(), - request_object_encryption_alg_values_supported: array(string2()).optional(), - request_object_encryption_enc_values_supported: array(string2()).optional(), - token_endpoint_auth_methods_supported: array(string2()).optional(), - token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), - display_values_supported: array(string2()).optional(), - claim_types_supported: array(string2()).optional(), - claims_supported: array(string2()).optional(), - service_documentation: string2().optional(), - claims_locales_supported: array(string2()).optional(), - ui_locales_supported: array(string2()).optional(), - claims_parameter_supported: boolean2().optional(), - request_parameter_supported: boolean2().optional(), - request_uri_parameter_supported: boolean2().optional(), - require_request_uri_registration: boolean2().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: boolean2().optional(), - authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0) - }); - OpenIdProviderDiscoveryMetadataSchema = object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape - }); - OAuthTokensSchema = object({ - access_token: string2(), - id_token: string2().optional(), - token_type: string2(), - expires_in: coerce_exports.number().optional(), - scope: string2().optional(), - refresh_token: string2().optional() - }).strip(); - IdJagTokenExchangeResponseSchema = object({ - issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), - access_token: string2(), - token_type: string2().optional(), - expires_in: number2().optional(), - scope: string2().optional() - }).strip(); - OAuthErrorResponseSchema = object({ - error: string2(), - error_description: string2().optional(), - error_uri: string2().optional() - }); - OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); - OAuthClientMetadataSchema = object({ - redirect_uris: array(SafeUrlSchema), - token_endpoint_auth_method: string2().optional(), - grant_types: array(string2()).optional(), - response_types: array(string2()).optional(), - application_type: string2().optional(), - client_name: string2().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: string2().optional(), - contacts: array(string2()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: string2().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: any().optional(), - software_id: string2().optional(), - software_version: string2().optional(), - software_statement: string2().optional() - }).strip(); - OAuthClientInformationSchema = object({ - client_id: string2(), - client_secret: string2().optional(), - client_id_issued_at: number2().optional(), - client_secret_expires_at: number2().optional() - }).strip(); - OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); - OAuthClientRegistrationErrorSchema = object({ - error: string2(), - error_description: string2().optional() - }).strip(); - OAuthTokenRevocationRequestSchema = object({ - token: string2(), - token_type_hint: string2().optional() - }).strip(); - } -}); - -// ../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/internal.mjs -var init_internal = __esm({ - "../freya/node_modules/.pnpm/@modelcontextprotocol+core@2.0.0-beta.5/node_modules/@modelcontextprotocol/core/dist/internal.mjs"() { - init_auth_CUe6YdwF(); - } -}); - -// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/src-CgOncMok.mjs -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 - }); -} -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); -} -function resourceUrlFromServerUrl(url2) { - const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href); - resourceURL.hash = ""; - return resourceURL; -} -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); -} -function isModernProtocolVersion(version2) { - return version2 >= FIRST_MODERN_PROTOCOL_VERSION; -} -function legacyProtocolVersions(versions) { - return versions.filter((version2) => !isModernProtocolVersion(version2)); -} -function modernProtocolVersions(versions) { - return versions.filter((version2) => isModernProtocolVersion(version2)); -} -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) - }] - }; -} -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: [] - }; -} -function build$1() { - const JSONValueSchema$1 = lazy(() => union([ - string2(), - number2(), - boolean2(), - _null3(), - record(string2(), JSONValueSchema$1), - array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = record(string2(), JSONValueSchema$1); - const ProgressTokenSchema$1 = union([string2(), number2().int()]); - const CursorSchema$1 = string2(); - const TaskMetadataSchema$1 = object({ ttl: number2().optional() }); - const RelatedTaskMetadataSchema$1 = object({ taskId: string2() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const RequestSchema$1 = object({ - method: string2(), - params: BaseRequestParamsSchema$1.loose().optional() - }); - const NotificationsParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = object({ - method: string2(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); - const RequestIdSchema$1 = union([string2(), number2().int()]); - const EmptyResultSchema$1 = ResultSchema$1.strict(); - const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - requestId: RequestIdSchema$1.optional(), - reason: string2().optional() - }); - const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - const IconSchema$1 = object({ - src: string2(), - mimeType: string2().optional(), - sizes: array(string2()).optional(), - theme: _enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = object({ icons: array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = object({ - name: string2(), - title: string2().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: string2(), - websiteUrl: string2().optional(), - description: string2().optional() - }); - const FormElicitationCapabilitySchema2 = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema2 = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(object({ - form: FormElicitationCapabilitySchema2.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - 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() - }); - 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 = object({ - experimental: record(string2(), JSONObjectSchema$1).optional(), - sampling: object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema2.optional(), - roots: object({ listChanged: boolean2().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: record(string2(), JSONObjectSchema$1).optional() - }); - const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - protocolVersion: string2(), - capabilities: ClientCapabilitiesSchema$1, - clientInfo: ImplementationSchema$1 - }); - const InitializeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema$1 - }); - const ServerCapabilitiesSchema$1 = object({ - experimental: record(string2(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: object({ listChanged: boolean2().optional() }).optional(), - resources: object({ - subscribe: boolean2().optional(), - listChanged: boolean2().optional() - }).optional(), - tools: object({ listChanged: boolean2().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: record(string2(), JSONObjectSchema$1).optional() - }); - const InitializeResultSchema$1 = ResultSchema$1.extend({ - protocolVersion: string2(), - capabilities: ServerCapabilitiesSchema$1, - serverInfo: ImplementationSchema$1, - instructions: string2().optional() - }); - const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema$1.optional() - }); - const PingRequestSchema$1 = RequestSchema$1.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema$1.optional() - }); - const ProgressSchema$1 = object({ - progress: number2(), - total: optional(number2()), - message: optional(string2()) - }); - const ProgressNotificationParamsSchema$1 = object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - 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() }); - const ResourceContentsSchema$1 = object({ - uri: string2(), - mimeType: optional(string2()), - _meta: record(string2(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: string2() }); - const Base64Schema2 = string2().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema2 }); - const RoleSchema$1 = _enum(["user", "assistant"]); - const AnnotationsSchema$1 = object({ - audience: array(RoleSchema$1).optional(), - priority: number2().min(0).max(1).optional(), - lastModified: iso_exports.datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: string2(), - description: optional(string2()), - mimeType: optional(string2()), - size: optional(number2()), - annotations: AnnotationsSchema$1.optional(), - _meta: optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: string2(), - description: optional(string2()), - mimeType: optional(string2()), - annotations: AnnotationsSchema$1.optional(), - _meta: optional(looseObject({})) - }); - const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); - const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: array(ResourceSchema$1) }); - const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); - const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: array(ResourceTemplateSchema$1) }); - const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: string2() }); - const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema$1 - }); - const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - const SubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema$1 - }); - const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema$1 - }); - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: string2() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = object({ - name: string2(), - description: optional(string2()), - required: optional(boolean2()) - }); - const PromptSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: optional(string2()), - arguments: optional(array(PromptArgumentSchema$1)), - _meta: optional(looseObject({})) - }); - const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); - const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: array(PromptSchema$1) }); - const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - name: string2(), - arguments: record(string2(), string2()).optional() - }); - const GetPromptRequestSchema$1 = RequestSchema$1.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema$1 - }); - const TextContentSchema$1 = object({ - type: literal("text"), - text: string2(), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ImageContentSchema$1 = object({ - type: literal("image"), - data: Base64Schema2, - mimeType: string2(), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const AudioContentSchema$1 = object({ - type: literal("audio"), - data: Base64Schema2, - mimeType: string2(), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ToolUseContentSchema$1 = object({ - type: literal("tool_use"), - name: string2(), - id: string2(), - input: record(string2(), unknown()), - _meta: record(string2(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = object({ - type: literal("resource"), - resource: union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const GetPromptResultSchema$1 = ResultSchema$1.extend({ - description: string2().optional(), - messages: array(PromptMessageSchema$1) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ToolAnnotationsSchema$1 = object({ - title: string2().optional(), - readOnlyHint: boolean2().optional(), - destructiveHint: boolean2().optional(), - idempotentHint: boolean2().optional(), - openWorldHint: boolean2().optional() - }); - const ToolExecutionSchema$1 = object({ taskSupport: _enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - const ToolSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: string2().optional(), - inputSchema: object({ - type: literal("object"), - properties: record(string2(), JSONValueSchema$1).optional(), - required: array(string2()).optional() - }).catchall(unknown()), - outputSchema: object({ - type: literal("object"), - properties: record(string2(), JSONValueSchema$1).optional(), - required: array(string2()).optional() - }).catchall(unknown()).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); - const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: array(ToolSchema$1) }); - const CallToolResultSchema$1 = ResultSchema$1.extend({ - content: array(ContentBlockSchema$1), - structuredContent: record(string2(), unknown()).optional(), - isError: boolean2().optional() - }); - const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - name: string2(), - arguments: record(string2(), unknown()).optional() - }); - const CallToolRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema$1 - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const LoggingLevelSchema$1 = _enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); - const SetLevelRequestSchema$1 = RequestSchema$1.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema$1 - }); - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: string2().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ModelHintSchema$1 = object({ name: string2().optional() }); - const ModelPreferencesSchema$1 = object({ - hints: array(ModelHintSchema$1).optional(), - costPriority: number2().min(0).max(1).optional(), - speedPriority: number2().min(0).max(1).optional(), - intelligencePriority: number2().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = object({ mode: _enum([ - "auto", - "required", - "none" - ]).optional() }); - const ToolResultContentSchema$1 = object({ - type: literal("tool_result"), - toolUseId: string2().describe("The unique identifier for the corresponding tool call."), - content: array(ContentBlockSchema$1), - structuredContent: object({}).loose().optional(), - isError: boolean2().optional(), - _meta: record(string2(), unknown()).optional() - }); - const SamplingContentSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1 - ]); - const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - const SamplingMessageSchema$1 = object({ - role: RoleSchema$1, - content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]), - _meta: record(string2(), unknown()).optional() - }); - const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - messages: array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: string2().optional(), - includeContext: _enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: number2().optional(), - maxTokens: number2().int(), - stopSequences: array(string2()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - const CreateMessageResultSchema$1 = ResultSchema$1.extend({ - model: string2(), - stopReason: optional(_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(string2())), - role: RoleSchema$1, - content: SamplingContentSchema$1 - }); - const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ - model: string2(), - stopReason: optional(_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(string2())), - role: RoleSchema$1, - content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]) - }); - const BooleanSchemaSchema$1 = object({ - type: literal("boolean"), - title: string2().optional(), - description: string2().optional(), - default: boolean2().optional() - }); - const StringSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - minLength: number2().optional(), - maxLength: number2().optional(), - format: _enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: string2().optional() - }); - const NumberSchemaSchema$1 = object({ - type: _enum(["number", "integer"]), - title: string2().optional(), - description: string2().optional(), - minimum: number2().optional(), - maximum: number2().optional(), - default: number2().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - default: string2().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - oneOf: array(object({ - const: string2(), - title: string2() - })), - default: string2().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - enumNames: array(string2()).optional(), - default: string2().optional() - }); - const SingleSelectEnumSchemaSchema$1 = union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = object({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object({ - type: literal("string"), - enum: array(string2()) - }), - default: array(string2()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = object({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object({ anyOf: array(object({ - const: string2(), - title: string2() - })) }), - default: array(string2()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: string2(), - requestedSchema: object({ - type: literal("object"), - properties: record(string2(), PrimitiveSchemaDefinitionSchema$1), - required: array(string2()).optional() - }).catchall(unknown()) - }); - const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("url"), - message: string2(), - elicitationId: string2(), - url: string2().url() - }); - const ElicitRequestParamsSchema$1 = union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - const ElicitRequestSchema$1 = RequestSchema$1.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: string2() }); - const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema$1 - }); - const ElicitResultSchema$1 = ResultSchema$1.extend({ - action: _enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([ - string2(), - number2(), - boolean2(), - array(string2()) - ])).optional()) - }); - const ResourceTemplateReferenceSchema$1 = object({ - type: literal("ref/resource"), - uri: string2() - }); - const PromptReferenceSchema$1 = object({ - type: literal("ref/prompt"), - name: string2() - }); - const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - ref: union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: object({ - name: string2(), - value: string2() - }), - context: object({ arguments: record(string2(), string2()).optional() }).optional() - }); - const CompleteRequestSchema$1 = RequestSchema$1.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema$1 - }); - const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ - values: array(string2()).max(100), - total: optional(number2().int()), - hasMore: optional(boolean2()) - }) }); - const RootSchema$1 = object({ - uri: string2().startsWith("file://"), - name: string2().optional(), - _meta: record(string2(), unknown()).optional() - }); - const ListRootsRequestSchema$1 = RequestSchema$1.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema$1.optional() - }); - const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: array(RootSchema$1) }); - const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TaskCreationParamsSchema$1 = looseObject({ - ttl: number2().optional(), - pollInterval: number2().optional() - }); - const TaskStatusSchema$1 = _enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - const TaskSchema$1 = object({ - taskId: string2(), - status: TaskStatusSchema$1, - ttl: union([number2(), _null3()]), - createdAt: string2(), - lastUpdatedAt: string2(), - pollInterval: optional(number2()), - statusMessage: optional(string2()) - }); - const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); - const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); - const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema$1 - }); - const GetTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) - }); - const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); - const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) - }); - const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); - const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); - const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: array(TaskSchema$1) }); - const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) - }); - 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: 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: union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - InitializedNotificationSchema$1, - RootsListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1 - ]), - ClientResultSchema: union([ - EmptyResultSchema$1, - CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema$1, - ElicitResultSchema$1, - ListRootsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - ServerRequestSchema: union([ - PingRequestSchema$1, - CreateMessageRequestSchema$1, - ElicitRequestSchema$1, - ListRootsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ServerNotificationSchema: union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - LoggingMessageNotificationSchema$1, - ResourceUpdatedNotificationSchema$1, - ResourceListChangedNotificationSchema$1, - ToolListChangedNotificationSchema$1, - PromptListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1, - ElicitationCompleteNotificationSchema$1 - ]), - ServerResultSchema: 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}' \u2014 another result family cannot default into an empty tools/call success` - }); - return; - } - }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) - }; -} -function buildSchemas2025() { - return memo$1 ??= build$1(); -} -function isNonObjectJsonSchemaRoot(json2) { - return json2["type"] !== "object"; -} -function wrapOutputSchemaForLegacy(natural) { - const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; - if (natural["$id"] !== void 0) return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: natural }, - required: ["result"] - }; - 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 && node["$id"] !== void 0) return node; - const out = {}; - 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 (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); - return out; - }; - return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: rewriteRefs(natural, false) }, - required: ["result"] - }; -} -function registryMaps() { - if (maps$1) return maps$1; - const s3 = buildSchemas2025(); - maps$1 = { - requestSchemas: { - ping: s3.PingRequestSchema, - initialize: s3.InitializeRequestSchema, - "completion/complete": s3.CompleteRequestSchema, - "logging/setLevel": s3.SetLevelRequestSchema, - "prompts/get": s3.GetPromptRequestSchema, - "prompts/list": s3.ListPromptsRequestSchema, - "resources/list": s3.ListResourcesRequestSchema, - "resources/templates/list": s3.ListResourceTemplatesRequestSchema, - "resources/read": s3.ReadResourceRequestSchema, - "resources/subscribe": s3.SubscribeRequestSchema, - "resources/unsubscribe": s3.UnsubscribeRequestSchema, - "tools/call": s3.CallToolRequestSchema, - "tools/list": s3.ListToolsRequestSchema, - "tasks/get": s3.GetTaskRequestSchema, - "tasks/result": s3.GetTaskPayloadRequestSchema, - "tasks/list": s3.ListTasksRequestSchema, - "tasks/cancel": s3.CancelTaskRequestSchema, - "sampling/createMessage": s3.CreateMessageRequestSchema, - "elicitation/create": s3.ElicitRequestSchema, - "roots/list": s3.ListRootsRequestSchema - }, - notificationSchemas: { - "notifications/cancelled": s3.CancelledNotificationSchema, - "notifications/progress": s3.ProgressNotificationSchema, - "notifications/initialized": s3.InitializedNotificationSchema, - "notifications/roots/list_changed": s3.RootsListChangedNotificationSchema, - "notifications/tasks/status": s3.TaskStatusNotificationSchema, - "notifications/message": s3.LoggingMessageNotificationSchema, - "notifications/resources/updated": s3.ResourceUpdatedNotificationSchema, - "notifications/resources/list_changed": s3.ResourceListChangedNotificationSchema, - "notifications/tools/list_changed": s3.ToolListChangedNotificationSchema, - "notifications/prompts/list_changed": s3.PromptListChangedNotificationSchema, - "notifications/elicitation/complete": s3.ElicitationCompleteNotificationSchema - }, - resultSchemas: { - ping: s3.EmptyResultSchema, - initialize: s3.InitializeResultSchema, - "completion/complete": s3.CompleteResultSchema, - "logging/setLevel": s3.EmptyResultSchema, - "prompts/get": s3.GetPromptResultSchema, - "prompts/list": s3.ListPromptsResultSchema, - "resources/list": s3.ListResourcesResultSchema, - "resources/templates/list": s3.ListResourceTemplatesResultSchema, - "resources/read": s3.ReadResourceResultSchema, - "resources/subscribe": s3.EmptyResultSchema, - "resources/unsubscribe": s3.EmptyResultSchema, - "tools/call": s3.CallToolResultWireSchema, - "tools/list": s3.ListToolsResultSchema, - "sampling/createMessage": s3.CreateMessageResultWithToolsSchema, - "elicitation/create": s3.ElicitResultSchema, - "roots/list": s3.ListRootsResultSchema - } - }; - return maps$1; -} -function warmRegistryMaps2025() { - registryMaps(); -} -function hasRequestMethod2025(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); -} -function hasNotificationMethod2025(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); -} -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; -} -function isPlainObject$4(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -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) - }; -} -function toolNeedsLegacyWrap(t) { - return isPlainObject$4(t) && isPlainObject$4(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); -} -function toNeutralResult(value) { - return value; -} -function build() { - const JSONValueSchema$1 = lazy(() => union([ - string2(), - number2(), - boolean2(), - _null3(), - record(string2(), JSONValueSchema$1), - array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = record(string2(), JSONValueSchema$1); - const ProgressTokenSchema$1 = union([string2(), number2().int()]); - const CursorSchema$1 = string2(); - const RequestIdSchema$1 = union([string2(), number2().int()]); - const RoleSchema$1 = _enum(["user", "assistant"]); - const LoggingLevelSchema$1 = _enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - const Base64Schema2 = string2().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const TaskMetadataSchema$1 = object({ ttl: number2().optional() }); - const RelatedTaskMetadataSchema$1 = object({ taskId: string2() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const NotificationsParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = object({ - method: string2(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const IconSchema$1 = object({ - src: string2(), - mimeType: string2().optional(), - sizes: array(string2()).optional(), - theme: _enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = object({ icons: array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = object({ - name: string2(), - title: string2().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: string2(), - websiteUrl: string2().optional(), - description: string2().optional() - }); - const FormElicitationCapabilitySchema2 = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema2 = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(object({ - form: FormElicitationCapabilitySchema2.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - 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() - }); - 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 = object({ - experimental: record(string2(), JSONObjectSchema$1).optional(), - sampling: object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema2.optional(), - roots: object({ listChanged: boolean2().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: record(string2(), JSONObjectSchema$1).optional() - }); - const ServerCapabilitiesSchema$1 = object({ - experimental: record(string2(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: object({ listChanged: boolean2().optional() }).optional(), - resources: object({ - subscribe: boolean2().optional(), - listChanged: boolean2().optional() - }).optional(), - tools: object({ listChanged: boolean2().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: record(string2(), JSONObjectSchema$1).optional() - }); - const ProgressSchema$1 = object({ - progress: number2(), - total: optional(number2()), - message: optional(string2()) - }); - const ProgressNotificationParamsSchema$1 = 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: string2().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ResourceContentsSchema$1 = object({ - uri: string2(), - mimeType: optional(string2()), - _meta: record(string2(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: string2() }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema2 }); - const AnnotationsSchema$1 = object({ - audience: array(RoleSchema$1).optional(), - priority: number2().min(0).max(1).optional(), - lastModified: iso_exports.datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: string2(), - description: optional(string2()), - mimeType: optional(string2()), - size: optional(number2()), - annotations: AnnotationsSchema$1.optional(), - _meta: optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: string2(), - description: optional(string2()), - mimeType: optional(string2()), - annotations: AnnotationsSchema$1.optional(), - _meta: 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: string2() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = object({ - name: string2(), - description: optional(string2()), - required: optional(boolean2()) - }); - const PromptSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: optional(string2()), - arguments: optional(array(PromptArgumentSchema$1)), - _meta: optional(looseObject({})) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TextContentSchema$1 = object({ - type: literal("text"), - text: string2(), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ImageContentSchema$1 = object({ - type: literal("image"), - data: Base64Schema2, - mimeType: string2(), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const AudioContentSchema$1 = object({ - type: literal("audio"), - data: Base64Schema2, - mimeType: string2(), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ToolUseContentSchema$1 = object({ - type: literal("tool_use"), - name: string2(), - id: string2(), - input: record(string2(), unknown()), - _meta: record(string2(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = object({ - type: literal("resource"), - resource: union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const ToolAnnotationsSchema$1 = object({ - title: string2().optional(), - readOnlyHint: boolean2().optional(), - destructiveHint: boolean2().optional(), - idempotentHint: boolean2().optional(), - openWorldHint: boolean2().optional() - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ModelHintSchema$1 = object({ name: string2().optional() }); - const ModelPreferencesSchema$1 = object({ - hints: array(ModelHintSchema$1).optional(), - costPriority: number2().min(0).max(1).optional(), - speedPriority: number2().min(0).max(1).optional(), - intelligencePriority: number2().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = object({ mode: _enum([ - "auto", - "required", - "none" - ]).optional() }); - const BooleanSchemaSchema$1 = object({ - type: literal("boolean"), - title: string2().optional(), - description: string2().optional(), - default: boolean2().optional() - }); - const StringSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - minLength: number2().optional(), - maxLength: number2().optional(), - format: _enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: string2().optional() - }); - const NumberSchemaSchema$1 = object({ - type: _enum(["number", "integer"]), - title: string2().optional(), - description: string2().optional(), - minimum: number2().optional(), - maximum: number2().optional(), - default: number2().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - default: string2().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - oneOf: array(object({ - const: string2(), - title: string2() - })), - default: string2().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = object({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - enumNames: array(string2()).optional(), - default: string2().optional() - }); - const SingleSelectEnumSchemaSchema$1 = union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = object({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object({ - type: literal("string"), - enum: array(string2()) - }), - default: array(string2()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = object({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object({ anyOf: array(object({ - const: string2(), - title: string2() - })) }), - default: array(string2()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: string2(), - requestedSchema: object({ - type: literal("object"), - properties: record(string2(), PrimitiveSchemaDefinitionSchema$1), - required: array(string2()).optional() - }).catchall(unknown()) - }); - const ResourceTemplateReferenceSchema$1 = object({ - type: literal("ref/resource"), - uri: string2() - }); - const PromptReferenceSchema$1 = object({ - type: literal("ref/prompt"), - name: string2() - }); - const RootSchema$1 = object({ - uri: string2().startsWith("file://"), - name: string2().optional(), - _meta: record(string2(), unknown()).optional() - }); - const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; - const ClientCapabilities2026Schema = object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions - }); - const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; - const ServerCapabilities2026Schema = object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions - }); - const RequestMetaEnvelopeSchema = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - [PROTOCOL_VERSION_META_KEY]: string2(), - [CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), - [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() - }); - const ToolSchema$1 = object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: string2().optional(), - inputSchema: looseObject({ - $schema: string2().optional(), - type: literal("object") - }), - outputSchema: looseObject({ $schema: string2().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - _meta: record(string2(), unknown()).optional() - }); - const ToolResultContentSchema$1 = object({ - type: literal("tool_result"), - toolUseId: string2(), - content: array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: boolean2().optional(), - _meta: record(string2(), unknown()).optional() - }); - const SamplingMessageContentBlockSchema$1 = union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - const SamplingMessageSchema$1 = object({ - role: RoleSchema$1, - content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]), - _meta: record(string2(), unknown()).optional() - }); - const ResultTypeSchema = string2(); - const ResultMetaSchema = looseObject({ [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: array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: boolean2().optional() - }); - const ListToolsResultSchema$1 = wireResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - tools: array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - prompts: array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const GetPromptResultSchema$1 = wireResult({ - description: string2().optional(), - messages: array(PromptMessageSchema$1) - }); - const ListResourcesResultSchema$1 = wireResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - resources: array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListResourceTemplatesResultSchema$1 = wireResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - resourceTemplates: array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ReadResourceResultSchema$1 = wireResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }); - const CompleteResultSchema$1 = wireResult({ completion: object({ - values: array(string2()).max(100), - total: number2().int().optional(), - hasMore: boolean2().optional() - }).loose() }); - const CacheableResultSchema = wireResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]) - }); - const DiscoverResultSchema$1 = wireResult({ - ttlMs: number2().int().min(0).catch(0), - cacheScope: _enum(["public", "private"]).catch("private"), - supportedVersions: array(string2()), - capabilities: ServerCapabilities2026Schema, - instructions: string2().optional() - }); - const CreateMessageRequestParamsSchema$1 = object({ - messages: array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: string2().optional(), - includeContext: _enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: number2().optional(), - maxTokens: number2().int(), - stopSequences: array(string2()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - const CreateMessageRequestSchema$1 = object({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - const ListRootsRequestSchema$1 = object({ - method: literal("roots/list"), - params: object({ _meta: record(string2(), unknown()).optional() }).optional() - }); - const CreateMessageResultSchema$1 = object({ - ...SamplingMessageSchema$1.shape, - model: string2(), - stopReason: string2().optional() - }); - const ListRootsResultSchema$1 = object({ roots: array(RootSchema$1) }); - const ElicitResultSchema$1 = object({ - action: _enum([ - "accept", - "decline", - "cancel" - ]), - content: record(string2(), union([ - string2(), - number2(), - boolean2(), - array(string2()) - ])).optional() - }); - const ElicitRequestURLParamsSchema$1 = object({ - mode: literal("url"), - message: string2(), - url: string2().url() - }); - const ElicitRequestParamsSchema$1 = union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - const ElicitRequestSchema$1 = object({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - const InputRequestSchema = union([ - CreateMessageRequestSchema$1, - ListRootsRequestSchema$1, - ElicitRequestSchema$1 - ]); - const InputResponseSchema = union([ - CreateMessageResultSchema$1, - ListRootsResultSchema$1, - ElicitResultSchema$1 - ]); - const InputRequestsSchema = record(string2(), InputRequestSchema); - const InputResponsesSchema = record(string2(), InputResponseSchema); - const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: string2().optional() - }); - const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: string2().optional() - }; - const InputResponseRequestParamsSchema = object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape - }); - const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); - function wireRequest(method, paramsShape) { - return object({ - method: literal(method), - params: object({ - _meta: RequestMetaEnvelopeSchema, - ...paramsShape - }) - }); - } - function dispatchRequest(method, paramsShape) { - return object({ - method: literal(method), - params: object({ - _meta: DispatchRequestMetaSchema.optional(), - ...paramsShape - }).optional() - }); - } - const callToolParamsShape = { - name: string2(), - arguments: record(string2(), 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: string2(), - arguments: record(string2(), string2()).optional(), - ...retryParamsShape - }); - const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); - const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); - const ReadResourceRequestSchema$1 = wireRequest("resources/read", { - uri: string2(), - ...retryParamsShape - }); - const completeParamsShape = { - ref: union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: object({ - name: string2(), - value: string2() - }), - context: object({ arguments: record(string2(), string2()).optional() }).optional() - }; - const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); - const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); - const SubscriptionFilterSchema$1 = object({ - toolsListChanged: boolean2().optional(), - promptsListChanged: boolean2().optional(), - resourcesListChanged: boolean2().optional(), - resourceSubscriptions: array(string2()).optional() - }); - const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; - const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); - const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); - const SubscriptionsListenResultSchema$1 = looseObject({ - _meta: SubscriptionsListenResultMetaSchema$1, - resultType: ResultTypeSchema.default("complete") - }); - const dispatchRequestSchemas = { - "tools/call": dispatchRequest("tools/call", callToolParamsShape), - "tools/list": dispatchRequest("tools/list", paginatedParamsShape), - "prompts/get": dispatchRequest("prompts/get", { - name: string2(), - arguments: record(string2(), string2()).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: string2() }), - "completion/complete": dispatchRequest("completion/complete", completeParamsShape), - "server/discover": dispatchRequest("server/discover", {}), - "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) - }; - function liftedResult(shape) { - return looseObject({ - _meta: wireMeta, - ...shape - }); - } - const dispatchResultSchemas = { - "tools/call": liftedResult({ - content: array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: boolean2().optional() - }), - "tools/list": liftedResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - tools: array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ - description: string2().optional(), - messages: array(PromptMessageSchema$1) - }), - "prompts/list": liftedResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - prompts: array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/list": liftedResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - resources: array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/templates/list": liftedResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - resourceTemplates: array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/read": liftedResult({ - ttlMs: number2().int().min(0), - cacheScope: _enum(["public", "private"]), - contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }), - "completion/complete": liftedResult({ completion: object({ - values: array(string2()).max(100), - total: number2().int().optional(), - hasMore: boolean2().optional() - }).loose() }), - "server/discover": liftedResult({ - ttlMs: number2().int().min(0).catch(0), - cacheScope: _enum(["public", "private"]).catch("private"), - supportedVersions: array(string2()), - capabilities: ServerCapabilities2026Schema, - instructions: string2().optional() - }), - "subscriptions/listen": liftedResult({}) - }; - const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); - const SubscriptionsAcknowledgedNotificationSchema$1 = object({ - method: literal("notifications/subscriptions/acknowledged"), - params: object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema$1 - }) - }); - const CancelledNotificationParamsSchema$1 = object({ - _meta: NotificationMetaSchema.optional(), - requestId: RequestIdSchema$1, - reason: string2().optional() - }); - const CancelledNotificationSchema$1 = 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) => object({ - jsonrpc: literal("2.0"), - id: union([string2(), number2().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(union([CallToolResultSchema$1, InputRequiredResultSchema])), - ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), - ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), - GetPromptResultResponseSchema: wireResultResponse(union([GetPromptResultSchema$1, InputRequiredResultSchema])), - ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), - ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), - ReadResourceResultResponseSchema: wireResultResponse(union([ReadResourceResultSchema$1, InputRequiredResultSchema])), - CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), - DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) - }; -} -function buildSchemas2026() { - return memo ??= build(); -} -function isCacheableResultMethod(method) { - return CACHEABLE_RESULT_METHODS.includes(method); -} -function cacheHintFallbackOf(result) { - return result[RESULT_CACHE_HINT_FALLBACK]; -} -function isValidCacheTtlMs(value) { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; -} -function isValidCacheScope(value) { - return value === "public" || value === "private"; -} -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 ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); -} -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$3(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function stampServerInfoMeta(result, serverInfo) { - if (serverInfo === void 0) return result; - const meta3 = result["_meta"]; - if (meta3 === void 0) return { - ...result, - _meta: { [SERVER_INFO_META_KEY]: serverInfo } - }; - if (!isPlainObject$3(meta3)) return result; - if (meta3[SERVER_INFO_META_KEY] !== void 0) return result; - return { - ...result, - _meta: { - ...meta3, - [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; -} -function inputSchemaMaps() { - if (maps) return maps; - const s3 = buildSchemas2026(); - maps = { - request: { - "elicitation/create": object({ - method: literal("elicitation/create"), - params: s3.ElicitRequestParamsSchema - }), - "sampling/createMessage": object({ - method: literal("sampling/createMessage"), - params: s3.CreateMessageRequestParamsSchema - }), - "roots/list": object({ - method: literal("roots/list"), - params: looseObject({}).optional() - }) - }, - response: { - "elicitation/create": s3.ElicitResultSchema, - "sampling/createMessage": s3.CreateMessageResultSchema, - "roots/list": s3.ListRootsResultSchema - } - }; - return maps; -} -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; -} -function hasRequestMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -function hasNotificationMethod2026(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); -} -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; -} -function isPlainObject$2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -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) - }; -} -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$2(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { - if (!isPlainObject$2(tool) || !("execution" in tool)) return tool; - const rest = { ...tool }; - delete rest["execution"]; - return rest; - }); - const capabilities = result.capabilities; - if (isPlainObject$2(capabilities) && "tasks" in capabilities) { - const rest = { ...capabilities }; - delete rest["tasks"]; - copy().capabilities = rest; - } - return next; -} -function getWireResultSchemas() { - if (wireResultSchemasMemo) return wireResultSchemasMemo; - const s3 = buildSchemas2026(); - wireResultSchemasMemo = { - "tools/call": s3.CallToolResultSchema, - "tools/list": s3.ListToolsResultSchema, - "prompts/get": s3.GetPromptResultSchema, - "prompts/list": s3.ListPromptsResultSchema, - "resources/list": s3.ListResourcesResultSchema, - "resources/templates/list": s3.ListResourceTemplatesResultSchema, - "resources/read": s3.ReadResourceResultSchema, - "completion/complete": s3.CompleteResultSchema, - "server/discover": s3.DiscoverResultSchema - }; - return wireResultSchemasMemo; -} -function warmWireResultSchemas2026() { - getWireResultSchemas(); -} -function codecForVersion(version2) { - return version2 !== void 0 && isModernProtocolVersion(version2) ? rev2026Codec : rev2025Codec; -} -function classifiedWireEra(classification) { - if (classification.revision !== void 0) return codecForVersion(classification.revision).era; - return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; -} -function isSpecRequestMethod(method) { - return ALL_CODECS.some((codec2) => codec2.hasRequestMethod(method)); -} -function isSpecNotificationMethod(method) { - return ALL_CODECS.some((codec2) => codec2.hasNotificationMethod(method)); -} -function parseJSONRPCMessage(value) { - return JSONRPCMessageSchema.parse(value); -} -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}`); -} -function 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 - }; -} -function pathName(path) { - return path.length === 0 ? "" : path.join("."); -} -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 needsBase64(s3) { - if (s3.length === 0) return true; - if (s3.startsWith(BASE64_SENTINEL_PREFIX) && s3.endsWith(BASE64_SENTINEL_SUFFIX)) return true; - if (s3 !== s3.trim()) return true; - for (let i = 0; i < s3.length; i++) { - const c = s3.codePointAt(i); - if (c === 9 || c >= 32 && c <= 126) continue; - return true; - } - return false; -} -function utf8ToBase64(s3) { - const bytes = new TextEncoder().encode(s3); - let bin = ""; - for (const b of bytes) bin += String.fromCodePoint(b); - return btoa(bin); -} -function encodeMcpParamValue(value) { - return needsBase64(value) ? `${BASE64_SENTINEL_PREFIX}${utf8ToBase64(value)}${BASE64_SENTINEL_SUFFIX}` : value; -} -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; -} -function buildMcpParamHeaders(declarations, args) { - const out = {}; - for (const decl of declarations) { - const raw = valueAtPath(args, decl.path); - if (raw === void 0 || raw === null) continue; - const stringValue = mcpParamPrimitiveToString(raw); - if (stringValue === void 0) continue; - out[`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`] = encodeMcpParamValue(stringValue); - } - return out; -} -function parseSchema(schema, data) { - return safeParse2(schema, data); -} -function shapeKeys(schemas) { - return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); -} -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"; -} -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 - }; -} -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(issue2) { - if (!issue2.path?.length) return issue2.message; - return `${issue2.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue2.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; -} -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_exports.datetime({ - local, - offset, - precision - })))); -} -function referencePatternsForFormat(format, pattern) { - let referenceSchemas; - switch (format) { - case "email": - referenceSchemas = [email2()]; - break; - case "uri": - referenceSchemas = [url()]; - break; - case "date": - referenceSchemas = [iso_exports.date()]; - break; - case "date-time": - referenceSchemas = datetimeReferenceSchemas(pattern); - break; - } - return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); -} -function isLibraryFormatPattern(format, pattern, vendor) { - if (vendor !== "zod") return true; - return referencePatternsForFormat(format, pattern).has(pattern); -} -function isJsonObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function convertStandardElicitationSchema(schema) { - try { - return standardSchemaToJsonSchema(schema, "input"); - } catch (error2) { - const detail = error2 instanceof Error ? error2.message : String(error2); - throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); - } -} -function isAnnotationOnlyJsonSchemaKeyword(key) { - return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); -} -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; -} -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 ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); - return pruned; -} -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); - }); -} -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 ProtocolError(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 ProtocolError(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 ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); - return { - ...input, - mode: "form", - requestedSchema: parsed.data - }; -} -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 } - }; -} -function withInputRequired(schema) { - return { "~standard": { - version: 1, - vendor: "modelcontextprotocol", - validate: (value, options) => { - if (isInputRequiredResult(value)) return { value }; - return schema["~standard"].validate(value, options); - } - } }; -} -function resolveInputRequiredDriverConfig(options) { - return { - autoFulfill: options?.autoFulfill ?? DEFAULT_INPUT_REQUIRED_AUTO_FULFILL, - maxRounds: options?.maxRounds ?? DEFAULT_INPUT_REQUIRED_MAX_ROUNDS - }; -} -function buildInputRequiredRetryParams(originalParams, responses, requestState) { - const hasResponses = responses !== void 0 && Object.keys(responses).length > 0; - if (!hasResponses && requestState === void 0) return originalParams; - return { - ...originalParams, - ...hasResponses && { inputResponses: responses }, - ...requestState !== void 0 && { requestState } - }; -} -function inputRequiredRoundsExceededMessage(method, maxRounds) { - return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; -} -function sleep(ms, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason))); - return; - } - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal?.reason))); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} -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) - }; -} -async function runInputRequiredDriver(args) { - const { config: config2, method, originalParams, requestOptions, hooks, signal } = args; - const startedAt = args.flowStartedAt ?? Date.now(); - let payload = args.firstPayload; - let round = 0; - while (true) { - round += 1; - if (round > config2.maxRounds) throw new SdkError(SdkErrorCode.InputRequiredRoundsExceeded, inputRequiredRoundsExceededMessage(method, config2.maxRounds), { - rounds: config2.maxRounds, - lastResult: { - inputRequests: payload.inputRequests, - ...payload.requestState !== void 0 && { requestState: payload.requestState } - } - }); - requestOptions.onprogress?.({ - progress: round, - message: `Fulfilling input required by '${method}' (round ${round})` - }); - const entries = Object.entries(payload.inputRequests ?? {}); - let responses; - if (entries.length > 0) { - const round$1 = linkedRoundAbort(signal); - try { - const fulfilled = await Promise.all(entries.map(async ([key, entry]) => { - try { - return [key, await hooks.dispatchInputRequest(key, entry, round$1.signal)]; - } catch (error2) { - round$1.abort(error2); - throw error2; - } - })); - responses = Object.fromEntries(fulfilled); - } finally { - round$1.dispose(); - } - } else await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, signal); - const legOptions = { ...requestOptions.timeout !== void 0 && { timeout: requestOptions.timeout } }; - if (requestOptions.maxTotalTimeout !== void 0) { - const totalElapsed = Date.now() - startedAt; - const remaining = requestOptions.maxTotalTimeout - totalElapsed; - if (remaining <= 0) throw new SdkError(SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: requestOptions.maxTotalTimeout, - totalElapsed - }); - legOptions.maxTotalTimeout = remaining; - } - const result = await hooks.retry(buildInputRequiredRetryParams(originalParams, responses, payload.requestState), legOptions); - if (isInputRequiredResult(result)) { - payload = { - inputRequests: result.inputRequests ?? {}, - ...result.requestState !== void 0 && { requestState: result.requestState } - }; - continue; - } - return result; - } -} -function register(key, schema) { - const name = key.slice(0, -6); - _specTypeSchemas[name] = schema; - _isSpecType[name] = (v) => schema.safeParse(v).success; -} -function bootstrapOutboundCodec(method) { - switch (method) { - case "initialize": - case "notifications/initialized": - return codecForVersion(void 0); - case "server/discover": - return codecForVersion(MODERN_WIRE_REVISION); - default: - return; - } -} -function liftWireOnlyMaterial(message2, kind) { - const params = message2.params; - if (!isPlainObject$1(params)) return { - message: message2, - lifted: {} - }; - const meta3 = params._meta; - const envelopeKeys = isPlainObject$1(meta3) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta3) : []; - const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; - if (envelopeKeys.length === 0 && retryKeys.length === 0) return { - message: message2, - lifted: {} - }; - const lifted = {}; - const nextParams = { ...params }; - if (envelopeKeys.length > 0 && isPlainObject$1(meta3)) { - const envelope = {}; - const nextMeta = { ...meta3 }; - for (const key of envelopeKeys) { - envelope[key] = meta3[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: { - ...message2, - params: nextParams - }, - lifted - }; -} -function codecResultValidator(codec2, method) { - const probe = codec2.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 = codec2.validateResult(method, value); - if (outcome.ok) return { value: outcome.value }; - return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; - } - } }; -} -function requestStateAccessor(value) { - return () => value; -} -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; -} -function isPlainObject2(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function partitionInputResponses(inputResponses) { - const accepted = {}; - const droppedKeys = []; - if (!isPlainObject2(inputResponses)) return { - accepted, - droppedKeys - }; - for (const [key, entry] of Object.entries(inputResponses)) { - if (!isPlainObject2(entry) || "method" in entry || "result" in entry) { - droppedKeys.push(key); - continue; - } - accepted[key] = entry; - } - return { - accepted, - droppedKeys - }; -} -function relatedMessagingUnavailable(member) { - throw new SdkError(SdkErrorCode.SendFailed, `ctx.mcpReq.${member} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`); -} -function synthesizeInputRequestContext(key, method, params, signal, sessionId) { - return { - sessionId, - mcpReq: { - id: key, - method, - _meta: params?.["_meta"], - requestState: requestStateAccessor(void 0), - signal, - send: (() => relatedMessagingUnavailable("send")), - notify: () => relatedMessagingUnavailable("notify") - } - }; -} -async function dispatchInputRequest(host, codec2, key, entry, signal) { - if (!isPlainObject2(entry) || typeof entry["method"] !== "string") throw new SdkError(SdkErrorCode.InvalidResult, `Invalid input request '${key}': each inputRequests entry must be an embedded request object with a method`, { key }); - const method = entry["method"]; - if (!codec2.hasInputRequestMethod(method)) throw new SdkError(SdkErrorCode.InvalidResult, `Invalid input request '${key}': '${method}' is not an embedded request the ${codec2.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`, { - key, - method - }); - const handler = host.getRequestHandler(method); - if (handler === void 0) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Cannot fulfil input request '${key}': no handler is registered for '${method}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`, { - key, - method - }); - const params = isPlainObject2(entry["params"]) ? entry["params"] : void 0; - return await handler({ - jsonrpc: "2.0", - id: key, - method, - ...params !== void 0 && { params } - }, host.buildContext(synthesizeInputRequestContext(key, method, params, signal, host.sessionId))); -} -function buildRetryLegRequestOptions(options, legOptions) { - return { - ...options?.signal !== void 0 && { signal: options.signal }, - ...options?.onprogress !== void 0 && { onprogress: options.onprogress }, - ...options?.resetTimeoutOnProgress !== void 0 && { resetTimeoutOnProgress: options.resetTimeoutOnProgress }, - ...options?.headers !== void 0 && { headers: options.headers }, - ...legOptions.timeout !== void 0 && { timeout: legOptions.timeout }, - ...legOptions.maxTotalTimeout !== void 0 && { maxTotalTimeout: legOptions.maxTotalTimeout }, - allowInputRequired: true - }; -} -function runInputRequiredFlow(host, config2, decoded, flow) { - const { codec: codec2, request, options, flowStartedAt } = flow; - const firstPayload = { - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; - const hooks = { - dispatchInputRequest: (key, entry, signal) => dispatchInputRequest(host, codec2, key, entry, signal), - retry: (params, legOptions) => flow.retry(params, buildRetryLegRequestOptions(options, legOptions)) - }; - return runInputRequiredDriver({ - config: config2, - method: request.method, - originalParams: request.params, - firstPayload, - flowStartedAt, - signal: options?.signal, - requestOptions: { - ...options?.timeout !== void 0 && { timeout: options.timeout }, - ...options?.maxTotalTimeout !== void 0 && { maxTotalTimeout: options.maxTotalTimeout }, - ...options?.onprogress !== void 0 && { onprogress: options.onprogress } - }, - hooks - }); -} -function manualInputRequiredValue(decoded) { - return { - resultType: "input_required", - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; -} -function 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; - } -} -function isJsonContentType(header) { - if (header === "application/json") return true; - return mediaTypeEssence(header) === "application/json"; -} -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; -} -function deserializeMessage(line) { - return JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message2) { - return JSON.stringify(message2) + "\n"; -} -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 }; -} -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) return baseFetch; - return async (url2, init) => { - return baseFetch(url2, { - ...baseInit, - ...init, - headers: init?.headers ? { - ...normalizeHeaders(baseInit.headers), - ...normalizeHeaders(init.headers) - } : baseInit.headers - }); - }; -} -function preloadSchemas() { - buildSchemas2025(); - buildSchemas2026(); - warmRegistryMaps2025(); - warmInputSchemaMaps2026(); - warmWireResultSchemas2026(); -} -function fromJsonSchema(schema, validator) { - const check3 = validator.getValidator(schema); - return { "~standard": { - version: 1, - vendor: "mcp", - jsonSchema: { - input: () => schema, - output: () => schema - }, - validate: (data) => { - const result = check3(data); - return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; - } - } }; -} -var BRANDS, OAuthErrorCode, OAuthError, SdkErrorCode, SdkError, SdkHttpError, FIRST_MODERN_PROTOCOL_VERSION, SUPPORTED_MODERN_PROTOCOL_VERSIONS, TOOL_RESULT_FOREIGN_FAMILY_KEYS, memo$1, REF_REWRITE_DATA_POSITION_KEYS, REF_REWRITE_NAME_MAP_KEYS, requestMethodKeys$1, notificationMethodKeys$1, resultMethodKeys, maps$1, rev2025RequestMethods, rev2025NotificationMethods, NOT_IN_ERA$1, rev2025Codec, memo, CACHEABLE_RESULT_METHODS, RESULT_CACHE_HINT_FALLBACK, ProtocolErrorCode, ProtocolError, ResourceNotFoundError, UrlElicitationRequiredError, UnsupportedProtocolVersionError, MissingRequiredClientCapabilityError, DEFAULT_CACHE_TTL_MS, DEFAULT_CACHE_SCOPE, EXTENDED_RESULT_TYPE_METHODS, INPUT_REQUEST_METHODS_2026, maps, requestMethodKeys, notificationMethodKeys, rev2026RequestMethods, rev2026NotificationMethods, NOT_IN_ERA, REQUIRED_ENVELOPE_KEYS, rev2026Codec, wireResultSchemasMemo, MODERN_WIRE_REVISION, ALL_CODECS, schemas_exports3, isJSONRPCRequest, isJSONRPCNotification, isJSONRPCResultResponse, isJSONRPCErrorResponse, isJSONRPCResponse, isCallToolResult, isInputRequiredResult, isTaskAugmentedRequestParams, isInitializeRequest, isInitializedNotification, MCP_PARAM_HEADER_PREFIX, X_MCP_HEADER_KEY, RFC9110_TOKEN, PERMITTED_X_MCP_HEADER_TYPES, NON_REACHABLE_SUBSCHEMA_KEYWORDS, OBJECT_VALUED_SUBSCHEMA_KEYWORDS, BASE64_SENTINEL_PREFIX, BASE64_SENTINEL_SUFFIX, HEADER_MISMATCH_ERROR_CODE, INBOUND_VALIDATION_LADDER, LADDER_ERROR_HTTP_STATUS, warnedZodFallback, JSON_SCHEMA_CONVERSION_TARGET, DATETIME_FRACTION_DIGITS, ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS, ROOT_KEYS, PROPERTY_KEYS_BY_TYPE, SUPPORTED_STRING_FORMATS, inputRequired, DEFAULT_INPUT_REQUIRED_AUTO_FULFILL, DEFAULT_INPUT_REQUIRED_MAX_ROUNDS, REQUEST_STATE_ONLY_LEG_PACING_MS, SPEC_SCHEMA_KEYS, authSchemas, _specTypeSchemas, _isSpecType, specTypeSchemas, isSpecType, DEFAULT_REQUEST_TIMEOUT_MSEC, RESERVED_ENVELOPE_META_KEYS, RETRY_PARAMS_KEYS, NO_REQUEST_STATE, writeNegotiatedProtocolVersion, Protocol, require_content_type, import_content_type, STDIO_DEFAULT_MAX_BUFFER_SIZE, ReadBuffer, MAX_TEMPLATE_LENGTH, MAX_VARIABLE_LENGTH, MAX_TEMPLATE_EXPRESSIONS, MAX_REGEX_LENGTH, UriTemplate, InMemoryTransport; -var init_src_CgOncMok = __esm({ - "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/src-CgOncMok.mjs"() { - init_chunk_Br0eD_fh(); - init_internal(); - init_v4(); - BRANDS = /* @__PURE__ */ Symbol.for("mcp.sdk.errorBrands"); - OAuthErrorCode = /* @__PURE__ */ (function(OAuthErrorCode$1) { - OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; - OAuthErrorCode$1["InvalidClient"] = "invalid_client"; - OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; - OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; - OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; - OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; - OAuthErrorCode$1["AccessDenied"] = "access_denied"; - OAuthErrorCode$1["ServerError"] = "server_error"; - OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; - OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; - OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; - OAuthErrorCode$1["InvalidToken"] = "invalid_token"; - OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; - OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; - OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; - OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; - OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; - OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; - return OAuthErrorCode$1; - })({}); - OAuthError = class OAuthError2 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, message2, errorUri) { - super(message2); - 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 OAuthError2(response.error, response.error_description ?? response.error, response.error_uri); - } - }; - SdkErrorCode = /* @__PURE__ */ (function(SdkErrorCode$1) { - SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; - SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; - SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; - SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; - SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; - SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; - SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; - SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; - SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; - SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; - SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; - SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; - SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; - SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; - SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; - 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; - })({}); - 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, message2, data) { - super(message2); - this.code = code; - this.data = data; - this.name = "SdkError"; - stampErrorBrands(this, new.target); - } - }; - SdkHttpError = class extends SdkError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); - } - constructor(code, message2, data) { - super(code, message2, data); - this.name = "SdkHttpError"; - } - get status() { - return this.data.status; - } - get statusText() { - return this.data.statusText; - } - }; - FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; - SUPPORTED_MODERN_PROTOCOL_VERSIONS = [FIRST_MODERN_PROTOCOL_VERSION]; - TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ - "task", - "inputRequests", - "requestState" - ]; - REF_REWRITE_DATA_POSITION_KEYS = /* @__PURE__ */ new Set([ - "const", - "enum", - "default", - "examples" - ]); - REF_REWRITE_NAME_MAP_KEYS = /* @__PURE__ */ new Set([ - "properties", - "patternProperties", - "$defs", - "definitions", - "dependentSchemas" - ]); - 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 - }; - 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 - }; - 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 - }; - rev2025RequestMethods = Object.keys(requestMethodKeys$1); - rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); - NOT_IN_ERA$1 = { - ok: false, - reason: "not-in-era" - }; - 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 s3 = buildSchemas2025(); - return triState$1(hasTools ? s3.CreateMessageResultWithToolsSchema : s3.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$4(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 - }; - CACHEABLE_RESULT_METHODS = [ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "resources/read", - "server/discover" - ]; - RESULT_CACHE_HINT_FALLBACK = /* @__PURE__ */ Symbol("modelcontextprotocol.resultCacheHintFallback"); - 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"; - ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; - ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; - return ProtocolErrorCode$1; - })({}); - ProtocolError = class ProtocolError2 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, message2, data) { - super(message2); - 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, message2, data) { - if (code === ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message2); - } - if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) { - const errorData = data; - if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new UnsupportedProtocolVersionError({ - supported: errorData.supported, - requested: errorData.requested - }, message2); - } - if (code === ProtocolErrorCode.InvalidParams || code === ProtocolErrorCode.ResourceNotFound) { - const errorData = data; - if (typeof errorData?.uri === "string" && (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message2); - } - if (code === ProtocolErrorCode.MissingRequiredClientCapability && data) { - const errorData = data; - if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message2); - } - return new ProtocolError2(code, message2, data); - } - }; - ResourceNotFoundError = class extends ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); - } - constructor(uri, message2 = `Resource not found: ${uri}`) { - super(ProtocolErrorCode.InvalidParams, message2, { uri }); - } - /** The URI that was requested and not found. */ - get uri() { - return this.data.uri; - } - }; - UrlElicitationRequiredError = class extends ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); - } - constructor(elicitations, message2 = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(ProtocolErrorCode.UrlElicitationRequired, message2, { elicitations }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } - }; - UnsupportedProtocolVersionError = class extends ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); - } - constructor(data, message2 = `Unsupported protocol version: ${data.requested}`) { - super(ProtocolErrorCode.UnsupportedProtocolVersion, message2, data); - } - /** - * Protocol versions the receiver supports. - */ - get supported() { - return this.data.supported; - } - /** - * The protocol version that was requested. - */ - get requested() { - return this.data.requested; - } - }; - MissingRequiredClientCapabilityError = class extends ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); - } - constructor(data, message2 = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { - super(ProtocolErrorCode.MissingRequiredClientCapability, message2, 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; - } - }; - DEFAULT_CACHE_TTL_MS = 0; - DEFAULT_CACHE_SCOPE = "private"; - EXTENDED_RESULT_TYPE_METHODS = [ - "tools/call", - "prompts/get", - "resources/read" - ]; - INPUT_REQUEST_METHODS_2026 = [ - "elicitation/create", - "sampling/createMessage", - "roots/list" - ]; - 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 - }; - 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 - }; - rev2026RequestMethods = Object.keys(requestMethodKeys); - rev2026NotificationMethods = Object.keys(notificationMethodKeys); - NOT_IN_ERA = { - ok: false, - reason: "not-in-era" - }; - REQUIRED_ENVELOPE_KEYS = [PROTOCOL_VERSION_META_KEY, CLIENT_CAPABILITIES_META_KEY]; - 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 { - [PROTOCOL_VERSION_META_KEY]: material.protocolVersion, - [CLIENT_INFO_META_KEY]: material.clientInfo, - [CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, - ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } - }; - }, - validateEnvelopeMeta(meta3) { - const issues = []; - for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta3)) issues.push({ - key, - problem: "missing" - }); - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3); - if (!parsed.success) for (const issue2 of parsed.error.issues) { - const path = issue2.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: issue2.message - }); - } - return issues; - }, - projectCallToolResult: (result) => appendTextFallbackForNonObject(result), - inputRequestSchema: getInputRequestSchema2026, - decodeResult(method, raw) { - if (!isPlainObject$2(raw)) return { - kind: "invalid", - error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) - }; - const rawResultType = raw["resultType"]; - if (rawResultType === void 0) return { - kind: "invalid", - error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { - method, - violation: "missing-resultType" - }) - }; - if (typeof rawResultType !== "string") return { - kind: "invalid", - error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { - method, - resultType: rawResultType - }) - }; - if (rawResultType === "input_required") { - const rawInputRequests = raw["inputRequests"]; - const inputRequests = isPlainObject$2(rawInputRequests) ? rawInputRequests : {}; - const requestState = raw["requestState"]; - if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { - kind: "invalid", - error: new SdkError(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 SdkError(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 SdkError(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((issue2) => issue2.message).join("; ")}`; - } - }; - MODERN_WIRE_REVISION = "2026-07-28"; - ALL_CODECS = [rev2025Codec, rev2026Codec]; - schemas_exports3 = /* @__PURE__ */ __exportAll({ - AnnotationsSchema: () => AnnotationsSchema, - AudioContentSchema: () => AudioContentSchema, - BaseMetadataSchema: () => BaseMetadataSchema, - BaseRequestParamsSchema: () => BaseRequestParamsSchema, - BlobResourceContentsSchema: () => BlobResourceContentsSchema, - BooleanSchemaSchema: () => BooleanSchemaSchema, - CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, - CallToolRequestSchema: () => CallToolRequestSchema, - CallToolResultSchema: () => 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: () => InitializeRequestSchema, - InitializeResultSchema: () => InitializeResultSchema, - InitializedNotificationSchema: () => InitializedNotificationSchema, - JSONArraySchema: () => JSONArraySchema, - JSONObjectSchema: () => JSONObjectSchema, - JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, - JSONRPCMessageSchema: () => JSONRPCMessageSchema, - JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, - JSONRPCRequestSchema: () => JSONRPCRequestSchema, - JSONRPCResponseSchema: () => 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: () => 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 - }); - isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; - isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; - isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; - isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; - isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; - isCallToolResult = (value) => { - if (typeof value !== "object" || value === null || value.content === void 0) return false; - return CallToolResultSchema.safeParse(value).success; - }; - isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; - isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; - isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; - isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; - MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; - X_MCP_HEADER_KEY = "x-mcp-header"; - RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; - PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([ - "string", - "integer", - "boolean", - "number" - ]); - NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions" - ]; - OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ - "patternProperties", - "dependentSchemas", - "$defs", - "definitions" - ]); - BASE64_SENTINEL_PREFIX = "=?base64?"; - BASE64_SENTINEL_SUFFIX = "?="; - HEADER_MISMATCH_ERROR_CODE = -32020; - 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: [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, 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: [ProtocolErrorCode.InvalidParams], - conformance: ["server-stateless"], - rationale: "A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." - }, - { - rung: "method-registry", - order: 5, - evaluatedAt: "dispatch", - codes: [ProtocolErrorCode.MethodNotFound], - conformance: ["server-stateless"], - rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." - }, - { - rung: "request-params", - order: 6, - evaluatedAt: "dispatch", - codes: [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 \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted." - }, - { - rung: "client-capabilities", - order: 8, - evaluatedAt: "pre-dispatch", - codes: [ProtocolErrorCode.MissingRequiredClientCapability], - conformance: ["server-stateless"], - rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." - }, - { - rung: "param-header-validation", - order: 9, - evaluatedAt: "pre-dispatch", - codes: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-custom-header-server-validation"], - rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." - } - ]; - LADDER_ERROR_HTTP_STATUS = { - [ProtocolErrorCode.ParseError]: 400, - [ProtocolErrorCode.InvalidRequest]: 400, - [ProtocolErrorCode.MethodNotFound]: 404, - [ProtocolErrorCode.UnsupportedProtocolVersion]: 400, - [ProtocolErrorCode.MissingRequiredClientCapability]: 400, - [HEADER_MISMATCH_ERROR_CODE]: 400 - }; - warnedZodFallback = false; - JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; - DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; - ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ - "$comment", - "deprecated", - "description", - "examples", - "readOnly", - "title", - "writeOnly" - ]); - ROOT_KEYS = /* @__PURE__ */ new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); - PROPERTY_KEYS_BY_TYPE = { - string: shapeKeys([ - StringSchemaSchema, - UntitledSingleSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema, - LegacyTitledEnumSchemaSchema - ]), - number: shapeKeys([NumberSchemaSchema]), - integer: shapeKeys([NumberSchemaSchema]), - boolean: shapeKeys([BooleanSchemaSchema]), - array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) - }; - SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); - inputRequired = Object.assign(buildInputRequired, { - elicit(params) { - try { - return { - method: "elicitation/create", - params: normalizeElicitInputParams(params) - }; - } catch (error2) { - throw error2 instanceof ProtocolError ? new TypeError(error2.message, { cause: error2 }) : error2; - } - }, - elicitUrl(params) { - return { - method: "elicitation/create", - params: { - ...params, - mode: "url" - } - }; - }, - createMessage(params) { - return { - method: "sampling/createMessage", - params - }; - }, - listRoots() { - return { method: "roots/list" }; - } - }); - DEFAULT_INPUT_REQUIRED_AUTO_FULFILL = true; - DEFAULT_INPUT_REQUIRED_MAX_ROUNDS = 10; - REQUEST_STATE_ONLY_LEG_PACING_MS = 250; - 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" - ]; - authSchemas = { - IdJagTokenExchangeResponseSchema, - OAuthClientInformationFullSchema, - OAuthClientInformationSchema, - OAuthClientMetadataSchema, - OAuthClientRegistrationErrorSchema, - OAuthErrorResponseSchema, - OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema, - OAuthTokenRevocationRequestSchema, - OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema, - OpenIdProviderMetadataSchema - }; - _specTypeSchemas = {}; - _isSpecType = {}; - for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports3[key]); - for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); - specTypeSchemas = Object.freeze(_specTypeSchemas); - isSpecType = Object.freeze(_isSpecType); - DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; - RESERVED_ENVELOPE_META_KEYS = [ - PROTOCOL_VERSION_META_KEY, - CLIENT_INFO_META_KEY, - CLIENT_CAPABILITIES_META_KEY, - LOG_LEVEL_META_KEY - ]; - RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; - NO_REQUEST_STATE = requestStateAccessor(void 0); - 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, version2) => { - instance._negotiatedProtocolVersion = version2; - }; - } - _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 ?? 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(message2) { - const envelope = this._outboundMetaEnvelope(); - if (envelope === void 0) return message2; - const params = message2.params ?? {}; - return { - ...message2, - 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 SdkError(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 SdkError(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 = (error2) => { - _onerror?.(error2); - this._onerror(error2); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message2, extra) => { - _onmessage?.(message2, extra); - if (isJSONRPCResultResponse(message2) || isJSONRPCErrorResponse(message2)) this._onresponse(message2); - else if (isJSONRPCRequest(message2)) this._onrequest(message2, extra); - else if (isJSONRPCNotification(message2)) this._onnotification(message2, extra); - else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message2)}`)); - }; - 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 error2 = new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - try { - this.onclose?.(); - } finally { - for (const handler of responseHandlers.values()) handler(error2); - for (const controller of requestHandlerAbortControllers.values()) controller.abort(error2); - } - } - _onerror(error2) { - this.onerror?.(error2); - } - /** - * 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 codec2 = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec2.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec2.era}`)); - return; - } - } - if (isSpecNotificationMethod(notification.method) && !codec2.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, codec2)).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error2}`))); - } - _onrequest(rawRequest, extra) { - const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); - const codec2 = 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, message2, data) => { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code, - message: message2, - ...data !== void 0 && { data } - } - }; - capturedTransport?.send(errorResponse).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error2}`))); - }; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec2.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec2.era}`)); - const requested = extra.classification.revision ?? classified; - sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { - supported: this._supportedProtocolVersions, - requested - }); - return; - } - } - if (isSpecRequestMethod(request.method) && !codec2.hasRequestMethod(request.method)) { - sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - if (handler === void 0) { - sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const envelopeError = codec2.checkInboundEnvelope(lifted); - if (envelopeError !== void 0) { - sendErrorResponse(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 = codec2.encodeResult(request.method, result, this._outboundServerInfo()); - } catch (error2) { - this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error2}`)); - sendErrorResponse(ProtocolErrorCode.InternalError, "Internal error"); - return; - } - const response = { - result: encoded, - jsonrpc: "2.0", - id: request.id - }; - await capturedTransport?.send(response); - }, async (error2) => { - if (abortController.signal.aborted) return; - const thrownCode = Number.isSafeInteger(error2["code"]) ? error2["code"] : ProtocolErrorCode.InternalError; - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: codec2.encodeErrorCode(thrownCode), - message: error2.message ?? "Internal error", - ...error2["data"] !== void 0 && { data: error2["data"] } - } - }; - await capturedTransport?.send(errorResponse); - }).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error2}`))).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 (error2) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error2); - 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 (isJSONRPCResultResponse(response)) handler(response); - else handler(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 codec2 = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec2, request.method); - if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec2, request, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(codec2, 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(codec2, 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 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(codec2, method) { - if (isSpecRequestMethod(method) && !codec2.hasRequestMethod(method)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec2.era})`, { - method, - era: codec2.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 codec2 = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec2, request.method); - return this._requestWithSchemaViaCodec(codec2, 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(codec2, request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; - const flowStartedAt = Date.now(); - let onAbort; - let cleanupMessageId; - return new Promise((resolve, reject) => { - const earlyReject = (error2) => { - reject(error2); - }; - if (!this._transport) { - earlyReject(/* @__PURE__ */ new Error("Not connected")); - return; - } - if (this._options?.enforceStrictCapabilities === true) try { - this.assertCapabilityForMethod(request.method); - } catch (error2) { - earlyReject(error2); - return; - } - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = codec2.era === 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((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error2}`))); - else requestAbort.abort(); - reject(reason instanceof SdkError ? reason : new SdkError(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 = codec2.decodeResult(request.method, response.result); - } catch (error2) { - return reject(error2 instanceof Error ? error2 : new Error(String(error2))); - } - if (decoded.kind === "invalid") return reject(decoded.error); - if (decoded.kind === "input_required") { - if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); - const flow = { - codec: codec2, - request, - resultSchema, - options, - flowStartedAt, - retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec2, 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 SdkError(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 SdkError(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((error2) => { - this._progressHandlers.delete(messageId); - reject(error2); - }); - }).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(codec2, notification, options) { - if (!this._transport) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); - if (isSpecNotificationMethod(notification.method) && !codec2.hasNotificationMethod(notification.method)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec2.era})`, { - method: notification.method, - era: codec2.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((error2) => this._onerror(error2)); - }); - 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 ProtocolError(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 ProtocolError(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, codec2) => { - const outcome = codec2.validateNotification(method, notification); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new ProtocolError(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 ProtocolError(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); - } - }; - require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.parse = parse3; - function parse3(string4) { - if (!string4) throw new TypeError("argument string is required"); - var header = typeof string4 === "object" ? getcontenttype(string4) : string4; - 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; - } - 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; - } - function ContentType(type) { - this.parameters = /* @__PURE__ */ Object.create(null); - this.type = type; - } - })); - import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); - STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; - 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 (error2) { - if (error2 instanceof SyntaxError) continue; - throw error2; - } - } - return null; - } - clear() { - this._buffer = void 0; - } - }; - MAX_TEMPLATE_LENGTH = 1e6; - MAX_VARIABLE_LENGTH = 1e6; - MAX_TEMPLATE_EXPRESSIONS = 1e4; - MAX_REGEX_LENGTH = 1e6; - UriTemplate = class UriTemplate2 { - /** - * 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) { - UriTemplate2.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) UriTemplate2.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) { - UriTemplate2.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) UriTemplate2.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) { - UriTemplate2.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 += "$"; - UriTemplate2.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; - } - }; - InMemoryTransport = class InMemoryTransport2 { - _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 InMemoryTransport2(); - const serverTransport = new InMemoryTransport2(); - 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(message2, options) { - if (!this._otherTransport) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); - if (this._otherTransport.onmessage) this._otherTransport.onmessage(message2, { authInfo: options?.authInfo }); - else this._otherTransport._messageQueue.push({ - message: message2, - extra: { authInfo: options?.authInfo } - }); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/ajvProvider-Asx17_Co.mjs -function createDefaultAjvInstance() { - const ajv = new import__2020.Ajv2020({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - addFormats(ajv); - return ajv; -} -var require_code$1, require_scope, require_codegen, require_util, require_names, require_errors, require_boolSchema, require_rules, require_applicability, require_dataType, require_defaults, require_code, require_keyword, require_subschema, require_fast_deep_equal, require_json_schema_traverse, require_resolve, require_validate, require_validation_error, require_ref_error, require_compile, require_data, require_utils, require_schemes, require_fast_uri, require_uri, require_core$2, require_id, require_ref, require_core$1, require_limitNumber, require_multipleOf, require_ucs2length, require_limitLength, require_pattern, require_limitProperties, require_required, require_limitItems, require_equal, require_uniqueItems, require_const, require_enum, require_validation$1, require_additionalItems, require_items, require_prefixItems, require_items2020, require_contains, require_dependencies, require_propertyNames, require_additionalProperties, require_properties, require_patternProperties, require_not, require_anyOf, require_oneOf, require_allOf, require_if, require_thenElse, require_applicator$1, require_format$1, require_format, require_metadata, require_draft7, require_types, require_discriminator, require_json_schema_draft_07, require_ajv, require_dynamicAnchor, require_dynamicRef, require_recursiveAnchor, require_recursiveRef, require_dynamic, require_dependentRequired, require_dependentSchemas, require_limitContains, require_next, require_unevaluatedProperties, require_unevaluatedItems, require_unevaluated$1, require_draft2020, require_schema, require_applicator, require_unevaluated, require_content, require_core, require_format_annotation, require_meta_data, require_validation, require_json_schema_2020_12, require__2020, require_formats, require_limit, require_dist, import_ajv, import__2020, import_dist, DRAFT_2020_12_URIS, addFormats, AjvJsonSchemaValidator, Ajv; -var init_ajvProvider_Asx17_Co = __esm({ - "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/ajvProvider-Asx17_Co.mjs"() { - init_chunk_Br0eD_fh(); - 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(s3) { - super(); - if (!exports.IDENTIFIER.test(s3)) throw new Error("CodeGen: name must be a valid identifier"); - this.str = s3; - } - 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 _a2; - return (_a2 = this._str) !== null && _a2 !== void 0 ? _a2 : this._str = this._items.reduce((s3, c) => `${s3}${c}`, ""); - } - get names() { - var _a2; - return (_a2 = this._names) !== null && _a2 !== void 0 ? _a2 : 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; - })); - 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(UsedValueState2) { - UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; - UsedValueState2[UsedValueState2["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 _a2, _b; - if (((_b = (_a2 = this._parent) === null || _a2 === void 0 ? void 0 : _a2._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 _a2; - 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 = (_a2 = value.key) !== null && _a2 !== void 0 ? _a2 : 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 s3 = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s3.length; - s3[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; - })); - 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(error2) { - super(); - this.error = error2; - } - 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 If2 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 If2 ? e : e.nodes; - if (this.nodes.length) return this; - return new If2(not(cond), e instanceof If2 ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) return void 0; - return this; - } - optimizeNames(names, constants) { - var _a2; - this.else = (_a2 = this.else) === null || _a2 === void 0 ? void 0 : _a2.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 _a2, _b; - super.optimizeNodes(); - (_a2 = this.catch) === null || _a2 === void 0 || _a2.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a2, _b; - super.optimizeNames(names, constants); - (_a2 = this.catch) === null || _a2 === void 0 || _a2.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(error2) { - super(); - this.error = error2; - } - 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 error2 = this.name("e"); - this._currNode = node.catch = new Catch(error2); - catchCode(error2); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error2) { - return this._leafNode(new Throw(error2)); - } - 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})`; - } - })); - 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 hash2 = {}; - for (const item of arr) hash2[item] = true; - return hash2; - } - 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: mergeValues2, 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) : mergeValues2(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(Type2) { - Type2[Type2["Num"] = 0] = "Num"; - Type2[Type2["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; - })); - 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; - })); - 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, error2 = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error2, 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, error2 = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - addError(gen, errorObjectCode(cxt, error2, 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 }) { - 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, error2, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error2, errorPaths); - } - function errorObject(cxt, error2, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; - extraErrorProps(cxt, error2, 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: message2 }, 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 message2 == "function" ? message2(cxt) : message2]); - 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]); - } - })); - 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); - } - })); - require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - const jsonTypes = /* @__PURE__ */ 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; - })); - 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 _a2; - return schema[rule.keyword] !== void 0 || ((_a2 = rule.definition.implements) === null || _a2 === void 0 ? void 0 : _a2.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; - })); - 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(DataType2) { - DataType2[DataType2["Correct"] = 0] = "Correct"; - DataType2[DataType2["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 = /* @__PURE__ */ 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 - }; - } - })); - 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)}`); - } - })); - 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; - 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; - })); - 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 _a2; - 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((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : 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) { - 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; - })); - 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; - })); - 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; - }; - })); - 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"); - } - })); - 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 = /* @__PURE__ */ 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 = /* @__PURE__ */ 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; - })); - 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) { - 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 matches2 = RELATIVE_JSON_POINTER.exec($data); - if (!matches2) throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches2[1]; - jsonPointer = matches2[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; - })); - 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; - })); - 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; - })); - 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 _a2; - 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 = (_a2 = env.baseId) !== null && _a2 !== void 0 ? _a2 : (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 _a2; - 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 = (_a2 = root.localRefs) === null || _a2 === void 0 ? void 0 : _a2[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, s22) { - return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.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 = /* @__PURE__ */ new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a2; - if (((_a2 = parsedRef.fragment) === null || _a2 === void 0 ? void 0 : _a2[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; - } - })); - 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 - }; - })); - require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - 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); - 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; - } - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex3 = stringArrayToHexStripped(buffer); - if (hex3 !== "") address.push(hex3); - else { - output.error = true; - return false; - } - buffer.length = 0; - } - return true; - } - function getIPV6(input) { - let tokenCount = 0; - const output = { - error: false, - address: "", - zone: "" - }; - const address = []; - 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; - } - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) return { - host, - isIPV6: false - }; - const ipv63 = getIPV6(host); - if (!ipv63.error) { - let newHost = ipv63.address; - let escapedHost = ipv63.address; - if (ipv63.zone) { - newHost += "%" + ipv63.zone; - escapedHost += "%25" + ipv63.zone; - } - return { - host: newHost, - isIPV6: true, - escapedHost - }; - } else return { - host, - isIPV6: false - }; - } - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; - return ind; - } - 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(""); - } - function normalizeComponentEncoding(component, esc2) { - const func = esc2 !== 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; - } - 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 - }; - })); - 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" - ]; - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf(name) !== -1; - } - 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; - } - function httpParse(component) { - if (!component.host) component.error = component.error || "HTTP URIs must have a host."; - return component; - } - 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; - } - 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; - } - 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; - } - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches2 = urnComponent.path.match(URN_REG); - if (matches2) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches2[1].toLowerCase(); - urnComponent.nss = matches2[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; - } - 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; - } - 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; - } - 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); - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; - })); - require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - const { SCHEMES, getSchemeHandler } = require_schemes(); - function normalize(uri, options) { - if (typeof uri === "string") uri = serialize(parse3(uri, options), options); - else if (typeof uri === "object") uri = parse3(serialize(uri, options), options); - return uri; - } - function resolve(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - function resolveComponent(base, relative, options, skipNormalization) { - const target = {}; - if (!skipNormalization) { - base = parse3(serialize(base, options), options); - relative = parse3(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; - } - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse3(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(parse3(uriB, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { - ...options, - skipEscape: true - }); - return uriA.toLowerCase() === uriB.toLowerCase(); - } - 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 s3 = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s3 = removeDotSegments(s3); - if (authority === void 0 && s3[0] === "/" && s3[1] === "/") s3 = "/%2F" + s3.slice(2); - uriTokens.push(s3); - } - 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; - function parse3(uri, opts) { - const options = Object.assign({}, opts); - 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 matches2 = uri.match(URI_PARSE); - if (matches2) { - parsed.scheme = matches2[1]; - parsed.userinfo = matches2[3]; - parsed.host = matches2[4]; - parsed.port = parseInt(matches2[5], 10); - parsed.path = matches2[6] || ""; - parsed.query = matches2[7]; - parsed.fragment = matches2[8]; - if (isNaN(parsed.port)) parsed.port = matches2[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: parse3 - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; - })); - 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; - })); - require_core$2 = /* @__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 = /* @__PURE__ */ 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 _a2, _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 s3 = o.strict; - const _optz = (_a2 = o.code) === null || _a2 === void 0 ? void 0 : _a2.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 : s3) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s3) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s3) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s3) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s3) !== 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 Ajv2 = 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: meta3, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta3 && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta: meta3, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : 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, meta3) { - if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta3); - 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, meta3); - } - 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 message2 = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") this.logger.error(message2); - else throw new Error(message2); - } - 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, meta3, 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: meta3, - 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); - 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; - } - } - }; - Ajv2.ValidationError = validation_error_1.default; - Ajv2.MissingRefError = ref_error_1.default; - exports.default = Ajv2; - 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 _a2; - 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; - (_a2 = definition.implements) === null || _a2 === void 0 || _a2.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] }; - } - })); - 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; - })); - 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 _a2; - if (!it.opts.unevaluated) return; - const schEvaluated = (_a2 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a2 === void 0 ? void 0 : _a2.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; - })); - require_core$1 = /* @__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; - })); - 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; - })); - 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; - })); - 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'; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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 { - 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; - })); - require_validation$1 = /* @__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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - 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; - })); - 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; - 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; - })); - 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; - })); - 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; - })); - require_applicator$1 = /* @__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; - })); - require_format$1 = /* @__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; - })); - require_format = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const format = [require_format$1().default]; - exports.default = format; - })); - 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" - ]; - })); - require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$1(); - const validation_1 = require_validation$1(); - const applicator_1 = require_applicator$1(); - const format_1 = require_format(); - 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; - })); - require_types = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError2) { - DiscrError2["Tag"] = "tag"; - DiscrError2["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); - })); - 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: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` - }, - 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 tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag2} == "string"`, () => validateMapping(), () => cxt.error(false, { - discrError: types_1.DiscrError.Tag, - tag: tag2, - tagName - })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { - discrError: types_1.DiscrError.Mapping, - tag: tag2, - 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 _a2; - 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 = (_a2 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a2 === void 0 ? void 0 : _a2[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: required2 }) { - return Array.isArray(required2) && required2.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; - })); - 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 - }; - })); - 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$2(); - 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 Ajv2 = 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 = Ajv2; - module.exports = exports = Ajv2; - module.exports.Ajv = Ajv2; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2; - 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; - } - }); - })); - 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: meta3 } = schemaEnv.root; - const { schemaId } = self.opts; - const sch = new compile_1.SchemaEnv({ - schema, - schemaId, - root, - baseId, - localRefs, - meta: meta3 - }); - compile_1.compileSchema.call(self, sch); - return (0, ref_1.getValidate)(cxt, sch); - } - exports.default = def; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - })); - 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; - 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; - })); - 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; - })); - 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; - })); - require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$1(); - const validation_1 = require_validation$1(); - const applicator_1 = require_applicator$1(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const format_1 = require_format(); - 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; - })); - 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 - } - } - }; - })); - 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" } - } } - }; - })); - 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" } - } - }; - })); - 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" } - } - }; - })); - 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" - } - } - }; - })); - 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" } } - }; - })); - 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 - } - } - }; - })); - 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": [] - } - } - }; - })); - 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; - })); - 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$2(); - 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: meta3 } = this.opts; - if (!meta3) 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; - } - }); - })); - 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(date5, 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(year2) { - return year2 % 4 === 0 && (year2 % 100 !== 0 || year2 % 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 date5(str) { - const matches2 = DATE.exec(str); - if (!matches2) return false; - const year2 = +matches2[1]; - const month = +matches2[2]; - const day2 = +matches2[3]; - return month >= 1 && month <= 12 && day2 >= 1 && day2 <= (month === 2 && isLeapYear(year2) ? 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 time3(str) { - const matches2 = TIME.exec(str); - if (!matches2) return false; - const hr = +matches2[1]; - const min = +matches2[2]; - const sec = +matches2[3]; - const tz = matches2[4]; - const tzSign = matches2[5] === "-" ? -1 : 1; - const tzH = +(matches2[6] || 0); - const tzM = +(matches2[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, s22) { - if (!(s1 && s22)) return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).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 time3 = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date5(dateTime[0]) && time3(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_INT322 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT322 && 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; - } - } - })); - 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 error2 = { - 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: error2, - 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; - })); - 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)) { - addFormats2(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - addFormats2(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 addFormats2(ajv, list, fs, exportName) { - var _a2; - var _b; - (_a2 = (_b = ajv.opts.code).formats) !== null && _a2 !== 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; - })); - import_ajv = require_ajv(); - import__2020 = require__2020(); - import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); - DRAFT_2020_12_URIS = /* @__PURE__ */ new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); - addFormats = import_dist.default; - AjvJsonSchemaValidator = class { - _ajv; - /** True iff the constructor received a caller-supplied engine; the `$schema` check 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 a single `Ajv2020` instance with - * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call**, 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 engine — the default instance is created on first use. */ - get ajv() { - return this._ajv ??= createDefaultAjvInstance(); - } - getValidator(schema) { - if (!this._userAjv && "$schema" in schema && typeof schema.$schema === "string" && !DRAFT_2020_12_URIS.has(schema.$schema.replace(/#$/, ""))) { - const declared = schema.$schema.slice(0, 200); - throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${declared}"). The default validator supports JSON Schema 2020-12 only; pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.`); - } - const engine = this.ajv; - 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) - }; - }; - } - }; - Ajv = import_ajv.Ajv; - } -}); - -// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/shimsNode.mjs -var CORS_IS_POSSIBLE; -var init_shimsNode = __esm({ - "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/shimsNode.mjs"() { - init_ajvProvider_Asx17_Co(); - CORS_IS_POSSIBLE = false; - } -}); - -// ../freya/node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js -async function getRandomValues(size) { - return (await crypto2).getRandomValues(new Uint8Array(size)); -} -async function random(size) { - const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; - const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length; - let result = ""; - while (result.length < size) { - const randomBytes = await getRandomValues(size - result.length); - for (const randomByte of randomBytes) { - if (randomByte < evenDistCutoff) { - result += mask[randomByte % mask.length]; - } - } - } - return result; -} -async function generateVerifier(length) { - return await random(length); -} -async function generateChallenge(code_verifier) { - const buffer = await (await crypto2).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); - return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, ""); -} -async function pkceChallenge(length) { - if (!length) - length = 43; - if (length < 43 || length > 128) { - throw `Expected a length between 43 and 128. Received ${length}.`; - } - const verifier = await generateVerifier(length); - const challenge = await generateChallenge(verifier); - return { - code_verifier: verifier, - code_challenge: challenge - }; -} -var crypto2; -var init_index_node = __esm({ - "../freya/node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js"() { - crypto2 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL - globalThis.crypto ?? // Node.js >18 - import("node:crypto").then((m) => m.webcrypto); - } -}); - -// ../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js -function noop(_arg) { -} -function createParser(callbacks) { - if (typeof callbacks == "function") - throw new TypeError( - "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" - ); - const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; - let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; - function feed(newChunk) { - const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); - for (const line of complete) - parseLine(line); - incompleteLine = incomplete, isFirstChunk = false; - } - function parseLine(line) { - if (line === "") { - dispatchEvent(); - return; - } - if (line.startsWith(":")) { - onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); - return; - } - const fieldSeparatorIndex = line.indexOf(":"); - if (fieldSeparatorIndex !== -1) { - const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); - processField(field, value, line); - return; - } - processField(line, "", line); - } - function processField(field, value, line) { - switch (field) { - case "event": - eventType = value; - break; - case "data": - data = `${data}${value} -`; - break; - case "id": - id = value.includes("\0") ? void 0 : value; - break; - case "retry": - /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( - new ParseError(`Invalid \`retry\` value: "${value}"`, { - type: "invalid-retry", - value, - line - }) - ); - break; - default: - onError( - new ParseError( - `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, - { type: "unknown-field", field, value, line } - ) - ); - break; - } - } - function dispatchEvent() { - data.length > 0 && onEvent({ - id, - event: eventType || void 0, - // If the data buffer's last character is a U+000A LINE FEED (LF) character, - // then remove the last character from the data buffer. - data: data.endsWith(` -`) ? data.slice(0, -1) : data - }), id = void 0, data = "", eventType = ""; - } - function reset(options = {}) { - incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = ""; - } - return { feed, reset }; -} -function splitLines(chunk) { - const lines = []; - let incompleteLine = "", searchIndex = 0; - for (; searchIndex < chunk.length; ) { - const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` -`, searchIndex); - let lineEnd = -1; - if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) { - incompleteLine = chunk.slice(searchIndex); - break; - } else { - const line = chunk.slice(searchIndex, lineEnd); - lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === ` -` && searchIndex++; - } - } - return [lines, incompleteLine]; -} -var ParseError; -var init_dist = __esm({ - "../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js"() { - ParseError = class extends Error { - constructor(message2, options) { - super(message2), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js -function syntaxError(message2) { - const DomException = globalThis.DOMException; - return typeof DomException == "function" ? new DomException(message2, "SyntaxError") : new SyntaxError(message2); -} -function flattenError2(err) { - return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError2).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError2(err.cause)}` : err.message : `${err}`; -} -function inspectableError(err) { - return { - type: err.type, - message: err.message, - code: err.code, - defaultPrevented: err.defaultPrevented, - cancelable: err.cancelable, - timeStamp: err.timeStamp - }; -} -function getBaseURL() { - const doc = "document" in globalThis ? globalThis.document : void 0; - return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0; -} -var ErrorEvent, __typeError, __accessCheck, __privateGet, __privateAdd, __privateSet, __privateMethod, _readyState, _url2, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect, EventSource; -var init_dist2 = __esm({ - "../freya/node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"() { - init_dist(); - ErrorEvent = class extends Event { - /** - * Constructs a new `ErrorEvent` instance. This is typically not called directly, - * but rather emitted by the `EventSource` object when an error occurs. - * - * @param type - The type of the event (should be "error") - * @param errorEventInitDict - Optional properties to include in the error event - */ - constructor(type, errorEventInitDict) { - var _a2, _b; - super(type), this.code = (_a2 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a2 : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0; - } - /** - * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance, - * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, - * we explicitly include the properties in the `inspect` method. - * - * This is automatically called by Node.js when you `console.log` an instance of this class. - * - * @param _depth - The current depth - * @param options - The options passed to `util.inspect` - * @param inspect - The inspect function to use (prevents having to import it from `util`) - * @returns A string representation of the error - */ - [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) { - return inspect(inspectableError(this), options); - } - /** - * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance, - * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, - * we explicitly include the properties in the `inspect` method. - * - * This is automatically called by Deno when you `console.log` an instance of this class. - * - * @param inspect - The inspect function to use (prevents having to import it from `util`) - * @param options - The options passed to `Deno.inspect` - * @returns A string representation of the error - */ - [/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) { - return inspect(inspectableError(this), options); - } - }; - __typeError = (msg) => { - throw TypeError(msg); - }; - __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); - __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); - __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); - __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); - __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); - EventSource = class extends EventTarget { - constructor(url2, eventSourceInitDict) { - var _a2, _b; - super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url2), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => { - var _a22; - __privateGet(this, _parser).reset(); - const { body, redirected, status, headers } = response; - if (status === 204) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close(); - return; - } - if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status); - return; - } - if (!(headers.get("content-type") || "").startsWith("text/event-stream")) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status); - return; - } - if (__privateGet(this, _readyState) === this.CLOSED) - return; - __privateSet(this, _readyState, this.OPEN); - const openEvent = new Event("open"); - if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close(); - return; - } - const decoder2 = new TextDecoder(), reader = body.getReader(); - let open = true; - do { - const { done, value } = await reader.read(); - value && __privateGet(this, _parser).feed(decoder2.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this)); - } while (open); - }), __privateAdd(this, _onFetchError, (err) => { - __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err)); - }), __privateAdd(this, _onEvent, (event) => { - typeof event.id == "string" && __privateSet(this, _lastEventId, event.id); - const messageEvent = new MessageEvent(event.event || "message", { - data: event.data, - origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url2).origin, - lastEventId: event.id || "" - }); - __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent); - }), __privateAdd(this, _onRetryChange, (value) => { - __privateSet(this, _reconnectInterval, value); - }), __privateAdd(this, _reconnect, () => { - __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this); - }); - try { - if (url2 instanceof URL) - __privateSet(this, _url2, url2); - else if (typeof url2 == "string") - __privateSet(this, _url2, new URL(url2, getBaseURL())); - else - throw new Error("Invalid URL"); - } catch { - throw syntaxError("An invalid or illegal string was specified"); - } - __privateSet(this, _parser, createParser({ - onEvent: __privateGet(this, _onEvent), - onRetry: __privateGet(this, _onRetryChange) - })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a2 : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this); - } - /** - * Returns the state of this EventSource object's connection. It can have the values described below. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - * - * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface, - * defined in the TypeScript `dom` library. - * - * @public - */ - get readyState() { - return __privateGet(this, _readyState); - } - /** - * Returns the URL providing the event stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - * - * @public - */ - get url() { - return __privateGet(this, _url2).href; - } - /** - * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials() { - return __privateGet(this, _withCredentials); - } - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror() { - return __privateGet(this, _onError); - } - set onerror(value) { - __privateSet(this, _onError, value); - } - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage() { - return __privateGet(this, _onMessage); - } - set onmessage(value) { - __privateSet(this, _onMessage, value); - } - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen() { - return __privateGet(this, _onOpen); - } - set onopen(value) { - __privateSet(this, _onOpen, value); - } - addEventListener(type, listener, options) { - const listen = listener; - super.addEventListener(type, listen, options); - } - removeEventListener(type, listener, options) { - const listen = listener; - super.removeEventListener(type, listen, options); - } - /** - * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - * - * @public - */ - close() { - __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0)); - } - }; - _readyState = /* @__PURE__ */ new WeakMap(), _url2 = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /** - * Connect to the given URL and start receiving events - * - * @internal - */ - connect_fn = function() { - __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url2), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError)); - }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /** - * Get request options for the `fetch()` request - * - * @returns The request options - * @internal - */ - getRequestOptions_fn = function() { - var _a2; - const init = { - // [spec] Let `corsAttributeState` be `Anonymous`… - // [spec] …will have their mode set to "cors"… - mode: "cors", - redirect: "follow", - headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 }, - cache: "no-store", - signal: (_a2 = __privateGet(this, _controller)) == null ? void 0 : _a2.signal - }; - return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init; - }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /** - * Handles the process referred to in the EventSource specification as "failing a connection". - * - * @param error - The error causing the connection to fail - * @param code - The HTTP status code, if available - * @internal - */ - failConnection_fn = function(message2, code) { - var _a2; - __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED); - const errorEvent = new ErrorEvent("error", { code, message: message2 }); - (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent); - }, /** - * Schedules a reconnection attempt against the EventSource endpoint. - * - * @param message - The error causing the connection to fail - * @param code - The HTTP status code, if available - * @internal - */ - scheduleReconnect_fn = function(message2, code) { - var _a2; - if (__privateGet(this, _readyState) === this.CLOSED) - return; - __privateSet(this, _readyState, this.CONNECTING); - const errorEvent = new ErrorEvent("error", { code, message: message2 }); - (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval))); - }, _reconnect = /* @__PURE__ */ new WeakMap(), /** - * ReadyState representing an EventSource currently trying to connect - * - * @public - */ - EventSource.CONNECTING = 0, /** - * ReadyState representing an EventSource connection that is open (eg connected) - * - * @public - */ - EventSource.OPEN = 1, /** - * ReadyState representing an EventSource connection that is closed (eg disconnected) - * - * @public - */ - EventSource.CLOSED = 2; - } -}); - -// ../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js -var EventSourceParserStream; -var init_stream = __esm({ - "../freya/node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js"() { - init_dist(); - EventSourceParserStream = class extends TransformStream { - constructor({ onError, onRetry, onComment } = {}) { - let parser; - super({ - start(controller) { - parser = createParser({ - onEvent: (event) => { - controller.enqueue(event); - }, - onError(error2) { - onError === "terminate" ? controller.error(error2) : typeof onError == "function" && onError(error2); - }, - onRetry, - onComment - }); - }, - transform(chunk) { - parser.feed(chunk); - } - }); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js -function concat(...buffers) { - const size = buffers.reduce((acc, { length }) => acc + length, 0); - const buf = new Uint8Array(size); - let i = 0; - for (const buffer of buffers) { - buf.set(buffer, i); - i += buffer.length; - } - return buf; -} -function writeUInt32BE(buf, value, offset) { - if (value < 0 || value >= MAX_INT32) { - throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); - } - buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); -} -function uint64be(value) { - const high = Math.floor(value / MAX_INT32); - const low = value % MAX_INT32; - const buf = new Uint8Array(8); - writeUInt32BE(buf, high, 0); - writeUInt32BE(buf, low, 4); - return buf; -} -function uint32be(value) { - const buf = new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -function encode2(string4) { - const bytes = new Uint8Array(string4.length); - for (let i = 0; i < string4.length; i++) { - const code = string4.charCodeAt(i); - if (code > 127) { - throw new TypeError("non-ASCII string encountered in encode()"); - } - bytes[i] = code; - } - return bytes; -} -var encoder, decoder, MAX_INT32; -var init_buffer_utils = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"() { - encoder = new TextEncoder(); - decoder = new TextDecoder(); - MAX_INT32 = 2 ** 32; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js -function encodeBase64(input) { - if (Uint8Array.prototype.toBase64) { - return input.toBase64(); - } - const CHUNK_SIZE = 32768; - const arr = []; - for (let i = 0; i < input.length; i += CHUNK_SIZE) { - arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))); - } - return btoa(arr.join("")); -} -function decodeBase64(encoded) { - if (Uint8Array.fromBase64) { - return Uint8Array.fromBase64(encoded); - } - const binary = atob(encoded); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) { - bytes[i] = binary.charCodeAt(i); - } - return bytes; -} -var init_base64 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"() { - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js -var base64url_exports = {}; -__export(base64url_exports, { - decode: () => decode2, - encode: () => encode3 -}); -function decode2(input) { - if (Uint8Array.fromBase64) { - return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { - alphabet: "base64url" - }); - } - let encoded = input; - if (encoded instanceof Uint8Array) { - encoded = decoder.decode(encoded); - } - encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); - try { - return decodeBase64(encoded); - } catch { - throw new TypeError("The input to be decoded is not correctly encoded."); - } -} -function encode3(input) { - let unencoded = input; - if (typeof unencoded === "string") { - unencoded = encoder.encode(unencoded); - } - if (Uint8Array.prototype.toBase64) { - return unencoded.toBase64({ alphabet: "base64url", omitPadding: true }); - } - return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} -var init_base64url = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"() { - init_buffer_utils(); - init_base64(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js -function getHashLength(hash2) { - return parseInt(hash2.name.slice(4), 10); -} -function checkHashLength(algorithm, expected) { - const actual = getHashLength(algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); -} -function getNamedCurve(alg) { - switch (alg) { - case "ES256": - return "P-256"; - case "ES384": - return "P-384"; - case "ES512": - return "P-521"; - default: - throw new Error("unreachable"); - } -} -function checkUsage(key, usage) { - if (usage && !key.usages.includes(usage)) { - throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); - } -} -function checkSigCryptoKey(key, alg, usage) { - switch (alg) { - case "HS256": - case "HS384": - case "HS512": { - if (!isAlgorithm(key.algorithm, "HMAC")) - throw unusable("HMAC"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - } - case "RS256": - case "RS384": - case "RS512": { - if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) - throw unusable("RSASSA-PKCS1-v1_5"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - } - case "PS256": - case "PS384": - case "PS512": { - if (!isAlgorithm(key.algorithm, "RSA-PSS")) - throw unusable("RSA-PSS"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - } - case "Ed25519": - case "EdDSA": { - if (!isAlgorithm(key.algorithm, "Ed25519")) - throw unusable("Ed25519"); - break; - } - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": { - if (!isAlgorithm(key.algorithm, alg)) - throw unusable(alg); - break; - } - case "ES256": - case "ES384": - case "ES512": { - if (!isAlgorithm(key.algorithm, "ECDSA")) - throw unusable("ECDSA"); - const expected = getNamedCurve(alg); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, "algorithm.namedCurve"); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -function checkEncCryptoKey(key, alg, usage) { - switch (alg) { - case "A128GCM": - case "A192GCM": - case "A256GCM": { - if (!isAlgorithm(key.algorithm, "AES-GCM")) - throw unusable("AES-GCM"); - const expected = parseInt(alg.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, "algorithm.length"); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - if (!isAlgorithm(key.algorithm, "AES-KW")) - throw unusable("AES-KW"); - const expected = parseInt(alg.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, "algorithm.length"); - break; - } - case "ECDH": { - switch (key.algorithm.name) { - case "ECDH": - case "X25519": - break; - default: - throw unusable("ECDH or X25519"); - } - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": - if (!isAlgorithm(key.algorithm, "PBKDF2")) - throw unusable("PBKDF2"); - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - if (!isAlgorithm(key.algorithm, "RSA-OAEP")) - throw unusable("RSA-OAEP"); - checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -var unusable, isAlgorithm; -var init_crypto_key = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"() { - unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); - isAlgorithm = (algorithm, name) => algorithm.name === name; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js -function message(msg, actual, ...types) { - types = types.filter(Boolean); - if (types.length > 2) { - const last = types.pop(); - msg += `one of type ${types.join(", ")}, or ${last}.`; - } else if (types.length === 2) { - msg += `one of type ${types[0]} or ${types[1]}.`; - } else { - msg += `of type ${types[0]}.`; - } - if (actual == null) { - msg += ` Received ${actual}`; - } else if (typeof actual === "function" && actual.name) { - msg += ` Received function ${actual.name}`; - } else if (typeof actual === "object" && actual != null) { - if (actual.constructor?.name) { - msg += ` Received an instance of ${actual.constructor.name}`; - } - } - return msg; -} -var invalidKeyInput, withAlg; -var init_invalid_key_input = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"() { - invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); - withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js -var errors_exports2 = {}; -__export(errors_exports2, { - JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, - JOSEError: () => JOSEError, - JOSENotSupported: () => JOSENotSupported, - JWEDecryptionFailed: () => JWEDecryptionFailed, - JWEInvalid: () => JWEInvalid, - JWKInvalid: () => JWKInvalid, - JWKSInvalid: () => JWKSInvalid, - JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, - JWKSNoMatchingKey: () => JWKSNoMatchingKey, - JWKSTimeout: () => JWKSTimeout, - JWSInvalid: () => JWSInvalid, - JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, - JWTClaimValidationFailed: () => JWTClaimValidationFailed, - JWTExpired: () => JWTExpired, - JWTInvalid: () => JWTInvalid -}); -var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed; -var init_errors3 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"() { - JOSEError = class extends Error { - static code = "ERR_JOSE_GENERIC"; - code = "ERR_JOSE_GENERIC"; - constructor(message2, options) { - super(message2, options); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } - }; - JWTClaimValidationFailed = class extends JOSEError { - static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - claim; - reason; - payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } - }; - JWTExpired = class extends JOSEError { - static code = "ERR_JWT_EXPIRED"; - code = "ERR_JWT_EXPIRED"; - claim; - reason; - payload; - constructor(message2, payload, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } - }; - JOSEAlgNotAllowed = class extends JOSEError { - static code = "ERR_JOSE_ALG_NOT_ALLOWED"; - code = "ERR_JOSE_ALG_NOT_ALLOWED"; - }; - JOSENotSupported = class extends JOSEError { - static code = "ERR_JOSE_NOT_SUPPORTED"; - code = "ERR_JOSE_NOT_SUPPORTED"; - }; - JWEDecryptionFailed = class extends JOSEError { - static code = "ERR_JWE_DECRYPTION_FAILED"; - code = "ERR_JWE_DECRYPTION_FAILED"; - constructor(message2 = "decryption operation failed", options) { - super(message2, options); - } - }; - JWEInvalid = class extends JOSEError { - static code = "ERR_JWE_INVALID"; - code = "ERR_JWE_INVALID"; - }; - JWSInvalid = class extends JOSEError { - static code = "ERR_JWS_INVALID"; - code = "ERR_JWS_INVALID"; - }; - JWTInvalid = class extends JOSEError { - static code = "ERR_JWT_INVALID"; - code = "ERR_JWT_INVALID"; - }; - JWKInvalid = class extends JOSEError { - static code = "ERR_JWK_INVALID"; - code = "ERR_JWK_INVALID"; - }; - JWKSInvalid = class extends JOSEError { - static code = "ERR_JWKS_INVALID"; - code = "ERR_JWKS_INVALID"; - }; - JWKSNoMatchingKey = class extends JOSEError { - static code = "ERR_JWKS_NO_MATCHING_KEY"; - code = "ERR_JWKS_NO_MATCHING_KEY"; - constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { - super(message2, options); - } - }; - JWKSMultipleMatchingKeys = class extends JOSEError { - [Symbol.asyncIterator]; - static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { - super(message2, options); - } - }; - JWKSTimeout = class extends JOSEError { - static code = "ERR_JWKS_TIMEOUT"; - code = "ERR_JWKS_TIMEOUT"; - constructor(message2 = "request timed out", options) { - super(message2, options); - } - }; - JWSSignatureVerificationFailed = class extends JOSEError { - static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - constructor(message2 = "signature verification failed", options) { - super(message2, options); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js -function assertCryptoKey(key) { - if (!isCryptoKey(key)) { - throw new Error("CryptoKey instance expected"); - } -} -var isCryptoKey, isKeyObject, isKeyLike; -var init_is_key_like = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"() { - isCryptoKey = (key) => { - if (key?.[Symbol.toStringTag] === "CryptoKey") - return true; - try { - return key instanceof CryptoKey; - } catch { - return false; - } - }; - isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; - isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js -function cekLength(alg) { - switch (alg) { - case "A128GCM": - return 128; - case "A192GCM": - return 192; - case "A256GCM": - case "A128CBC-HS256": - return 256; - case "A192CBC-HS384": - return 384; - case "A256CBC-HS512": - return 512; - default: - throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); - } -} -function checkCekLength(cek, expected) { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } -} -function ivBitLength(alg) { - switch (alg) { - case "A128GCM": - case "A128GCMKW": - case "A192GCM": - case "A192GCMKW": - case "A256GCM": - case "A256GCMKW": - return 96; - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - return 128; - default: - throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); - } -} -function checkIvLength(enc, iv) { - if (iv.length << 3 !== ivBitLength(enc)) { - throw new JWEInvalid("Invalid Initialization Vector length"); - } -} -async function cbcKeySetup(enc, cek, usage) { - if (!(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "Uint8Array")); - } - const keySize = parseInt(enc.slice(1, 4), 10); - const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]); - const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { - hash: `SHA-${keySize << 1}`, - name: "HMAC" - }, false, ["sign"]); - return { encKey, macKey, keySize }; -} -async function cbcHmacTag(macKey, macData, keySize) { - return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); -} -async function cbcEncrypt(enc, plaintext, cek, iv, aad) { - const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "encrypt"); - const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ - iv, - name: "AES-CBC" - }, encKey, plaintext)); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const tag2 = await cbcHmacTag(macKey, macData, keySize); - return { ciphertext, tag: tag2, iv }; -} -async function timingSafeEqual(a, b) { - if (!(a instanceof Uint8Array)) { - throw new TypeError("First argument must be a buffer"); - } - if (!(b instanceof Uint8Array)) { - throw new TypeError("Second argument must be a buffer"); - } - const algorithm = { name: "HMAC", hash: "SHA-256" }; - const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]); - const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a)); - const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b)); - let out = 0; - let i = -1; - while (++i < 32) { - out |= aHmac[i] ^ bHmac[i]; - } - return out === 0; -} -async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) { - const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "decrypt"); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const expectedTag = await cbcHmacTag(macKey, macData, keySize); - let macCheckPassed; - try { - macCheckPassed = await timingSafeEqual(tag2, expectedTag); - } catch { - } - if (!macCheckPassed) { - throw new JWEDecryptionFailed(); - } - let plaintext; - try { - plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); - } catch { - } - if (!plaintext) { - throw new JWEDecryptionFailed(); - } - return plaintext; -} -async function gcmEncrypt(enc, plaintext, cek, iv, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); - } else { - checkEncCryptoKey(cek, enc, "encrypt"); - encKey = cek; - } - const encrypted = new Uint8Array(await crypto.subtle.encrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, plaintext)); - const tag2 = encrypted.slice(-16); - const ciphertext = encrypted.slice(0, -16); - return { ciphertext, tag: tag2, iv }; -} -async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); - } else { - checkEncCryptoKey(cek, enc, "decrypt"); - encKey = cek; - } - try { - return new Uint8Array(await crypto.subtle.decrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, concat(ciphertext, tag2))); - } catch { - throw new JWEDecryptionFailed(); - } -} -async function encrypt(enc, plaintext, cek, iv, aad) { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); - } - if (iv) { - checkIvLength(enc, iv); - } else { - iv = generateIv(enc); - } - switch (enc) { - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc.slice(-3), 10)); - } - return cbcEncrypt(enc, plaintext, cek, iv, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); - } - return gcmEncrypt(enc, plaintext, cek, iv, aad); - default: - throw new JOSENotSupported(unsupportedEnc); - } -} -async function decrypt(enc, cek, ciphertext, iv, tag2, aad) { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); - } - if (!iv) { - throw new JWEInvalid("JWE Initialization Vector missing"); - } - if (!tag2) { - throw new JWEInvalid("JWE Authentication Tag missing"); - } - checkIvLength(enc, iv); - switch (enc) { - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc.slice(-3), 10)); - return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); - return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad); - default: - throw new JOSENotSupported(unsupportedEnc); - } -} -var generateCek, generateIv, unsupportedEnc; -var init_content_encryption = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js"() { - init_buffer_utils(); - init_crypto_key(); - init_invalid_key_input(); - init_errors3(); - init_is_key_like(); - generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3)); - generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3)); - unsupportedEnc = "Unsupported JWE Content Encryption Algorithm"; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js -function assertNotSet(value, name) { - if (value) { - throw new TypeError(`${name} can only be called once`); - } -} -function decodeBase64url(value, label, ErrorClass) { - try { - return decode2(value); - } catch { - throw new ErrorClass(`Failed to base64url decode the ${label}`); - } -} -async function digest(algorithm, data) { - const subtleDigest = `SHA-${algorithm.slice(-3)}`; - return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); -} -var unprotected; -var init_helpers = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"() { - init_base64url(); - unprotected = /* @__PURE__ */ Symbol(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js -function isObject2(input) { - if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { - return false; - } - if (Object.getPrototypeOf(input) === null) { - return true; - } - let proto = input; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(input) === proto; -} -function isDisjoint(...headers) { - const sources = headers.filter(Boolean); - if (sources.length === 0 || sources.length === 1) { - return true; - } - let acc; - for (const header of sources) { - const parameters = Object.keys(header); - if (!acc || acc.size === 0) { - acc = new Set(parameters); - continue; - } - for (const parameter of parameters) { - if (acc.has(parameter)) { - return false; - } - acc.add(parameter); - } - } - return true; -} -var isObjectLike, isJWK, isPrivateJWK, isPublicJWK, isSecretJWK; -var init_type_checks = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"() { - isObjectLike = (value) => typeof value === "object" && value !== null; - isJWK = (key) => isObject2(key) && typeof key.kty === "string"; - isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); - isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; - isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js -function checkKeySize(key, alg) { - if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { - throw new TypeError(`Invalid key size for alg: ${alg}`); - } -} -function getCryptoKey(key, alg, usage) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]); - } - checkEncCryptoKey(key, alg, usage); - return key; -} -async function wrap(alg, key, cek) { - const cryptoKey = await getCryptoKey(key, alg, "wrapKey"); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); - return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); -} -async function unwrap(alg, key, encryptedKey) { - const cryptoKey = await getCryptoKey(key, alg, "unwrapKey"); - checkKeySize(cryptoKey, alg); - const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); - return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); -} -var init_aeskw = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js"() { - init_crypto_key(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js -function lengthAndInput(input) { - return concat(uint32be(input.length), input); -} -async function concatKdf(Z, L, OtherInfo) { - const dkLen = L >> 3; - const hashLen = 32; - const reps = Math.ceil(dkLen / hashLen); - const dk = new Uint8Array(reps * hashLen); - for (let i = 1; i <= reps; i++) { - const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length); - hashInput.set(uint32be(i), 0); - hashInput.set(Z, 4); - hashInput.set(OtherInfo, 4 + Z.length); - const hashResult = await digest("sha256", hashInput); - dk.set(hashResult, (i - 1) * hashLen); - } - return dk.slice(0, dkLen); -} -async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { - checkEncCryptoKey(publicKey, "ECDH"); - checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); - const algorithmID = lengthAndInput(encode2(algorithm)); - const partyUInfo = lengthAndInput(apu); - const partyVInfo = lengthAndInput(apv); - const suppPubInfo = uint32be(keyLength); - const suppPrivInfo = new Uint8Array(); - const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); - const Z = new Uint8Array(await crypto.subtle.deriveBits({ - name: publicKey.algorithm.name, - public: publicKey - }, privateKey, getEcdhBitLength(publicKey))); - return concatKdf(Z, keyLength, otherInfo); -} -function getEcdhBitLength(publicKey) { - if (publicKey.algorithm.name === "X25519") { - return 256; - } - return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3; -} -function allowed(key) { - switch (key.algorithm.namedCurve) { - case "P-256": - case "P-384": - case "P-521": - return true; - default: - return key.algorithm.name === "X25519"; - } -} -var init_ecdhes = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js"() { - init_buffer_utils(); - init_crypto_key(); - init_helpers(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js -function getCryptoKey2(key, alg) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey("raw", key, "PBKDF2", false, [ - "deriveBits" - ]); - } - checkEncCryptoKey(key, alg, "deriveBits"); - return key; -} -async function deriveKey2(p2s, alg, p2c, key) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); - } - const salt = concatSalt(alg, p2s); - const keylen = parseInt(alg.slice(13, 16), 10); - const subtleAlg = { - hash: `SHA-${alg.slice(8, 11)}`, - iterations: p2c, - name: "PBKDF2", - salt - }; - const cryptoKey = await getCryptoKey2(key, alg); - return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); -} -async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) { - const derived = await deriveKey2(p2s, alg, p2c, key); - const encryptedKey = await wrap(alg.slice(-6), derived, cek); - return { encryptedKey, p2c, p2s: encode3(p2s) }; -} -async function unwrap2(alg, key, encryptedKey, p2c, p2s) { - const derived = await deriveKey2(p2s, alg, p2c, key); - return unwrap(alg.slice(-6), derived, encryptedKey); -} -var concatSalt; -var init_pbes2kw = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js"() { - init_base64url(); - init_aeskw(); - init_crypto_key(); - init_buffer_utils(); - init_errors3(); - concatSalt = (alg, p2sInput) => concat(encode2(alg), Uint8Array.of(0), p2sInput); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js -function checkKeyLength(alg, key) { - if (alg.startsWith("RS") || alg.startsWith("PS")) { - const { modulusLength } = key.algorithm; - if (typeof modulusLength !== "number" || modulusLength < 2048) { - throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); - } - } -} -function subtleAlgorithm(alg, algorithm) { - const hash2 = `SHA-${alg.slice(-3)}`; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - return { hash: hash2, name: "HMAC" }; - case "PS256": - case "PS384": - case "PS512": - return { hash: hash2, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 }; - case "RS256": - case "RS384": - case "RS512": - return { hash: hash2, name: "RSASSA-PKCS1-v1_5" }; - case "ES256": - case "ES384": - case "ES512": - return { hash: hash2, name: "ECDSA", namedCurve: algorithm.namedCurve }; - case "Ed25519": - case "EdDSA": - return { name: "Ed25519" }; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - return { name: alg }; - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} -async function getSigKey(alg, key, usage) { - if (key instanceof Uint8Array) { - if (!alg.startsWith("HS")) { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); - } - checkSigCryptoKey(key, alg, usage); - return key; -} -async function sign(alg, key, data) { - const cryptoKey = await getSigKey(alg, key, "sign"); - checkKeyLength(alg, cryptoKey); - const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); - return new Uint8Array(signature); -} -async function verify(alg, key, signature, data) { - const cryptoKey = await getSigKey(alg, key, "verify"); - checkKeyLength(alg, cryptoKey); - const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); - try { - return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); - } catch { - return false; - } -} -var init_signing = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"() { - init_errors3(); - init_crypto_key(); - init_invalid_key_input(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js -async function encrypt2(alg, key, cek) { - checkEncCryptoKey(key, alg, "encrypt"); - checkKeyLength(alg, key); - return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg), key, cek)); -} -async function decrypt2(alg, key, encryptedKey) { - checkEncCryptoKey(key, alg, "decrypt"); - checkKeyLength(alg, key); - return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg), key, encryptedKey)); -} -var subtleAlgorithm2; -var init_rsaes = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js"() { - init_crypto_key(); - init_signing(); - init_errors3(); - subtleAlgorithm2 = (alg) => { - switch (alg) { - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - return "RSA-OAEP"; - default: - throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js -function subtleMapping(jwk) { - let algorithm; - let keyUsages; - switch (jwk.kty) { - case "AKP": { - switch (jwk.alg) { - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - algorithm = { name: jwk.alg }; - keyUsages = jwk.priv ? ["sign"] : ["verify"]; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "RSA": { - switch (jwk.alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` - }; - keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "EC": { - switch (jwk.alg) { - case "ES256": - case "ES384": - case "ES512": - algorithm = { - name: "ECDSA", - namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg] - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm = { name: "ECDH", namedCurve: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "OKP": { - switch (jwk.alg) { - case "Ed25519": - case "EdDSA": - algorithm = { name: "Ed25519" }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm = { name: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); - } - return { algorithm, keyUsages }; -} -async function jwkToKey(jwk) { - if (!jwk.alg) { - throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); - } - const { algorithm, keyUsages } = subtleMapping(jwk); - const keyData = { ...jwk }; - if (keyData.kty !== "AKP") { - delete keyData.alg; - } - delete keyData.use; - return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); -} -var unsupportedAlg; -var init_jwk_to_key = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"() { - init_errors3(); - unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value'; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js -async function normalizeKey(key, alg) { - if (key instanceof Uint8Array) { - return key; - } - if (isCryptoKey(key)) { - return key; - } - if (isKeyObject(key)) { - if (key.type === "secret") { - return key.export(); - } - if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") { - try { - return handleKeyObject(key, alg); - } catch (err) { - if (err instanceof TypeError) { - throw err; - } - } - } - let jwk = key.export({ format: "jwk" }); - return handleJWK(key, jwk, alg); - } - if (isJWK(key)) { - if (key.k) { - return decode2(key.k); - } - return handleJWK(key, key, alg, true); - } - throw new Error("unreachable"); -} -var unusableForAlg, cache, handleJWK, handleKeyObject; -var init_normalize_key = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"() { - init_type_checks(); - init_base64url(); - init_jwk_to_key(); - init_is_key_like(); - unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; - handleJWK = async (key, jwk, alg, freeze = false) => { - cache ||= /* @__PURE__ */ new WeakMap(); - let cached2 = cache.get(key); - if (cached2?.[alg]) { - return cached2[alg]; - } - const cryptoKey = await jwkToKey({ ...jwk, alg }); - if (freeze) - Object.freeze(key); - if (!cached2) { - cache.set(key, { [alg]: cryptoKey }); - } else { - cached2[alg] = cryptoKey; - } - return cryptoKey; - }; - handleKeyObject = (keyObject, alg) => { - cache ||= /* @__PURE__ */ new WeakMap(); - let cached2 = cache.get(keyObject); - if (cached2?.[alg]) { - return cached2[alg]; - } - const isPublic = keyObject.type === "public"; - const extractable = isPublic ? true : false; - let cryptoKey; - if (keyObject.asymmetricKeyType === "x25519") { - switch (alg) { - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - break; - default: - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); - } - if (keyObject.asymmetricKeyType === "ed25519") { - if (alg !== "EdDSA" && alg !== "Ed25519") { - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ - isPublic ? "verify" : "sign" - ]); - } - switch (keyObject.asymmetricKeyType) { - case "ml-dsa-44": - case "ml-dsa-65": - case "ml-dsa-87": { - if (alg !== keyObject.asymmetricKeyType.toUpperCase()) { - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ - isPublic ? "verify" : "sign" - ]); - } - } - if (keyObject.asymmetricKeyType === "rsa") { - let hash2; - switch (alg) { - case "RSA-OAEP": - hash2 = "SHA-1"; - break; - case "RS256": - case "PS256": - case "RSA-OAEP-256": - hash2 = "SHA-256"; - break; - case "RS384": - case "PS384": - case "RSA-OAEP-384": - hash2 = "SHA-384"; - break; - case "RS512": - case "PS512": - case "RSA-OAEP-512": - hash2 = "SHA-512"; - break; - default: - throw new TypeError(unusableForAlg); - } - if (alg.startsWith("RSA-OAEP")) { - return keyObject.toCryptoKey({ - name: "RSA-OAEP", - hash: hash2 - }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); - } - cryptoKey = keyObject.toCryptoKey({ - name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", - hash: hash2 - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (keyObject.asymmetricKeyType === "ec") { - const nist = /* @__PURE__ */ new Map([ - ["prime256v1", "P-256"], - ["secp384r1", "P-384"], - ["secp521r1", "P-521"] - ]); - const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); - if (!namedCurve) { - throw new TypeError(unusableForAlg); - } - const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; - if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) { - cryptoKey = keyObject.toCryptoKey({ - name: "ECDSA", - namedCurve - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (alg.startsWith("ECDH-ES")) { - cryptoKey = keyObject.toCryptoKey({ - name: "ECDH", - namedCurve - }, extractable, isPublic ? [] : ["deriveBits"]); - } - } - if (!cryptoKey) { - throw new TypeError(unusableForAlg); - } - if (!cached2) { - cache.set(keyObject, { [alg]: cryptoKey }); - } else { - cached2[alg] = cryptoKey; - } - return cryptoKey; - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js -function parsePKCS8Header(state) { - expectTag(state, 48, "Invalid PKCS#8 structure"); - parseLength(state); - expectTag(state, 2, "Expected version field"); - const verLen = parseLength(state); - state.pos += verLen; - expectTag(state, 48, "Expected algorithm identifier"); - const algIdLen = parseLength(state); - const algIdStart = state.pos; - return { algIdStart, algIdLength: algIdLen }; -} -function parseSPKIHeader(state) { - expectTag(state, 48, "Invalid SPKI structure"); - parseLength(state); - expectTag(state, 48, "Expected algorithm identifier"); - const algIdLen = parseLength(state); - const algIdStart = state.pos; - return { algIdStart, algIdLength: algIdLen }; -} -function spkiFromX509(buf) { - const state = createASN1State(buf); - expectTag(state, 48, "Invalid certificate structure"); - parseLength(state); - expectTag(state, 48, "Invalid tbsCertificate structure"); - parseLength(state); - if (buf[state.pos] === 160) { - skipElement(state, 6); - } else { - skipElement(state, 5); - } - const spkiStart = state.pos; - expectTag(state, 48, "Invalid SPKI structure"); - const spkiContentLen = parseLength(state); - return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart)); -} -function extractX509SPKI(x509) { - const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g); - return spkiFromX509(derBytes); -} -var formatPEM, genericExport, toSPKI, toPKCS8, bytesEqual, createASN1State, parseLength, skipElement, expectTag, getSubarray, parseAlgorithmOID, parseECAlgorithmIdentifier, genericImport, processPEMData, fromPKCS8, fromSPKI, fromX509; -var init_asn1 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js"() { - init_invalid_key_input(); - init_base64(); - init_errors3(); - init_is_key_like(); - formatPEM = (b64, descriptor) => { - const newlined = (b64.match(/.{1,64}/g) || []).join("\n"); - return `-----BEGIN ${descriptor}----- -${newlined} ------END ${descriptor}-----`; - }; - genericExport = async (keyType, keyFormat, key) => { - if (isKeyObject(key)) { - if (key.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); - } - return key.export({ format: "pem", type: keyFormat }); - } - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject")); - } - if (!key.extractable) { - throw new TypeError("CryptoKey is not extractable"); - } - if (key.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); - } - return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); - }; - toSPKI = (key) => genericExport("public", "spki", key); - toPKCS8 = (key) => genericExport("private", "pkcs8", key); - bytesEqual = (a, b) => { - if (a.byteLength !== b.length) - return false; - for (let i = 0; i < a.byteLength; i++) { - if (a[i] !== b[i]) - return false; - } - return true; - }; - createASN1State = (data) => ({ data, pos: 0 }); - parseLength = (state) => { - const first = state.data[state.pos++]; - if (first & 128) { - const lengthOfLen = first & 127; - let length = 0; - for (let i = 0; i < lengthOfLen; i++) { - length = length << 8 | state.data[state.pos++]; - } - return length; - } - return first; - }; - skipElement = (state, count = 1) => { - if (count <= 0) - return; - state.pos++; - const length = parseLength(state); - state.pos += length; - if (count > 1) { - skipElement(state, count - 1); - } - }; - expectTag = (state, expectedTag, errorMessage) => { - if (state.data[state.pos++] !== expectedTag) { - throw new Error(errorMessage); - } - }; - getSubarray = (state, length) => { - const result = state.data.subarray(state.pos, state.pos + length); - state.pos += length; - return result; - }; - parseAlgorithmOID = (state) => { - expectTag(state, 6, "Expected algorithm OID"); - const oidLen = parseLength(state); - return getSubarray(state, oidLen); - }; - parseECAlgorithmIdentifier = (state) => { - const algOid = parseAlgorithmOID(state); - if (bytesEqual(algOid, [43, 101, 110])) { - return "X25519"; - } - if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) { - throw new Error("Unsupported key algorithm"); - } - expectTag(state, 6, "Expected curve OID"); - const curveOidLen = parseLength(state); - const curveOid = getSubarray(state, curveOidLen); - for (const { name, oid } of [ - { name: "P-256", oid: [42, 134, 72, 206, 61, 3, 1, 7] }, - { name: "P-384", oid: [43, 129, 4, 0, 34] }, - { name: "P-521", oid: [43, 129, 4, 0, 35] } - ]) { - if (bytesEqual(curveOid, oid)) { - return name; - } - } - throw new Error("Unsupported named curve"); - }; - genericImport = async (keyFormat, keyData, alg, options) => { - let algorithm; - let keyUsages; - const isPublic = keyFormat === "spki"; - const getSigUsages = () => isPublic ? ["verify"] : ["sign"]; - const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"]; - switch (alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` }; - keyUsages = getSigUsages(); - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` }; - keyUsages = getSigUsages(); - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}` - }; - keyUsages = getEncUsages(); - break; - case "ES256": - case "ES384": - case "ES512": { - const curveMap = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; - algorithm = { name: "ECDSA", namedCurve: curveMap[alg] }; - keyUsages = getSigUsages(); - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - try { - const namedCurve = options.getNamedCurve(keyData); - algorithm = namedCurve === "X25519" ? { name: "X25519" } : { name: "ECDH", namedCurve }; - } catch (cause) { - throw new JOSENotSupported("Invalid or unsupported key format"); - } - keyUsages = isPublic ? [] : ["deriveBits"]; - break; - } - case "Ed25519": - case "EdDSA": - algorithm = { name: "Ed25519" }; - keyUsages = getSigUsages(); - break; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - algorithm = { name: alg }; - keyUsages = getSigUsages(); - break; - default: - throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); - } - return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages); - }; - processPEMData = (pem, pattern) => { - return decodeBase64(pem.replace(pattern, "")); - }; - fromPKCS8 = (pem, alg, options) => { - const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g); - let opts = options; - if (alg?.startsWith?.("ECDH-ES")) { - opts ||= {}; - opts.getNamedCurve = (keyData2) => { - const state = createASN1State(keyData2); - parsePKCS8Header(state); - return parseECAlgorithmIdentifier(state); - }; - } - return genericImport("pkcs8", keyData, alg, opts); - }; - fromSPKI = (pem, alg, options) => { - const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g); - let opts = options; - if (alg?.startsWith?.("ECDH-ES")) { - opts ||= {}; - opts.getNamedCurve = (keyData2) => { - const state = createASN1State(keyData2); - parseSPKIHeader(state); - return parseECAlgorithmIdentifier(state); - }; - } - return genericImport("spki", keyData, alg, opts); - }; - fromX509 = (pem, alg, options) => { - let spki; - try { - spki = extractX509SPKI(pem); - } catch (cause) { - throw new TypeError("Failed to parse the X.509 certificate", { cause }); - } - return fromSPKI(formatPEM(encodeBase64(spki), "PUBLIC KEY"), alg, options); - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js -async function importSPKI(spki, alg, options) { - if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) { - throw new TypeError('"spki" must be SPKI formatted string'); - } - return fromSPKI(spki, alg, options); -} -async function importX509(x509, alg, options) { - if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) { - throw new TypeError('"x509" must be X.509 formatted string'); - } - return fromX509(x509, alg, options); -} -async function importPKCS8(pkcs8, alg, options) { - if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); - } - return fromPKCS8(pkcs8, alg, options); -} -async function importJWK(jwk, alg, options) { - if (!isObject2(jwk)) { - throw new TypeError("JWK must be an object"); - } - let ext; - alg ??= jwk.alg; - ext ??= options?.extractable ?? jwk.ext; - switch (jwk.kty) { - case "oct": - if (typeof jwk.k !== "string" || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value'); - } - return decode2(jwk.k); - case "RSA": - if ("oth" in jwk && jwk.oth !== void 0) { - throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); - } - return jwkToKey({ ...jwk, alg, ext }); - case "AKP": { - if (typeof jwk.alg !== "string" || !jwk.alg) { - throw new TypeError('missing "alg" (Algorithm) Parameter value'); - } - if (alg !== void 0 && alg !== jwk.alg) { - throw new TypeError("JWK alg and alg option value mismatch"); - } - return jwkToKey({ ...jwk, ext }); - } - case "EC": - case "OKP": - return jwkToKey({ ...jwk, alg, ext }); - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } -} -var init_import = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"() { - init_base64url(); - init_asn1(); - init_jwk_to_key(); - init_errors3(); - init_type_checks(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js -async function keyToJWK(key) { - if (isKeyObject(key)) { - if (key.type === "secret") { - key = key.export(); - } else { - return key.export({ format: "jwk" }); - } - } - if (key instanceof Uint8Array) { - return { - kty: "oct", - k: encode3(key) - }; - } - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array")); - } - if (!key.extractable) { - throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); - } - const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key); - if (jwk.kty === "AKP") { - ; - jwk.alg = alg; - } - return jwk; -} -var init_key_to_jwk = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js"() { - init_invalid_key_input(); - init_base64url(); - init_is_key_like(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js -async function exportSPKI(key) { - return toSPKI(key); -} -async function exportPKCS8(key) { - return toPKCS8(key); -} -async function exportJWK(key) { - return keyToJWK(key); -} -var init_export = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js"() { - init_asn1(); - init_key_to_jwk(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js -async function wrap3(alg, key, cek, iv) { - const jweAlgorithm = alg.slice(0, 7); - const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array()); - return { - encryptedKey: wrapped.ciphertext, - iv: encode3(wrapped.iv), - tag: encode3(wrapped.tag) - }; -} -async function unwrap3(alg, key, encryptedKey, iv, tag2) { - const jweAlgorithm = alg.slice(0, 7); - return decrypt(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array()); -} -var init_aesgcmkw = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js"() { - init_content_encryption(); - init_base64url(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js -function assertEncryptedKey(encryptedKey) { - if (encryptedKey === void 0) - throw new JWEInvalid("JWE Encrypted Key missing"); -} -async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { - switch (alg) { - case "dir": { - if (encryptedKey !== void 0) - throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); - return key; - } - case "ECDH-ES": - if (encryptedKey !== void 0) - throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - if (!isObject2(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - assertCryptoKey(key); - if (!allowed(key)) - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - const epk = await importJWK(joseHeader.epk, alg); - assertCryptoKey(epk); - let partyUInfo; - let partyVInfo; - if (joseHeader.apu !== void 0) { - if (typeof joseHeader.apu !== "string") - throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); - partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid); - } - if (joseHeader.apv !== void 0) { - if (typeof joseHeader.apv !== "string") - throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); - partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid); - } - const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); - if (alg === "ECDH-ES") - return sharedSecret; - assertEncryptedKey(encryptedKey); - return unwrap(alg.slice(-6), sharedSecret, encryptedKey); - } - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - assertEncryptedKey(encryptedKey); - assertCryptoKey(key); - return decrypt2(alg, key, encryptedKey); - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - assertEncryptedKey(encryptedKey); - if (typeof joseHeader.p2c !== "number") - throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); - const p2cLimit = options?.maxPBES2Count || 1e4; - if (joseHeader.p2c > p2cLimit) - throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); - if (typeof joseHeader.p2s !== "string") - throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); - let p2s; - p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid); - return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s); - } - case "A128KW": - case "A192KW": - case "A256KW": { - assertEncryptedKey(encryptedKey); - return unwrap(alg, key, encryptedKey); - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - assertEncryptedKey(encryptedKey); - if (typeof joseHeader.iv !== "string") - throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); - if (typeof joseHeader.tag !== "string") - throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); - let iv; - iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid); - let tag2; - tag2 = decodeBase64url(joseHeader.tag, "tag", JWEInvalid); - return unwrap3(alg, key, encryptedKey, iv, tag2); - } - default: { - throw new JOSENotSupported(unsupportedAlgHeader); - } - } -} -async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - switch (alg) { - case "dir": { - cek = key; - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - assertCryptoKey(key); - if (!allowed(key)) { - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - } - const { apu, apv } = providedParameters; - let ephemeralKey; - if (providedParameters.epk) { - ephemeralKey = await normalizeKey(providedParameters.epk, alg); - } else { - ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey; - } - const { x, y, crv, kty } = await exportJWK(ephemeralKey); - const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === "EC") - parameters.epk.y = y; - if (apu) - parameters.apu = encode3(apu); - if (apv) - parameters.apv = encode3(apv); - if (alg === "ECDH-ES") { - cek = sharedSecret; - break; - } - cek = providedCek || generateCek(enc); - const kwAlg = alg.slice(-6); - encryptedKey = await wrap(kwAlg, sharedSecret, cek); - break; - } - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - cek = providedCek || generateCek(enc); - assertCryptoKey(key); - encryptedKey = await encrypt2(alg, key, cek); - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - cek = providedCek || generateCek(enc); - const { p2c, p2s } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s)); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - cek = providedCek || generateCek(enc); - encryptedKey = await wrap(alg, key, cek); - break; - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - cek = providedCek || generateCek(enc); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv)); - break; - } - default: { - throw new JOSENotSupported(unsupportedAlgHeader); - } - } - return { cek, encryptedKey, parameters }; -} -var unsupportedAlgHeader; -var init_key_management = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js"() { - init_aeskw(); - init_ecdhes(); - init_pbes2kw(); - init_rsaes(); - init_base64url(); - init_normalize_key(); - init_errors3(); - init_helpers(); - init_content_encryption(); - init_import(); - init_export(); - init_type_checks(); - init_aesgcmkw(); - init_is_key_like(); - unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value'; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); - } - if (!protectedHeader || protectedHeader.crit === void 0) { - return /* @__PURE__ */ new Set(); - } - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { - throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); - } - let recognized; - if (recognizedOption !== void 0) { - recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); - } else { - recognized = recognizedDefault; - } - for (const parameter of protectedHeader.crit) { - if (!recognized.has(parameter)) { - throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); - } - if (joseHeader[parameter] === void 0) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`); - } - if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - } - return new Set(protectedHeader.crit); -} -var init_validate_crit = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"() { - init_errors3(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js -function validateAlgorithms(option, algorithms) { - if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s3) => typeof s3 !== "string"))) { - throw new TypeError(`"${option}" option must be an array of strings`); - } - if (!algorithms) { - return void 0; - } - return new Set(algorithms); -} -var init_validate_algorithms = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"() { - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js -function checkKeyType(alg, key, usage) { - switch (alg.substring(0, 2)) { - case "A1": - case "A2": - case "di": - case "HS": - case "PB": - symmetricTypeCheck(alg, key, usage); - break; - default: - asymmetricTypeCheck(alg, key, usage); - } -} -var tag, jwkMatchesOp, symmetricTypeCheck, asymmetricTypeCheck; -var init_check_key_type = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"() { - init_invalid_key_input(); - init_is_key_like(); - init_type_checks(); - tag = (key) => key?.[Symbol.toStringTag]; - jwkMatchesOp = (alg, key, usage) => { - if (key.use !== void 0) { - let expected; - switch (usage) { - case "sign": - case "verify": - expected = "sig"; - break; - case "encrypt": - case "decrypt": - expected = "enc"; - break; - } - if (key.use !== expected) { - throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); - } - } - if (key.alg !== void 0 && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); - } - if (Array.isArray(key.key_ops)) { - let expectedKeyOp; - switch (true) { - case (usage === "sign" || usage === "verify"): - case alg === "dir": - case alg.includes("CBC-HS"): - expectedKeyOp = usage; - break; - case alg.startsWith("PBES2"): - expectedKeyOp = "deriveBits"; - break; - case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg): - if (!alg.includes("GCM") && alg.endsWith("KW")) { - expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; - } else { - expectedKeyOp = usage; - } - break; - case (usage === "encrypt" && alg.startsWith("RSA")): - expectedKeyOp = "wrapKey"; - break; - case usage === "decrypt": - expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits"; - break; - } - if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { - throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); - } - } - return true; - }; - symmetricTypeCheck = (alg, key, usage) => { - if (key instanceof Uint8Array) - return; - if (isJWK(key)) { - if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); - } - if (!isKeyLike(key)) { - throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); - } - if (key.type !== "secret") { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } - }; - asymmetricTypeCheck = (alg, key, usage) => { - if (isJWK(key)) { - switch (usage) { - case "decrypt": - case "sign": - if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation must be a private JWK`); - case "encrypt": - case "verify": - if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation must be a public JWK`); - } - } - if (!isKeyLike(key)) { - throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - if (key.type === "secret") { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (key.type === "public") { - switch (usage) { - case "sign": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - case "decrypt": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - } - if (key.type === "private") { - switch (usage) { - case "verify": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - case "encrypt": - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js -function supported(name) { - if (typeof globalThis[name] === "undefined") { - throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`); - } -} -async function compress(input) { - supported("CompressionStream"); - const cs = new CompressionStream("deflate-raw"); - const writer = cs.writable.getWriter(); - writer.write(input).catch(() => { - }); - writer.close().catch(() => { - }); - const chunks = []; - const reader = cs.readable.getReader(); - for (; ; ) { - const { value, done } = await reader.read(); - if (done) - break; - chunks.push(value); - } - return concat(...chunks); -} -async function decompress(input, maxLength) { - supported("DecompressionStream"); - const ds = new DecompressionStream("deflate-raw"); - const writer = ds.writable.getWriter(); - writer.write(input).catch(() => { - }); - writer.close().catch(() => { - }); - const chunks = []; - let length = 0; - const reader = ds.readable.getReader(); - for (; ; ) { - const { value, done } = await reader.read(); - if (done) - break; - chunks.push(value); - length += value.byteLength; - if (maxLength !== Infinity && length > maxLength) { - throw new JWEInvalid("Decompressed plaintext exceeded the configured limit"); - } - } - return concat(...chunks); -} -var init_deflate = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js"() { - init_errors3(); - init_buffer_utils(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js -async function flattenedDecrypt(jwe, key, options) { - if (!isObject2(jwe)) { - throw new JWEInvalid("Flattened JWE must be an object"); - } - if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { - throw new JWEInvalid("JOSE Header missing"); - } - if (jwe.iv !== void 0 && typeof jwe.iv !== "string") { - throw new JWEInvalid("JWE Initialization Vector incorrect type"); - } - if (typeof jwe.ciphertext !== "string") { - throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); - } - if (jwe.tag !== void 0 && typeof jwe.tag !== "string") { - throw new JWEInvalid("JWE Authentication Tag incorrect type"); - } - if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { - throw new JWEInvalid("JWE Protected Header incorrect type"); - } - if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { - throw new JWEInvalid("JWE Encrypted Key incorrect type"); - } - if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { - throw new JWEInvalid("JWE AAD incorrect type"); - } - if (jwe.header !== void 0 && !isObject2(jwe.header)) { - throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); - } - if (jwe.unprotected !== void 0 && !isObject2(jwe.unprotected)) { - throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); - } - let parsedProt; - if (jwe.protected) { - try { - const protectedHeader2 = decode2(jwe.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader2)); - } catch { - throw new JWEInvalid("JWE Protected Header is invalid"); - } - } - if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { - throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jwe.header, - ...jwe.unprotected - }; - validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader); - if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { - throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); - } - if (joseHeader.zip !== void 0 && !parsedProt?.zip) { - throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); - } - if (typeof enc !== "string" || !enc) { - throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); - } - const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms); - const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); - if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { - throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); - } - let encryptedKey; - if (jwe.encrypted_key !== void 0) { - encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jwe); - resolvedKey = true; - } - checkKeyType(alg === "dir" ? enc : alg, key, "decrypt"); - const k = await normalizeKey(key, alg); - let cek; - try { - cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options); - } catch (err) { - if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { - throw err; - } - cek = generateCek(enc); - } - let iv; - let tag2; - if (jwe.iv !== void 0) { - iv = decodeBase64url(jwe.iv, "iv", JWEInvalid); - } - if (jwe.tag !== void 0) { - tag2 = decodeBase64url(jwe.tag, "tag", JWEInvalid); - } - const protectedHeader = jwe.protected !== void 0 ? encode2(jwe.protected) : new Uint8Array(); - let additionalData; - if (jwe.aad !== void 0) { - additionalData = concat(protectedHeader, encode2("."), encode2(jwe.aad)); - } else { - additionalData = protectedHeader; - } - const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid); - const plaintext = await decrypt(enc, cek, ciphertext, iv, tag2, additionalData); - const result = { plaintext }; - if (joseHeader.zip === "DEF") { - const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4; - if (maxDecompressedLength === 0) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) { - throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity"); - } - result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => { - if (cause instanceof JWEInvalid) - throw cause; - throw new JWEInvalid("Failed to decompress plaintext", { cause }); - }); - } - if (jwe.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jwe.aad !== void 0) { - result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid); - } - if (jwe.unprotected !== void 0) { - result.sharedUnprotectedHeader = jwe.unprotected; - } - if (jwe.header !== void 0) { - result.unprotectedHeader = jwe.header; - } - if (resolvedKey) { - return { ...result, key: k }; - } - return result; -} -var init_decrypt = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js"() { - init_base64url(); - init_content_encryption(); - init_helpers(); - init_errors3(); - init_type_checks(); - init_type_checks(); - init_key_management(); - init_buffer_utils(); - init_content_encryption(); - init_validate_crit(); - init_validate_algorithms(); - init_normalize_key(); - init_check_key_type(); - init_deflate(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js -async function compactDecrypt(jwe, key, options) { - if (jwe instanceof Uint8Array) { - jwe = decoder.decode(jwe); - } - if (typeof jwe !== "string") { - throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split("."); - if (length !== 5) { - throw new JWEInvalid("Invalid Compact JWE"); - } - const decrypted = await flattenedDecrypt({ - ciphertext, - iv: iv || void 0, - protected: protectedHeader, - tag: tag2 || void 0, - encrypted_key: encryptedKey || void 0 - }, key, options); - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; -} -var init_decrypt2 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js"() { - init_decrypt(); - init_errors3(); - init_buffer_utils(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/decrypt.js -async function generalDecrypt(jwe, key, options) { - if (!isObject2(jwe)) { - throw new JWEInvalid("General JWE must be an object"); - } - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject2)) { - throw new JWEInvalid("JWE Recipients missing or incorrect type"); - } - if (!jwe.recipients.length) { - throw new JWEInvalid("JWE Recipients has no members"); - } - for (const recipient of jwe.recipients) { - try { - return await flattenedDecrypt({ - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected - }, key, options); - } catch { - } - } - throw new JWEDecryptionFailed(); -} -var init_decrypt3 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/decrypt.js"() { - init_decrypt(); - init_errors3(); - init_type_checks(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js -var FlattenedEncrypt; -var init_encrypt = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js"() { - init_base64url(); - init_helpers(); - init_content_encryption(); - init_key_management(); - init_errors3(); - init_type_checks(); - init_buffer_utils(); - init_validate_crit(); - init_normalize_key(); - init_check_key_type(); - init_deflate(); - FlattenedEncrypt = class { - #plaintext; - #protectedHeader; - #sharedUnprotectedHeader; - #unprotectedHeader; - #aad; - #cek; - #iv; - #keyManagementParameters; - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError("plaintext must be an instance of Uint8Array"); - } - this.#plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); - this.#keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.#protectedHeader, "setProtectedHeader"); - this.#protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - assertNotSet(this.#sharedUnprotectedHeader, "setSharedUnprotectedHeader"); - this.#sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); - this.#unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this.#aad = aad; - return this; - } - setContentEncryptionKey(cek) { - assertNotSet(this.#cek, "setContentEncryptionKey"); - this.#cek = cek; - return this; - } - setInitializationVector(iv) { - assertNotSet(this.#iv, "setInitializationVector"); - this.#iv = iv; - return this; - } - async encrypt(key, options) { - if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) { - throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); - } - if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this.#protectedHeader, - ...this.#unprotectedHeader, - ...this.#sharedUnprotectedHeader - }; - validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader); - if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { - throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); - } - if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) { - throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc !== "string" || !enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); - } - checkKeyType(alg === "dir" ? enc : alg, key, "encrypt"); - let cek; - { - let parameters; - const k = await normalizeKey(key, alg); - ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters)); - if (parameters) { - if (options && unprotected in options) { - if (!this.#unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } else { - this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters }; - } - } else if (!this.#protectedHeader) { - this.setProtectedHeader(parameters); - } else { - this.#protectedHeader = { ...this.#protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeaderS; - let protectedHeaderB; - let aadMember; - if (this.#protectedHeader) { - protectedHeaderS = encode3(JSON.stringify(this.#protectedHeader)); - protectedHeaderB = encode2(protectedHeaderS); - } else { - protectedHeaderS = ""; - protectedHeaderB = new Uint8Array(); - } - if (this.#aad) { - aadMember = encode3(this.#aad); - const aadMemberBytes = encode2(aadMember); - additionalData = concat(protectedHeaderB, encode2("."), aadMemberBytes); - } else { - additionalData = protectedHeaderB; - } - let plaintext = this.#plaintext; - if (joseHeader.zip === "DEF") { - plaintext = await compress(plaintext).catch((cause) => { - throw new JWEInvalid("Failed to compress plaintext", { cause }); - }); - } - const { ciphertext, tag: tag2, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData); - const jwe = { - ciphertext: encode3(ciphertext) - }; - if (iv) { - jwe.iv = encode3(iv); - } - if (tag2) { - jwe.tag = encode3(tag2); - } - if (encryptedKey) { - jwe.encrypted_key = encode3(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this.#protectedHeader) { - jwe.protected = protectedHeaderS; - } - if (this.#sharedUnprotectedHeader) { - jwe.unprotected = this.#sharedUnprotectedHeader; - } - if (this.#unprotectedHeader) { - jwe.header = this.#unprotectedHeader; - } - return jwe; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/encrypt.js -var IndividualRecipient, GeneralEncrypt; -var init_encrypt2 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/general/encrypt.js"() { - init_encrypt(); - init_helpers(); - init_errors3(); - init_content_encryption(); - init_type_checks(); - init_key_management(); - init_base64url(); - init_validate_crit(); - init_normalize_key(); - init_check_key_type(); - IndividualRecipient = class { - #parent; - unprotectedHeader; - keyManagementParameters; - key; - options; - constructor(enc, key, options) { - this.#parent = enc; - this.key = key; - this.options = options; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(this.unprotectedHeader, "setUnprotectedHeader"); - this.unprotectedHeader = unprotectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - assertNotSet(this.keyManagementParameters, "setKeyManagementParameters"); - this.keyManagementParameters = parameters; - return this; - } - addRecipient(...args) { - return this.#parent.addRecipient(...args); - } - encrypt(...args) { - return this.#parent.encrypt(...args); - } - done() { - return this.#parent; - } - }; - GeneralEncrypt = class { - #plaintext; - #recipients = []; - #protectedHeader; - #unprotectedHeader; - #aad; - constructor(plaintext) { - this.#plaintext = plaintext; - } - addRecipient(key, options) { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); - this.#recipients.push(recipient); - return recipient; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.#protectedHeader, "setProtectedHeader"); - this.#protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - assertNotSet(this.#unprotectedHeader, "setSharedUnprotectedHeader"); - this.#unprotectedHeader = sharedUnprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this.#aad = aad; - return this; - } - async encrypt() { - if (!this.#recipients.length) { - throw new JWEInvalid("at least one recipient must be added"); - } - if (this.#recipients.length === 1) { - const [recipient] = this.#recipients; - const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options }); - const jwe2 = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag - }; - if (flattened.aad) - jwe2.aad = flattened.aad; - if (flattened.protected) - jwe2.protected = flattened.protected; - if (flattened.unprotected) - jwe2.unprotected = flattened.unprotected; - if (flattened.encrypted_key) - jwe2.recipients[0].encrypted_key = flattened.encrypted_key; - if (flattened.header) - jwe2.recipients[0].header = flattened.header; - return jwe2; - } - let enc; - for (let i = 0; i < this.#recipients.length; i++) { - const recipient = this.#recipients[i]; - if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this.#protectedHeader, - ...this.#unprotectedHeader, - ...recipient.unprotectedHeader - }; - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (alg === "dir" || alg === "ECDH-ES") { - throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); - } - if (typeof joseHeader.enc !== "string" || !joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - if (!enc) { - enc = joseHeader.enc; - } else if (enc !== joseHeader.enc) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); - } - validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this.#protectedHeader, joseHeader); - if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { - throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); - } - if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) { - throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); - } - } - const cek = generateCek(enc); - const jwe = { - ciphertext: "", - recipients: [] - }; - for (let i = 0; i < this.#recipients.length; i++) { - const recipient = this.#recipients[i]; - const target = {}; - jwe.recipients.push(target); - if (i === 0) { - const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setContentEncryptionKey(cek).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters(recipient.keyManagementParameters).encrypt(recipient.key, { - ...recipient.options, - [unprotected]: true - }); - jwe.ciphertext = flattened.ciphertext; - jwe.iv = flattened.iv; - jwe.tag = flattened.tag; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - target.encrypted_key = flattened.encrypted_key; - if (flattened.header) - target.header = flattened.header; - continue; - } - const alg = recipient.unprotectedHeader?.alg || this.#protectedHeader?.alg || this.#unprotectedHeader?.alg; - checkKeyType(alg === "dir" ? enc : alg, recipient.key, "encrypt"); - const k = await normalizeKey(recipient.key, alg); - const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters); - target.encrypted_key = encode3(encryptedKey); - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters }; - } - return jwe; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js -async function flattenedVerify(jws, key, options) { - if (!isObject2(jws)) { - throw new JWSInvalid("Flattened JWS must be an object"); - } - if (jws.protected === void 0 && jws.header === void 0) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== void 0 && typeof jws.protected !== "string") { - throw new JWSInvalid("JWS Protected Header incorrect type"); - } - if (jws.payload === void 0) { - throw new JWSInvalid("JWS Payload missing"); - } - if (typeof jws.signature !== "string") { - throw new JWSInvalid("JWS Signature missing or incorrect type"); - } - if (jws.header !== void 0 && !isObject2(jws.header)) { - throw new JWSInvalid("JWS Unprotected Header incorrect type"); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = decode2(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } catch { - throw new JWSInvalid("JWS Protected Header is invalid"); - } - } - if (!isDisjoint(parsedProt, jws.header)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jws.header - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = parsedProt.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && validateAlgorithms("algorithms", options.algorithms); - if (algorithms && !algorithms.has(alg)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== "string") { - throw new JWSInvalid("JWS Payload must be a string"); - } - } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jws); - resolvedKey = true; - } - checkKeyType(alg, key, "verify"); - const data = concat(jws.protected !== void 0 ? encode2(jws.protected) : new Uint8Array(), encode2("."), typeof jws.payload === "string" ? b64 ? encode2(jws.payload) : encoder.encode(jws.payload) : jws.payload); - const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); - const k = await normalizeKey(key, alg); - const verified = await verify(alg, k, signature, data); - if (!verified) { - throw new JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - payload = decodeBase64url(jws.payload, "payload", JWSInvalid); - } else if (typeof jws.payload === "string") { - payload = encoder.encode(jws.payload); - } else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jws.header !== void 0) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key: k }; - } - return result; -} -var init_verify = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"() { - init_base64url(); - init_signing(); - init_errors3(); - init_buffer_utils(); - init_helpers(); - init_type_checks(); - init_type_checks(); - init_check_key_type(); - init_validate_crit(); - init_validate_algorithms(); - init_normalize_key(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws); - } - if (typeof jws !== "string") { - throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); - if (length !== 3) { - throw new JWSInvalid("Invalid Compact JWS"); - } - const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} -var init_verify2 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"() { - init_verify(); - init_errors3(); - init_buffer_utils(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/verify.js -async function generalVerify(jws, key, options) { - if (!isObject2(jws)) { - throw new JWSInvalid("General JWS must be an object"); - } - if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject2)) { - throw new JWSInvalid("JWS Signatures missing or incorrect type"); - } - for (const signature of jws.signatures) { - try { - return await flattenedVerify({ - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature - }, key, options); - } catch { - } - } - throw new JWSSignatureVerificationFailed(); -} -var init_verify3 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/verify.js"() { - init_verify(); - init_errors3(); - init_type_checks(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js -function secs(str) { - const matched = REGEX.exec(str); - if (!matched || matched[4] && matched[1]) { - throw new TypeError("Invalid time period format"); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case "sec": - case "secs": - case "second": - case "seconds": - case "s": - numericDate = Math.round(value); - break; - case "minute": - case "minutes": - case "min": - case "mins": - case "m": - numericDate = Math.round(value * minute); - break; - case "hour": - case "hours": - case "hr": - case "hrs": - case "h": - numericDate = Math.round(value * hour); - break; - case "day": - case "days": - case "d": - numericDate = Math.round(value * day); - break; - case "week": - case "weeks": - case "w": - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === "-" || matched[4] === "ago") { - return -numericDate; - } - return numericDate; -} -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; -} -function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } catch { - } - if (!isObject2(payload)) { - throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); - } - const { typ } = options; - if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed"); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== void 0) - presenceCheck.push("iat"); - if (audience !== void 0) - presenceCheck.push("aud"); - if (subject !== void 0) - presenceCheck.push("sub"); - if (issuer !== void 0) - presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed"); - } - if (subject && payload.sub !== subject) { - throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed"); - } - if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { - throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed"); - } - let tolerance; - switch (typeof options.clockTolerance) { - case "string": - tolerance = secs(options.clockTolerance); - break; - case "number": - tolerance = options.clockTolerance; - break; - case "undefined": - tolerance = 0; - break; - default: - throw new TypeError("Invalid clockTolerance option type"); - } - const { currentDate } = options; - const now = epoch(currentDate || /* @__PURE__ */ new Date()); - if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid"); - } - if (payload.nbf !== void 0) { - if (typeof payload.nbf !== "number") { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid"); - } - if (payload.nbf > now + tolerance) { - throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed"); - } - } - if (payload.exp !== void 0) { - if (typeof payload.exp !== "number") { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid"); - } - if (payload.exp <= now - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed"); - } - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed"); - } - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed"); - } - } - return payload; -} -var epoch, minute, hour, day, week, year, REGEX, normalizeTyp, checkAudiencePresence, JWTClaimsBuilder; -var init_jwt_claims_set = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"() { - init_errors3(); - init_buffer_utils(); - init_type_checks(); - epoch = (date5) => Math.floor(date5.getTime() / 1e3); - minute = 60; - hour = minute * 60; - day = hour * 24; - week = day * 7; - year = day * 365.25; - REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; - normalizeTyp = (value) => { - if (value.includes("/")) { - return value.toLowerCase(); - } - return `application/${value.toLowerCase()}`; - }; - checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === "string") { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; - }; - JWTClaimsBuilder = class { - #payload; - constructor(payload) { - if (!isObject2(payload)) { - throw new TypeError("JWT Claims Set MUST be an object"); - } - this.#payload = structuredClone(payload); - } - data() { - return encoder.encode(JSON.stringify(this.#payload)); - } - get iss() { - return this.#payload.iss; - } - set iss(value) { - this.#payload.iss = value; - } - get sub() { - return this.#payload.sub; - } - set sub(value) { - this.#payload.sub = value; - } - get aud() { - return this.#payload.aud; - } - set aud(value) { - this.#payload.aud = value; - } - set jti(value) { - this.#payload.jti = value; - } - set nbf(value) { - if (typeof value === "number") { - this.#payload.nbf = validateInput("setNotBefore", value); - } else if (value instanceof Date) { - this.#payload.nbf = validateInput("setNotBefore", epoch(value)); - } else { - this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - } - set exp(value) { - if (typeof value === "number") { - this.#payload.exp = validateInput("setExpirationTime", value); - } else if (value instanceof Date) { - this.#payload.exp = validateInput("setExpirationTime", epoch(value)); - } else { - this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - } - set iat(value) { - if (value === void 0) { - this.#payload.iat = epoch(/* @__PURE__ */ new Date()); - } else if (value instanceof Date) { - this.#payload.iat = validateInput("setIssuedAt", epoch(value)); - } else if (typeof value === "string") { - this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); - } else { - this.#payload.iat = validateInput("setIssuedAt", value); - } - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js -async function jwtVerify(jwt2, key, options) { - const verified = await compactVerify(jwt2, key, options); - if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} -var init_verify4 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"() { - init_verify2(); - init_jwt_claims_set(); - init_errors3(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js -async function jwtDecrypt(jwt2, key, options) { - const decrypted = await compactDecrypt(jwt2, key, options); - const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { - throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch"); - } - if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { - throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch"); - } - if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch"); - } - const result = { payload, protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; -} -var init_decrypt4 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js"() { - init_decrypt2(); - init_jwt_claims_set(); - init_errors3(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js -var CompactEncrypt; -var init_encrypt3 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js"() { - init_encrypt(); - CompactEncrypt = class { - #flattened; - constructor(plaintext) { - this.#flattened = new FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this.#flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this.#flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this.#flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this.#flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this.#flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js -var FlattenedSign; -var init_sign = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"() { - init_base64url(); - init_signing(); - init_type_checks(); - init_errors3(); - init_buffer_utils(); - init_check_key_type(); - init_validate_crit(); - init_normalize_key(); - init_helpers(); - FlattenedSign = class { - #payload; - #protectedHeader; - #unprotectedHeader; - constructor(payload) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError("payload must be an instance of Uint8Array"); - } - this.#payload = payload; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.#protectedHeader, "setProtectedHeader"); - this.#protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); - this.#unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this.#protectedHeader && !this.#unprotectedHeader) { - throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); - } - if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this.#protectedHeader, - ...this.#unprotectedHeader - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = this.#protectedHeader.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - checkKeyType(alg, key, "sign"); - let payloadS; - let payloadB; - if (b64) { - payloadS = encode3(this.#payload); - payloadB = encode2(payloadS); - } else { - payloadB = this.#payload; - payloadS = ""; - } - let protectedHeaderString; - let protectedHeaderBytes; - if (this.#protectedHeader) { - protectedHeaderString = encode3(JSON.stringify(this.#protectedHeader)); - protectedHeaderBytes = encode2(protectedHeaderString); - } else { - protectedHeaderString = ""; - protectedHeaderBytes = new Uint8Array(); - } - const data = concat(protectedHeaderBytes, encode2("."), payloadB); - const k = await normalizeKey(key, alg); - const signature = await sign(alg, k, data); - const jws = { - signature: encode3(signature), - payload: payloadS - }; - if (this.#unprotectedHeader) { - jws.header = this.#unprotectedHeader; - } - if (this.#protectedHeader) { - jws.protected = protectedHeaderString; - } - return jws; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js -var CompactSign; -var init_sign2 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"() { - init_sign(); - CompactSign = class { - #flattened; - constructor(payload) { - this.#flattened = new FlattenedSign(payload); - } - setProtectedHeader(protectedHeader) { - this.#flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this.#flattened.sign(key, options); - if (jws.payload === void 0) { - throw new TypeError("use the flattened module for creating JWS with b64: false"); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/sign.js -var IndividualSignature, GeneralSign; -var init_sign3 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/general/sign.js"() { - init_sign(); - init_errors3(); - init_helpers(); - IndividualSignature = class { - #parent; - protectedHeader; - unprotectedHeader; - options; - key; - constructor(sig, key, options) { - this.#parent = sig; - this.key = key; - this.options = options; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.protectedHeader, "setProtectedHeader"); - this.protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(this.unprotectedHeader, "setUnprotectedHeader"); - this.unprotectedHeader = unprotectedHeader; - return this; - } - addSignature(...args) { - return this.#parent.addSignature(...args); - } - sign(...args) { - return this.#parent.sign(...args); - } - done() { - return this.#parent; - } - }; - GeneralSign = class { - #payload; - #signatures = []; - constructor(payload) { - this.#payload = payload; - } - addSignature(key, options) { - const signature = new IndividualSignature(this, key, options); - this.#signatures.push(signature); - return signature; - } - async sign() { - if (!this.#signatures.length) { - throw new JWSInvalid("at least one signature must be added"); - } - const jws = { - signatures: [], - payload: "" - }; - for (let i = 0; i < this.#signatures.length; i++) { - const signature = this.#signatures[i]; - const flattened = new FlattenedSign(this.#payload); - flattened.setProtectedHeader(signature.protectedHeader); - flattened.setUnprotectedHeader(signature.unprotectedHeader); - const { payload, ...rest } = await flattened.sign(signature.key, signature.options); - if (i === 0) { - jws.payload = payload; - } else if (jws.payload !== payload) { - throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)"); - } - jws.signatures.push(rest); - } - return jws; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js -var SignJWT; -var init_sign4 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"() { - init_sign2(); - init_errors3(); - init_jwt_claims_set(); - SignJWT = class { - #protectedHeader; - #jwt; - constructor(payload = {}) { - this.#jwt = new JWTClaimsBuilder(payload); - } - setIssuer(issuer) { - this.#jwt.iss = issuer; - return this; - } - setSubject(subject) { - this.#jwt.sub = subject; - return this; - } - setAudience(audience) { - this.#jwt.aud = audience; - return this; - } - setJti(jwtId) { - this.#jwt.jti = jwtId; - return this; - } - setNotBefore(input) { - this.#jwt.nbf = input; - return this; - } - setExpirationTime(input) { - this.#jwt.exp = input; - return this; - } - setIssuedAt(input) { - this.#jwt.iat = input; - return this; - } - setProtectedHeader(protectedHeader) { - this.#protectedHeader = protectedHeader; - return this; - } - async sign(key, options) { - const sig = new CompactSign(this.#jwt.data()); - sig.setProtectedHeader(this.#protectedHeader); - if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - return sig.sign(key, options); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js -var EncryptJWT; -var init_encrypt4 = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js"() { - init_encrypt3(); - init_jwt_claims_set(); - init_helpers(); - EncryptJWT = class { - #cek; - #iv; - #keyManagementParameters; - #protectedHeader; - #replicateIssuerAsHeader; - #replicateSubjectAsHeader; - #replicateAudienceAsHeader; - #jwt; - constructor(payload = {}) { - this.#jwt = new JWTClaimsBuilder(payload); - } - setIssuer(issuer) { - this.#jwt.iss = issuer; - return this; - } - setSubject(subject) { - this.#jwt.sub = subject; - return this; - } - setAudience(audience) { - this.#jwt.aud = audience; - return this; - } - setJti(jwtId) { - this.#jwt.jti = jwtId; - return this; - } - setNotBefore(input) { - this.#jwt.nbf = input; - return this; - } - setExpirationTime(input) { - this.#jwt.exp = input; - return this; - } - setIssuedAt(input) { - this.#jwt.iat = input; - return this; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.#protectedHeader, "setProtectedHeader"); - this.#protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); - this.#keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - assertNotSet(this.#cek, "setContentEncryptionKey"); - this.#cek = cek; - return this; - } - setInitializationVector(iv) { - assertNotSet(this.#iv, "setInitializationVector"); - this.#iv = iv; - return this; - } - replicateIssuerAsHeader() { - this.#replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this.#replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this.#replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc = new CompactEncrypt(this.#jwt.data()); - if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) { - this.#protectedHeader = { - ...this.#protectedHeader, - iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0, - sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0, - aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0 - }; - } - enc.setProtectedHeader(this.#protectedHeader); - if (this.#iv) { - enc.setInitializationVector(this.#iv); - } - if (this.#cek) { - enc.setContentEncryptionKey(this.#cek); - } - if (this.#keyManagementParameters) { - enc.setKeyManagementParameters(this.#keyManagementParameters); - } - return enc.encrypt(key, options); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js -async function calculateJwkThumbprint(key, digestAlgorithm) { - let jwk; - if (isJWK(key)) { - jwk = key; - } else if (isKeyLike(key)) { - jwk = await exportJWK(key); - } else { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - digestAlgorithm ??= "sha256"; - if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case "AKP": - check2(jwk.alg, '"alg" (Algorithm) Parameter'); - check2(jwk.pub, '"pub" (Public key) Parameter'); - components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub }; - break; - case "EC": - check2(jwk.crv, '"crv" (Curve) Parameter'); - check2(jwk.x, '"x" (X Coordinate) Parameter'); - check2(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case "OKP": - check2(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check2(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case "RSA": - check2(jwk.e, '"e" (Exponent) Parameter'); - check2(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case "oct": - check2(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data = encode2(JSON.stringify(components)); - return encode3(await digest(digestAlgorithm, data)); -} -async function calculateJwkThumbprintUri(key, digestAlgorithm) { - digestAlgorithm ??= "sha256"; - const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm); - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; -} -var check2; -var init_thumbprint = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js"() { - init_helpers(); - init_base64url(); - init_errors3(); - init_buffer_utils(); - init_is_key_like(); - init_type_checks(); - init_export(); - init_invalid_key_input(); - check2 = (value, description) => { - if (typeof value !== "string" || !value) { - throw new JWKInvalid(`${description} missing or invalid`); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/embedded.js -async function EmbeddedJWK(protectedHeader, token) { - const joseHeader = { - ...protectedHeader, - ...token?.header - }; - if (!isObject2(joseHeader.jwk)) { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); - } - const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); - } - return key; -} -var init_embedded = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/embedded.js"() { - init_import(); - init_type_checks(); - init_errors3(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js -function getKtyFromAlg(alg) { - switch (typeof alg === "string" && alg.slice(0, 2)) { - case "RS": - case "PS": - return "RSA"; - case "ES": - return "EC"; - case "Ed": - return "OKP"; - case "ML": - return "AKP"; - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); -} -function isJWKLike(key) { - return isObject2(key); -} -async function importWithAlgCache(cache2, jwk, alg) { - const cached2 = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk); - if (cached2[alg] === void 0) { - const key = await importJWK({ ...jwk, ext: true }, alg); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWKSInvalid("JSON Web Key Set members must be public keys"); - } - cached2[alg] = key; - } - return cached2[alg]; -} -function createLocalJWKSet(jwks) { - const set2 = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => structuredClone(set2.jwks()), - enumerable: false, - configurable: false, - writable: false - } - }); - return localJWKSet; -} -var LocalJWKSet; -var init_local = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"() { - init_import(); - init_errors3(); - init_type_checks(); - LocalJWKSet = class { - #jwks; - #cached = /* @__PURE__ */ new WeakMap(); - constructor(jwks) { - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid("JSON Web Key Set malformed"); - } - this.#jwks = structuredClone(jwks); - } - jwks() { - return this.#jwks; - } - async getKey(protectedHeader, token) { - const { alg, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg); - const candidates = this.#jwks.keys.filter((jwk2) => { - let candidate = kty === jwk2.kty; - if (candidate && typeof kid === "string") { - candidate = kid === jwk2.kid; - } - if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) { - candidate = alg === jwk2.alg; - } - if (candidate && typeof jwk2.use === "string") { - candidate = jwk2.use === "sig"; - } - if (candidate && Array.isArray(jwk2.key_ops)) { - candidate = jwk2.key_ops.includes("verify"); - } - if (candidate) { - switch (alg) { - case "ES256": - candidate = jwk2.crv === "P-256"; - break; - case "ES384": - candidate = jwk2.crv === "P-384"; - break; - case "ES512": - candidate = jwk2.crv === "P-521"; - break; - case "Ed25519": - case "EdDSA": - candidate = jwk2.crv === "Ed25519"; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new JWKSNoMatchingKey(); - } - if (length !== 1) { - const error2 = new JWKSMultipleMatchingKeys(); - const _cached = this.#cached; - error2[Symbol.asyncIterator] = async function* () { - for (const jwk2 of candidates) { - try { - yield await importWithAlgCache(_cached, jwk2, alg); - } catch { - } - } - }; - throw error2; - } - return importWithAlgCache(this.#cached, jwk, alg); - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js -function isCloudflareWorkers() { - return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; -} -async function fetchJwks(url2, headers, signal, fetchImpl = fetch) { - const response = await fetchImpl(url2, { - method: "GET", - signal, - redirect: "manual", - headers - }).catch((err) => { - if (err.name === "TimeoutError") { - throw new JWKSTimeout(); - } - throw err; - }); - if (response.status !== 200) { - throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); - } - try { - return await response.json(); - } catch { - throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); - } -} -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== "object" || input === null) { - return false; - } - if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!("jwks" in input) || !isObject2(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject2)) { - return false; - } - return true; -} -function createRemoteJWKSet(url2, options) { - const set2 = new RemoteJWKSet(url2, options); - const remoteJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set2.coolingDown(), - enumerable: true, - configurable: false - }, - fresh: { - get: () => set2.fresh(), - enumerable: true, - configurable: false - }, - reload: { - value: () => set2.reload(), - enumerable: true, - configurable: false, - writable: false - }, - reloading: { - get: () => set2.pendingFetch(), - enumerable: true, - configurable: false - }, - jwks: { - value: () => set2.jwks(), - enumerable: true, - configurable: false, - writable: false - } - }); - return remoteJWKSet; -} -var USER_AGENT, customFetch, jwksCache, RemoteJWKSet; -var init_remote = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"() { - init_errors3(); - init_local(); - init_type_checks(); - if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { - const NAME = "jose"; - const VERSION = "v6.2.2"; - USER_AGENT = `${NAME}/${VERSION}`; - } - customFetch = /* @__PURE__ */ Symbol(); - jwksCache = /* @__PURE__ */ Symbol(); - RemoteJWKSet = class { - #url; - #timeoutDuration; - #cooldownDuration; - #cacheMaxAge; - #jwksTimestamp; - #pendingFetch; - #headers; - #customFetch; - #local; - #cache; - constructor(url2, options) { - if (!(url2 instanceof URL)) { - throw new TypeError("url must be an instance of URL"); - } - this.#url = new URL(url2.href); - this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; - this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; - this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; - this.#headers = new Headers(options?.headers); - if (USER_AGENT && !this.#headers.has("User-Agent")) { - this.#headers.set("User-Agent", USER_AGENT); - } - if (!this.#headers.has("accept")) { - this.#headers.set("accept", "application/json"); - this.#headers.append("accept", "application/jwk-set+json"); - } - this.#customFetch = options?.[customFetch]; - if (options?.[jwksCache] !== void 0) { - this.#cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { - this.#jwksTimestamp = this.#cache.uat; - this.#local = createLocalJWKSet(this.#cache.jwks); - } - } - } - pendingFetch() { - return !!this.#pendingFetch; - } - coolingDown() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false; - } - fresh() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false; - } - jwks() { - return this.#local?.jwks(); - } - async getKey(protectedHeader, token) { - if (!this.#local || !this.fresh()) { - await this.reload(); - } - try { - return await this.#local(protectedHeader, token); - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this.#local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this.#pendingFetch && isCloudflareWorkers()) { - this.#pendingFetch = void 0; - } - this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json2) => { - this.#local = createLocalJWKSet(json2); - if (this.#cache) { - this.#cache.uat = Date.now(); - this.#cache.jwks = json2; - } - this.#jwksTimestamp = Date.now(); - this.#pendingFetch = void 0; - }).catch((err) => { - this.#pendingFetch = void 0; - throw err; - }); - await this.#pendingFetch; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/unsecured.js -var UnsecuredJWT; -var init_unsecured = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/unsecured.js"() { - init_base64url(); - init_buffer_utils(); - init_errors3(); - init_jwt_claims_set(); - UnsecuredJWT = class { - #jwt; - constructor(payload = {}) { - this.#jwt = new JWTClaimsBuilder(payload); - } - encode() { - const header = encode3(JSON.stringify({ alg: "none" })); - const payload = encode3(this.#jwt.data()); - return `${header}.${payload}.`; - } - setIssuer(issuer) { - this.#jwt.iss = issuer; - return this; - } - setSubject(subject) { - this.#jwt.sub = subject; - return this; - } - setAudience(audience) { - this.#jwt.aud = audience; - return this; - } - setJti(jwtId) { - this.#jwt.jti = jwtId; - return this; - } - setNotBefore(input) { - this.#jwt.nbf = input; - return this; - } - setExpirationTime(input) { - this.#jwt.exp = input; - return this; - } - setIssuedAt(input) { - this.#jwt.iat = input; - return this; - } - static decode(jwt2, options) { - if (typeof jwt2 !== "string") { - throw new JWTInvalid("Unsecured JWT must be a string"); - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt2.split("."); - if (length !== 3 || signature !== "") { - throw new JWTInvalid("Invalid Unsecured JWT"); - } - let header; - try { - header = JSON.parse(decoder.decode(decode2(encodedHeader))); - if (header.alg !== "none") - throw new Error(); - } catch { - throw new JWTInvalid("Invalid Unsecured JWT"); - } - const payload = validateClaimsSet(header, decode2(encodedPayload), options); - return { payload, header }; - } - }; - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === "string") { - const parts = token.split("."); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; - } - } else if (typeof token === "object" && token) { - if ("protected" in token) { - protectedB64u = token.protected; - } else { - throw new TypeError("Token does not contain a Protected Header"); - } - } - try { - if (typeof protectedB64u !== "string" || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(decoder.decode(decode2(protectedB64u))); - if (!isObject2(result)) { - throw new Error(); - } - return result; - } catch { - throw new TypeError("Invalid Token or Protected Header formatting"); - } -} -var init_decode_protected_header = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js"() { - init_base64url(); - init_buffer_utils(); - init_type_checks(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js -function decodeJwt(jwt2) { - if (typeof jwt2 !== "string") - throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); - const { 1: payload, length } = jwt2.split("."); - if (length === 5) - throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); - if (length !== 3) - throw new JWTInvalid("Invalid JWT"); - if (!payload) - throw new JWTInvalid("JWTs must contain a payload"); - let decoded; - try { - decoded = decode2(payload); - } catch { - throw new JWTInvalid("Failed to base64url decode the payload"); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } catch { - throw new JWTInvalid("Failed to parse the decoded payload as JSON"); - } - if (!isObject2(result)) - throw new JWTInvalid("Invalid JWT Claims Set"); - return result; -} -var init_decode_jwt = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js"() { - init_base64url(); - init_buffer_utils(); - init_type_checks(); - init_errors3(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_key_pair.js -function getModulusLengthOption(options) { - const modulusLength = options?.modulusLength ?? 2048; - if (typeof modulusLength !== "number" || modulusLength < 2048) { - throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used"); - } - return modulusLength; -} -async function generateKeyPair(alg, options) { - let algorithm; - let keyUsages; - switch (alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { - name: "RSA-PSS", - hash: `SHA-${alg.slice(-3)}`, - publicExponent: Uint8Array.of(1, 0, 1), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["sign", "verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { - name: "RSASSA-PKCS1-v1_5", - hash: `SHA-${alg.slice(-3)}`, - publicExponent: Uint8Array.of(1, 0, 1), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["sign", "verify"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, - publicExponent: Uint8Array.of(1, 0, 1), - modulusLength: getModulusLengthOption(options) - }; - keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"]; - break; - case "ES256": - algorithm = { name: "ECDSA", namedCurve: "P-256" }; - keyUsages = ["sign", "verify"]; - break; - case "ES384": - algorithm = { name: "ECDSA", namedCurve: "P-384" }; - keyUsages = ["sign", "verify"]; - break; - case "ES512": - algorithm = { name: "ECDSA", namedCurve: "P-521" }; - keyUsages = ["sign", "verify"]; - break; - case "Ed25519": - case "EdDSA": { - keyUsages = ["sign", "verify"]; - algorithm = { name: "Ed25519" }; - break; - } - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": { - keyUsages = ["sign", "verify"]; - algorithm = { name: alg }; - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - keyUsages = ["deriveBits"]; - const crv = options?.crv ?? "P-256"; - switch (crv) { - case "P-256": - case "P-384": - case "P-521": { - algorithm = { name: "ECDH", namedCurve: crv }; - break; - } - case "X25519": - algorithm = { name: "X25519" }; - break; - default: - throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519"); - } - break; - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); -} -var init_generate_key_pair = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_key_pair.js"() { - init_errors3(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_secret.js -async function generateSecret(alg, options) { - let length; - let algorithm; - let keyUsages; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - length = parseInt(alg.slice(-3), 10); - algorithm = { name: "HMAC", hash: `SHA-${length}`, length }; - keyUsages = ["sign", "verify"]; - break; - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - length = parseInt(alg.slice(-3), 10); - return crypto.getRandomValues(new Uint8Array(length >> 3)); - case "A128KW": - case "A192KW": - case "A256KW": - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: "AES-KW", length }; - keyUsages = ["wrapKey", "unwrapKey"]; - break; - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": - case "A128GCM": - case "A192GCM": - case "A256GCM": - length = parseInt(alg.slice(1, 4), 10); - algorithm = { name: "AES-GCM", length }; - keyUsages = ["encrypt", "decrypt"]; - break; - default: - throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } - return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages); -} -var init_generate_secret = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/generate_secret.js"() { - init_errors3(); - } -}); - -// ../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js -var webapi_exports = {}; -__export(webapi_exports, { - CompactEncrypt: () => CompactEncrypt, - CompactSign: () => CompactSign, - EmbeddedJWK: () => EmbeddedJWK, - EncryptJWT: () => EncryptJWT, - FlattenedEncrypt: () => FlattenedEncrypt, - FlattenedSign: () => FlattenedSign, - GeneralEncrypt: () => GeneralEncrypt, - GeneralSign: () => GeneralSign, - SignJWT: () => SignJWT, - UnsecuredJWT: () => UnsecuredJWT, - base64url: () => base64url_exports, - calculateJwkThumbprint: () => calculateJwkThumbprint, - calculateJwkThumbprintUri: () => calculateJwkThumbprintUri, - compactDecrypt: () => compactDecrypt, - compactVerify: () => compactVerify, - createLocalJWKSet: () => createLocalJWKSet, - createRemoteJWKSet: () => createRemoteJWKSet, - cryptoRuntime: () => cryptoRuntime, - customFetch: () => customFetch, - decodeJwt: () => decodeJwt, - decodeProtectedHeader: () => decodeProtectedHeader, - errors: () => errors_exports2, - exportJWK: () => exportJWK, - exportPKCS8: () => exportPKCS8, - exportSPKI: () => exportSPKI, - flattenedDecrypt: () => flattenedDecrypt, - flattenedVerify: () => flattenedVerify, - generalDecrypt: () => generalDecrypt, - generalVerify: () => generalVerify, - generateKeyPair: () => generateKeyPair, - generateSecret: () => generateSecret, - importJWK: () => importJWK, - importPKCS8: () => importPKCS8, - importSPKI: () => importSPKI, - importX509: () => importX509, - jwksCache: () => jwksCache, - jwtDecrypt: () => jwtDecrypt, - jwtVerify: () => jwtVerify -}); -var cryptoRuntime; -var init_webapi = __esm({ - "../freya/node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"() { - init_decrypt2(); - init_decrypt(); - init_decrypt3(); - init_encrypt2(); - init_verify2(); - init_verify(); - init_verify3(); - init_verify4(); - init_decrypt4(); - init_encrypt3(); - init_encrypt(); - init_sign2(); - init_sign(); - init_sign3(); - init_sign4(); - init_encrypt4(); - init_thumbprint(); - init_embedded(); - init_local(); - init_remote(); - init_unsecured(); - init_export(); - init_import(); - init_decode_protected_header(); - init_decode_jwt(); - init_errors3(); - init_generate_key_pair(); - init_generate_secret(); - init_base64url(); - cryptoRuntime = "WebCryptoAPI"; - } -}); - -// ../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/index.mjs -var dist_exports = {}; -__export(dist_exports, { - AuthorizationServerMismatchError: () => AuthorizationServerMismatchError, - BAGGAGE_META_KEY: () => BAGGAGE_META_KEY, - CLIENT_CAPABILITIES_META_KEY: () => CLIENT_CAPABILITIES_META_KEY, - CLIENT_INFO_META_KEY: () => CLIENT_INFO_META_KEY, - Client: () => Client, - ClientCredentialsProvider: () => ClientCredentialsProvider, - CrossAppAccessProvider: () => CrossAppAccessProvider, - DEFAULT_NEGOTIATED_PROTOCOL_VERSION: () => DEFAULT_NEGOTIATED_PROTOCOL_VERSION, - DEFAULT_REQUEST_TIMEOUT_MSEC: () => DEFAULT_REQUEST_TIMEOUT_MSEC, - INTERNAL_ERROR: () => INTERNAL_ERROR, - INVALID_PARAMS: () => INVALID_PARAMS, - INVALID_REQUEST: () => INVALID_REQUEST, - InMemoryResponseCacheStore: () => InMemoryResponseCacheStore, - InMemoryTransport: () => InMemoryTransport, - InsecureTokenEndpointError: () => InsecureTokenEndpointError, - InsufficientScopeError: () => InsufficientScopeError, - IssuerMismatchError: () => IssuerMismatchError, - JSONRPC_VERSION: () => JSONRPC_VERSION, - LATEST_PROTOCOL_VERSION: () => LATEST_PROTOCOL_VERSION, - LOG_LEVEL_META_KEY: () => LOG_LEVEL_META_KEY, - MAX_CACHE_TTL_MS: () => MAX_CACHE_TTL_MS, - METHOD_NOT_FOUND: () => METHOD_NOT_FOUND, - MissingRequiredClientCapabilityError: () => MissingRequiredClientCapabilityError, - OAuthClientFlowError: () => OAuthClientFlowError, - OAuthError: () => OAuthError, - OAuthErrorCode: () => OAuthErrorCode, - PARSE_ERROR: () => PARSE_ERROR, - PROTOCOL_VERSION_META_KEY: () => PROTOCOL_VERSION_META_KEY, - PrivateKeyJwtProvider: () => PrivateKeyJwtProvider, - Protocol: () => Protocol, - ProtocolError: () => ProtocolError, - ProtocolErrorCode: () => ProtocolErrorCode, - RELATED_TASK_META_KEY: () => RELATED_TASK_META_KEY, - ReadBuffer: () => ReadBuffer, - RegistrationRejectedError: () => RegistrationRejectedError, - ResourceNotFoundError: () => ResourceNotFoundError, - SERVER_INFO_META_KEY: () => SERVER_INFO_META_KEY, - SSEClientTransport: () => SSEClientTransport, - STDIO_DEFAULT_MAX_BUFFER_SIZE: () => STDIO_DEFAULT_MAX_BUFFER_SIZE, - SUBSCRIPTION_ID_META_KEY: () => SUBSCRIPTION_ID_META_KEY, - SUPPORTED_PROTOCOL_VERSIONS: () => SUPPORTED_PROTOCOL_VERSIONS, - SdkError: () => SdkError, - SdkErrorCode: () => SdkErrorCode, - SdkHttpError: () => SdkHttpError, - SseError: () => SseError, - StaticPrivateKeyJwtProvider: () => StaticPrivateKeyJwtProvider, - StreamableHTTPClientTransport: () => StreamableHTTPClientTransport, - TRACEPARENT_META_KEY: () => TRACEPARENT_META_KEY, - TRACESTATE_META_KEY: () => TRACESTATE_META_KEY, - UnauthorizedError: () => UnauthorizedError, - UnsupportedProtocolVersionError: () => UnsupportedProtocolVersionError, - UriTemplate: () => UriTemplate, - UrlElicitationRequiredError: () => UrlElicitationRequiredError, - applyMiddlewares: () => applyMiddlewares, - assertCompleteRequestPrompt: () => assertCompleteRequestPrompt, - assertCompleteRequestResourceTemplate: () => assertCompleteRequestResourceTemplate, - assertSecureTokenEndpoint: () => assertSecureTokenEndpoint, - auth: () => auth, - buildDiscoveryUrls: () => buildDiscoveryUrls, - checkResourceAllowed: () => checkResourceAllowed, - computeScopeUnion: () => computeScopeUnion, - createFetchWithInit: () => createFetchWithInit, - createMiddleware: () => createMiddleware, - createPrivateKeyJwtAuth: () => createPrivateKeyJwtAuth, - deserializeMessage: () => deserializeMessage, - discoverAndRequestJwtAuthGrant: () => discoverAndRequestJwtAuthGrant, - discoverAuthorizationServerMetadata: () => discoverAuthorizationServerMetadata, - discoverOAuthMetadata: () => discoverOAuthMetadata, - discoverOAuthProtectedResourceMetadata: () => discoverOAuthProtectedResourceMetadata, - discoverOAuthServerInfo: () => discoverOAuthServerInfo, - exchangeAuthorization: () => exchangeAuthorization, - exchangeJwtAuthGrant: () => exchangeJwtAuthGrant, - extractResourceMetadataUrl: () => extractResourceMetadataUrl, - extractWWWAuthenticateParams: () => extractWWWAuthenticateParams, - fetchToken: () => fetchToken, - fromJsonSchema: () => fromJsonSchema2, - getDisplayName: () => getDisplayName, - getSupportedElicitationModes: () => getSupportedElicitationModes, - isCallToolResult: () => isCallToolResult, - isHttpsUrl: () => isHttpsUrl, - isInitializeRequest: () => isInitializeRequest, - isInitializedNotification: () => isInitializedNotification, - isInputRequiredResult: () => isInputRequiredResult, - isJSONRPCErrorResponse: () => isJSONRPCErrorResponse, - isJSONRPCNotification: () => isJSONRPCNotification, - isJSONRPCRequest: () => isJSONRPCRequest, - isJSONRPCResponse: () => isJSONRPCResponse, - isJSONRPCResultResponse: () => isJSONRPCResultResponse, - isJsonContentType: () => isJsonContentType, - isSpecType: () => isSpecType, - isStrictScopeSuperset: () => isStrictScopeSuperset, - isTaskAugmentedRequestParams: () => isTaskAugmentedRequestParams, - mergeCapabilities: () => mergeCapabilities, - parseErrorResponse: () => parseErrorResponse, - parseJSONRPCMessage: () => parseJSONRPCMessage, - preloadSchemas: () => preloadSchemas, - prepareAuthorizationCodeRequest: () => prepareAuthorizationCodeRequest, - refreshAuthorization: () => refreshAuthorization, - registerClient: () => registerClient, - requestJwtAuthorizationGrant: () => requestJwtAuthorizationGrant, - resolveClientMetadata: () => resolveClientMetadata, - resourceUrlFromServerUrl: () => resourceUrlFromServerUrl, - selectClientAuthMethod: () => selectClientAuthMethod, - selectResourceURL: () => selectResourceURL, - serializeMessage: () => serializeMessage, - specTypeSchemas: () => specTypeSchemas, - startAuthorization: () => startAuthorization, - validateAuthorizationResponseIssuer: () => validateAuthorizationResponseIssuer, - validateClientMetadataUrl: () => validateClientMetadataUrl, - withInputRequired: () => withInputRequired, - withLogging: () => withLogging, - withOAuth: () => withOAuth -}); -function discardIfIssuerMismatch(stored, issuer, opts) { - if (stored === void 0) return void 0; - if (stored.issuer === void 0) { - if (opts?.canPersistStamp !== false) console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."); - return stored; - } - return issuersMatch(stored.issuer, issuer) ? stored : void 0; -} -function issuersMatch(a, b) { - return a === b || a.endsWith("/") && a.slice(0, -1) === b || b.endsWith("/") && b.slice(0, -1) === a; -} -function isOAuthClientProvider(provider) { - if (provider == null) return false; - const p = provider; - return typeof p.tokens === "function" && typeof p.clientInformation === "function"; -} -async function handleOAuthUnauthorized(provider, ctx, extraAuthOptions) { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(ctx.response); - if (await auth(provider, { - serverUrl: ctx.serverUrl, - resourceMetadataUrl, - scope, - fetchFn: ctx.fetchFn, - ...extraAuthOptions - }) !== "AUTHORIZED") throw new UnauthorizedError(); -} -function adaptOAuthProvider(provider, extraAuthOptions) { - return { - token: async () => { - return (await provider.tokens())?.access_token; - }, - onUnauthorized: async (ctx) => handleOAuthUnauthorized(provider, ctx, extraAuthOptions) - }; -} -function isIssParameterSupported(metadata) { - return metadata?.authorization_response_iss_parameter_supported === true; -} -function validateAuthorizationResponseIssuer({ iss, expectedIssuer, issParameterSupported }) { - if (expectedIssuer === void 0) return; - if (iss === void 0) { - if (issParameterSupported) throw new IssuerMismatchError("authorization_response", expectedIssuer, void 0); - return; - } - if (iss !== expectedIssuer) throw new IssuerMismatchError("authorization_response", expectedIssuer, iss); -} -function computeScopeUnion(...scopes) { - const seen = /* @__PURE__ */ new Set(); - for (const scope of scopes) { - if (!scope) continue; - for (const token of scope.split(/\s+/)) if (token) seen.add(token); - } - return seen.size > 0 ? [...seen].join(" ") : void 0; -} -function isStrictScopeSuperset(union2, current) { - if (!union2) return false; - const currentSet = new Set((current ?? "").split(/\s+/).filter(Boolean)); - for (const token of union2.split(/\s+/)) if (token && !currentSet.has(token)) return true; - return false; -} -async function resolveAuthorizationCallbackParams(codeOrParams, iss, provider, serverUrl, opts) { - if (typeof codeOrParams === "string") return { - authorizationCode: codeOrParams, - iss - }; - const issParam = codeOrParams.get("iss") ?? void 0; - const code = codeOrParams.get("code"); - if (code) return { - authorizationCode: code, - iss: issParam - }; - let metadata = (await provider.discoveryState?.())?.authorizationServerMetadata; - if (!metadata) try { - metadata = (await discoverOAuthServerInfo(serverUrl, opts)).authorizationServerMetadata; - } catch { - metadata = void 0; - } - if (!metadata) throw new UnauthorizedError("Authorization callback failed and the issuer could not be verified"); - validateAuthorizationResponseIssuer({ - iss: issParam, - expectedIssuer: metadata.issuer, - issParameterSupported: isIssParameterSupported(metadata) - }); - const error2 = codeOrParams.get("error"); - if (error2) throw new OAuthError(error2, codeOrParams.get("error_description") ?? error2, codeOrParams.get("error_uri") ?? void 0); - throw new UnauthorizedError("Authorization callback contained neither `code` nor `error`"); -} -function isClientAuthMethod(method) { - return [ - "client_secret_basic", - "client_secret_post", - "none" - ].includes(method); -} -function selectClientAuthMethod(clientInformation, supportedMethods) { - const hasClientSecret = clientInformation.client_secret !== void 0; - if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) return clientInformation.token_endpoint_auth_method; - if (supportedMethods.length === 0) return hasClientSecret ? "client_secret_basic" : "none"; - if (hasClientSecret && supportedMethods.includes("client_secret_basic")) return "client_secret_basic"; - if (hasClientSecret && supportedMethods.includes("client_secret_post")) return "client_secret_post"; - if (supportedMethods.includes("none")) return "none"; - return hasClientSecret ? "client_secret_post" : "none"; -} -function applyClientAuthentication(method, clientInformation, headers, params) { - const { client_id, client_secret } = clientInformation; - switch (method) { - case "client_secret_basic": - applyBasicAuth(client_id, client_secret, headers); - return; - case "client_secret_post": - applyPostAuth(client_id, client_secret, params); - return; - case "none": - applyPublicAuth(client_id, params); - return; - default: - throw new Error(`Unsupported client authentication method: ${method}`); - } -} -function applyBasicAuth(clientId, clientSecret, headers) { - if (!clientSecret) throw new Error("client_secret_basic authentication requires a client_secret"); - const credentials = btoa(`${clientId}:${clientSecret}`); - headers.set("Authorization", `Basic ${credentials}`); -} -function applyPostAuth(clientId, clientSecret, params) { - params.set("client_id", clientId); - if (clientSecret) params.set("client_secret", clientSecret); -} -function applyPublicAuth(clientId, params) { - params.set("client_id", clientId); -} -function isLoopbackHost(hostname3) { - return hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "[::1]" || hostname3 === "::1"; -} -function assertSecureTokenEndpoint(tokenEndpoint) { - const url2 = new URL(String(tokenEndpoint)); - if (url2.protocol !== "https:" && !isLoopbackHost(url2.hostname)) throw new InsecureTokenEndpointError(url2.href); - return url2; -} -function deriveApplicationType(redirectUris) { - for (const raw of redirectUris ?? []) { - let url2; - try { - url2 = new URL(raw); - } catch { - continue; - } - if (url2.protocol !== "http:" && url2.protocol !== "https:") return "native"; - if (isLoopbackHost(url2.hostname)) return "native"; - } - return "web"; -} -function resolveClientMetadata(provider) { - const clientMetadata = provider.clientMetadata; - return { - ...clientMetadata, - grant_types: clientMetadata.grant_types ?? (provider.redirectUrl === void 0 ? void 0 : ["authorization_code", "refresh_token"]), - application_type: clientMetadata.application_type ?? deriveApplicationType(clientMetadata.redirect_uris) - }; -} -async function parseErrorResponse(input) { - const statusCode = input instanceof Response ? input.status : void 0; - const body = input instanceof Response ? await input.text() : input; - try { - const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); - return OAuthError.fromResponse(result); - } catch (error2) { - const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error2}. Raw body: ${body}`; - return new OAuthError(OAuthErrorCode.ServerError, errorMessage); - } -} -async function auth(provider, options) { - try { - return await authInternal(provider, options); - } catch (error2) { - if (error2 instanceof OAuthError) { - if (error2.code === OAuthErrorCode.InvalidClient || error2.code === OAuthErrorCode.UnauthorizedClient) { - await provider.invalidateCredentials?.("client"); - await provider.invalidateCredentials?.("tokens"); - return await authInternal(provider, options); - } else if (error2.code === OAuthErrorCode.InvalidGrant) { - await provider.invalidateCredentials?.("tokens"); - return await authInternal(provider, options); - } - } - throw error2; - } -} -function determineScope(options) { - const { requestedScope, resourceMetadata, authServerMetadata, clientMetadata } = options; - let effectiveScope = requestedScope || resourceMetadata?.scopes_supported?.join(" ") || clientMetadata.scope; - if (effectiveScope && authServerMetadata?.scopes_supported?.includes("offline_access") && !effectiveScope.split(" ").includes("offline_access") && clientMetadata.grant_types?.includes("refresh_token")) effectiveScope = `${effectiveScope} offline_access`; - return effectiveScope; -} -async function authInternal(provider, { serverUrl, authorizationCode, iss, scope, resourceMetadataUrl, fetchFn, skipIssuerMetadataValidation, forceReauthorization }) { - const clientMetadata = resolveClientMetadata(provider); - const cachedState = await provider.discoveryState?.(); - let resourceMetadata; - let authorizationServerUrl; - let metadata; - let freshDiscoveryState; - let effectiveResourceMetadataUrl = resourceMetadataUrl; - if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl); - if (cachedState?.authorizationServerUrl) { - authorizationServerUrl = cachedState.authorizationServerUrl; - resourceMetadata = cachedState.resourceMetadata; - metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { - fetchFn, - skipIssuerValidation: skipIssuerMetadataValidation - }); - if (!resourceMetadata) try { - resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn); - } catch (error2) { - if (error2 instanceof TypeError) throw error2; - } - if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) await provider.saveDiscoveryState?.({ - authorizationServerUrl: String(authorizationServerUrl), - resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), - resourceMetadata, - authorizationServerMetadata: metadata - }); - } else { - const serverInfo = await discoverOAuthServerInfo(serverUrl, { - resourceMetadataUrl: effectiveResourceMetadataUrl, - fetchFn, - skipIssuerMetadataValidation - }); - authorizationServerUrl = serverInfo.authorizationServerUrl; - metadata = serverInfo.authorizationServerMetadata; - resourceMetadata = serverInfo.resourceMetadata; - freshDiscoveryState = { - authorizationServerUrl: String(authorizationServerUrl), - resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), - resourceMetadata, - authorizationServerMetadata: metadata - }; - } - const issuer = metadata?.issuer ?? String(authorizationServerUrl); - const infoCtx = { issuer }; - await provider.saveAuthorizationServerUrl?.(issuer); - if (authorizationCode !== void 0) { - const recordedIssuer = cachedState?.authorizationServerMetadata?.issuer ?? cachedState?.authorizationServerUrl; - if (recordedIssuer === void 0) { - if (provider.saveDiscoveryState !== void 0) throw new AuthorizationServerMismatchError("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier", issuer); - console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352."); - } else if (!issuersMatch(recordedIssuer, issuer)) throw new AuthorizationServerMismatchError(recordedIssuer, issuer); - } - if (freshDiscoveryState) await provider.saveDiscoveryState?.(freshDiscoveryState); - const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); - if (resource) await provider.saveResourceUrl?.(String(resource)); - const resolvedScope = determineScope({ - requestedScope: scope, - resourceMetadata, - authServerMetadata: metadata, - clientMetadata: provider.clientMetadata - }); - const rawClientInfo = await Promise.resolve(provider.clientInformation(infoCtx)); - let clientInformation = discardIfIssuerMismatch(rawClientInfo, issuer, { canPersistStamp: provider.saveClientInformation !== void 0 }); - if (clientInformation === void 0 && rawClientInfo?.issuer && provider.saveClientInformation === void 0) throw new AuthorizationServerMismatchError(rawClientInfo.issuer, issuer); - if (clientInformation && clientInformation.issuer === void 0) { - clientInformation = { - ...clientInformation, - issuer - }; - await provider.saveClientInformation?.(clientInformation, infoCtx); - } - if (!clientInformation) { - if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code"); - const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true; - const clientMetadataUrl = provider.clientMetadataUrl; - if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) throw new OAuthError(OAuthErrorCode.InvalidClientMetadata, `clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); - if (supportsUrlBasedClientId && clientMetadataUrl) { - clientInformation = { - client_id: clientMetadataUrl, - issuer - }; - await provider.saveClientInformation?.(clientInformation, infoCtx); - } else { - if (!provider.saveClientInformation) throw new Error("OAuth client information must be saveable for dynamic registration"); - clientInformation = { - ...await registerClient(authorizationServerUrl, { - metadata, - clientMetadata, - scope: resolvedScope, - fetchFn - }), - issuer - }; - await provider.saveClientInformation(clientInformation, infoCtx); - } - } - const nonInteractiveFlow = !provider.redirectUrl; - if (authorizationCode !== void 0 || nonInteractiveFlow) { - if (authorizationCode !== void 0) validateAuthorizationResponseIssuer({ - iss, - expectedIssuer: metadata?.issuer, - issParameterSupported: isIssParameterSupported(metadata) - }); - const tokens$1 = await fetchToken(provider, authorizationServerUrl, { - metadata, - resource, - authorizationCode, - iss, - scope: resolvedScope, - fetchFn - }); - await provider.saveTokens({ - ...tokens$1, - issuer - }, infoCtx); - return "AUTHORIZED"; - } - let tokens = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer); - if (tokens && tokens.issuer === void 0) { - tokens = { - ...tokens, - issuer - }; - await provider.saveTokens(tokens, infoCtx); - } - if (tokens?.refresh_token && !forceReauthorization) try { - const newTokens = await refreshAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - refreshToken: tokens.refresh_token, - resource, - addClientAuthentication: provider.addClientAuthentication, - fetchFn - }); - await provider.saveTokens({ - ...newTokens, - issuer - }, infoCtx); - return "AUTHORIZED"; - } catch (error2) { - if (error2 instanceof InsecureTokenEndpointError) throw error2; - if (!(error2 instanceof OAuthError) || error2.code === OAuthErrorCode.ServerError) { - } else throw error2; - } - const state = provider.state ? await provider.state() : void 0; - const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - state, - redirectUrl: provider.redirectUrl, - scope: resolvedScope, - resource - }); - await provider.saveCodeVerifier(codeVerifier); - await provider.redirectToAuthorization(authorizationUrl); - return "REDIRECT"; -} -function validateClientMetadataUrl(url2) { - if (url2 && !isHttpsUrl(url2)) throw new OAuthError(OAuthErrorCode.InvalidClientMetadata, `clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${url2}`); -} -function isHttpsUrl(value) { - if (!value) return false; - try { - const url2 = new URL(value); - return url2.protocol === "https:" && url2.pathname !== "/"; - } catch { - return false; - } -} -async function selectResourceURL(serverUrl, provider, resourceMetadata) { - const defaultResource = resourceUrlFromServerUrl(serverUrl); - if (provider.validateResourceURL) return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); - if (!resourceMetadata) return; - if (!checkResourceAllowed({ - requestedResource: defaultResource, - configuredResource: resourceMetadata.resource - })) throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); - return new URL(resourceMetadata.resource); -} -function extractWWWAuthenticateParams(res) { - const authenticateHeader = res.headers.get("WWW-Authenticate"); - if (!authenticateHeader) return {}; - const [type, scheme] = authenticateHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !scheme) return {}; - const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0; - let resourceMetadataUrl; - if (resourceMetadataMatch) try { - resourceMetadataUrl = new URL(resourceMetadataMatch); - } catch { - } - const scope = extractFieldFromWwwAuth(res, "scope") || void 0; - const error2 = extractFieldFromWwwAuth(res, "error") || void 0; - const errorDescription = extractFieldFromWwwAuth(res, "error_description") || void 0; - return { - resourceMetadataUrl, - scope, - error: error2, - errorDescription - }; -} -function extractFieldFromWwwAuth(response, fieldName) { - const wwwAuthHeader = response.headers.get("WWW-Authenticate"); - if (!wwwAuthHeader) return null; - const pattern = new RegExp(String.raw`${fieldName}=(?:"([^"]+)"|([^\s,]+))`); - const match = wwwAuthHeader.match(pattern); - if (match) { - const result = match[1] || match[2]; - if (result) return result; - } - return null; -} -function extractResourceMetadataUrl(res) { - const authenticateHeader = res.headers.get("WWW-Authenticate"); - if (!authenticateHeader) return; - const [type, scheme] = authenticateHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !scheme) return; - const match = /resource_metadata="([^"]*)"/.exec(authenticateHeader); - if (!match || !match[1]) return; - try { - return new URL(match[1]); - } catch { - return; - } -} -async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { - const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, { - protocolVersion: opts?.protocolVersion, - metadataUrl: opts?.resourceMetadataUrl - }); - if (!response || response.status === 404) { - await response?.text?.().catch(() => { - }); - throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); - } - if (!response.ok) { - await response.text?.().catch(() => { - }); - throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); - } - return OAuthProtectedResourceMetadataSchema.parse(await response.json()); -} -async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) { - try { - return await fetchFn(url2, { headers }); - } catch (error2) { - if (!(error2 instanceof TypeError) || !CORS_IS_POSSIBLE) throw error2; - if (headers) try { - return await fetchFn(url2, {}); - } catch (retryError) { - if (!(retryError instanceof TypeError)) throw retryError; - return; - } - return; - } -} -function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) { - if (pathname.endsWith("/")) pathname = pathname.slice(0, -1); - return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; -} -async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) { - return await fetchWithCorsRetry(url2, { "MCP-Protocol-Version": protocolVersion }, fetchFn); -} -function shouldAttemptFallback(response, pathname) { - if (!response) return true; - if (pathname === "/") return false; - return response.status >= 400 && response.status < 500 || response.status === 502; -} -async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { - const issuer = new URL(serverUrl); - const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION; - let url2; - if (opts?.metadataUrl) url2 = new URL(opts.metadataUrl); - else { - const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); - url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); - url2.search = issuer.search; - } - let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn); - if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) response = await tryMetadataDiscovery(new URL(`/.well-known/${wellKnownType}`, issuer), protocolVersion, fetchFn); - return response; -} -async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { - if (typeof issuer === "string") issuer = new URL(issuer); - if (!authorizationServerUrl) authorizationServerUrl = issuer; - if (typeof authorizationServerUrl === "string") authorizationServerUrl = new URL(authorizationServerUrl); - protocolVersion ??= LATEST_PROTOCOL_VERSION; - const response = await discoverMetadataWithFallback(authorizationServerUrl, "oauth-authorization-server", fetchFn, { - protocolVersion, - metadataServerUrl: authorizationServerUrl - }); - if (!response || response.status === 404) { - await response?.text?.().catch(() => { - }); - return; - } - if (!response.ok) { - await response.text?.().catch(() => { - }); - throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); - } - return OAuthMetadataSchema.parse(await response.json()); -} -function buildDiscoveryUrls(authorizationServerUrl) { - const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl; - const hasPath = url2.pathname !== "/"; - const urlsToTry = []; - if (!hasPath) { - urlsToTry.push({ - url: new URL("/.well-known/oauth-authorization-server", url2.origin), - type: "oauth" - }, { - url: new URL(`/.well-known/openid-configuration`, url2.origin), - type: "oidc" - }); - return urlsToTry; - } - let pathname = url2.pathname; - if (pathname.endsWith("/")) pathname = pathname.slice(0, -1); - urlsToTry.push({ - url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin), - type: "oauth" - }, { - url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin), - type: "oidc" - }, { - url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin), - type: "oidc" - }); - return urlsToTry; -} -async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION, skipIssuerValidation = false } = {}) { - const headers = { - "MCP-Protocol-Version": protocolVersion, - Accept: "application/json" - }; - const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); - for (const { url: endpointUrl, type } of urlsToTry) { - const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); - if (!response) - continue; - if (!response.ok) { - await response.text?.().catch(() => { - }); - if (response.status >= 400 && response.status < 500 || response.status === 502) continue; - throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`); - } - const parsed = type === "oauth" ? OAuthMetadataSchema.parse(await response.json()) : OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); - if (!skipIssuerValidation) { - const expectedIssuer = typeof authorizationServerUrl === "string" ? authorizationServerUrl : authorizationServerUrl.href; - if (!(parsed.issuer === expectedIssuer || expectedIssuer.endsWith("/") && parsed.issuer === expectedIssuer.slice(0, -1))) throw new IssuerMismatchError("metadata", expectedIssuer, parsed.issuer); - } - return parsed; - } -} -async function discoverOAuthServerInfo(serverUrl, opts) { - let resourceMetadata; - let authorizationServerUrl; - try { - resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn); - if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) authorizationServerUrl = resourceMetadata.authorization_servers[0]; - } catch (error2) { - if (error2 instanceof TypeError) throw error2; - } - if (!authorizationServerUrl) authorizationServerUrl = String(new URL("/", serverUrl)); - const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { - fetchFn: opts?.fetchFn, - skipIssuerValidation: opts?.skipIssuerMetadataValidation - }); - return { - authorizationServerUrl, - authorizationServerMetadata, - resourceMetadata - }; -} -async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { - let authorizationUrl; - if (metadata) { - authorizationUrl = new URL(metadata.authorization_endpoint); - if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); - if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); - } else authorizationUrl = new URL("/authorize", authorizationServerUrl); - const challenge = await pkceChallenge(); - const codeVerifier = challenge.code_verifier; - const codeChallenge = challenge.code_challenge; - authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE); - authorizationUrl.searchParams.set("client_id", clientInformation.client_id); - authorizationUrl.searchParams.set("code_challenge", codeChallenge); - authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD); - authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl)); - if (state) authorizationUrl.searchParams.set("state", state); - if (scope) authorizationUrl.searchParams.set("scope", scope); - if (scope?.split(" ").includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent"); - if (resource) authorizationUrl.searchParams.set("resource", resource.href); - return { - authorizationUrl, - codeVerifier - }; -} -function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { - return new URLSearchParams({ - grant_type: "authorization_code", - code: authorizationCode, - code_verifier: codeVerifier, - redirect_uri: String(redirectUri) - }); -} -async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { - const tokenUrl = assertSecureTokenEndpoint(metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl)); - const headers = new Headers({ - "Content-Type": "application/x-www-form-urlencoded", - Accept: "application/json" - }); - if (resource) tokenRequestParams.set("resource", resource.href); - if (addClientAuthentication) await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); - else if (clientInformation) applyClientAuthentication(selectClientAuthMethod(clientInformation, metadata?.token_endpoint_auth_methods_supported ?? []), clientInformation, headers, tokenRequestParams); - const response = await (fetchFn ?? fetch)(tokenUrl, { - method: "POST", - headers, - body: tokenRequestParams - }); - if (!response.ok) throw await parseErrorResponse(response); - const json2 = await response.json(); - try { - return OAuthTokensSchema.parse(json2); - } catch (parseError) { - if (typeof json2 === "object" && json2 !== null && "error" in json2) throw await parseErrorResponse(JSON.stringify(json2)); - throw parseError; - } -} -async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, iss, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { - validateAuthorizationResponseIssuer({ - iss, - expectedIssuer: metadata?.issuer, - issParameterSupported: isIssParameterSupported(metadata) - }); - return executeTokenRequest(authorizationServerUrl, { - metadata, - tokenRequestParams: prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri), - clientInformation, - addClientAuthentication, - resource, - fetchFn - }); -} -async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { - return { - refresh_token: refreshToken, - ...await executeTokenRequest(authorizationServerUrl, { - metadata, - tokenRequestParams: new URLSearchParams({ - grant_type: "refresh_token", - refresh_token: refreshToken - }), - clientInformation, - addClientAuthentication, - resource, - fetchFn - }) - }; -} -async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, iss, scope, fetchFn } = {}) { - if (authorizationCode !== void 0) validateAuthorizationResponseIssuer({ - iss, - expectedIssuer: metadata?.issuer, - issParameterSupported: isIssParameterSupported(metadata) - }); - const effectiveScope = scope ?? provider.clientMetadata.scope; - let tokenRequestParams; - if (provider.prepareTokenRequest) tokenRequestParams = await provider.prepareTokenRequest(effectiveScope); - if (!tokenRequestParams) { - if (!authorizationCode) throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required"); - if (!provider.redirectUrl) throw new Error("redirectUrl is required for authorization_code flow"); - tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, await provider.codeVerifier(), provider.redirectUrl); - } - const clientInformation = await provider.clientInformation({ issuer: metadata?.issuer ?? String(authorizationServerUrl) }); - return executeTokenRequest(authorizationServerUrl, { - metadata, - tokenRequestParams, - clientInformation: clientInformation ?? void 0, - addClientAuthentication: provider.addClientAuthentication, - resource, - fetchFn - }); -} -async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) { - let registrationUrl; - if (metadata) { - if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration"); - registrationUrl = new URL(metadata.registration_endpoint); - } else registrationUrl = new URL("/register", authorizationServerUrl); - const submittedMetadata = { - ...clientMetadata, - ...scope === void 0 ? {} : { scope } - }; - const response = await (fetchFn ?? fetch)(registrationUrl, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(submittedMetadata) - }); - if (!response.ok) throw new RegistrationRejectedError({ - status: response.status, - body: await response.text(), - submittedMetadata - }); - return OAuthClientInformationFullSchema.parse(await response.json()); -} -function createPrivateKeyJwtAuth(options) { - return async (_headers, params, url2, metadata) => { - if (globalThis.crypto === void 0) throw new TypeError("crypto is not available, please ensure you have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)"); - const jose = await Promise.resolve().then(() => (init_webapi(), webapi_exports)); - const audience = String(options.audience ?? metadata?.issuer ?? url2); - const lifetimeSeconds = options.lifetimeSeconds ?? 300; - const now = Math.floor(Date.now() / 1e3); - const jti = `${Date.now()}-${Math.random().toString(36).slice(2)}`; - const baseClaims = { - iss: options.issuer, - sub: options.subject, - aud: audience, - exp: now + lifetimeSeconds, - iat: now, - jti - }; - const claims = options.claims ? { - ...baseClaims, - ...options.claims - } : baseClaims; - const alg = options.alg; - let key; - if (typeof options.privateKey === "string") if (alg.startsWith("RS") || alg.startsWith("ES") || alg.startsWith("PS")) key = await jose.importPKCS8(options.privateKey, alg); - else if (alg.startsWith("HS")) key = new TextEncoder().encode(options.privateKey); - else throw new Error(`Unsupported algorithm ${alg}`); - else if (options.privateKey instanceof Uint8Array) key = alg.startsWith("HS") ? options.privateKey : await jose.importPKCS8(new TextDecoder().decode(options.privateKey), alg); - else key = await jose.importJWK(options.privateKey, alg); - const assertion = await new jose.SignJWT(claims).setProtectedHeader({ - alg, - typ: "JWT" - }).setIssuer(options.issuer).setSubject(options.subject).setAudience(audience).setIssuedAt(now).setExpirationTime(now + lifetimeSeconds).setJti(jti).sign(key); - params.set("client_assertion", assertion); - params.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); - }; -} -function keyOf(key) { - return `${key.method}\0${JSON.stringify([key.partition ?? "", key.params ?? ""])}`; -} -function genKey(method, params) { - return params === void 0 ? method : `${method}\0${params}`; -} -function encodeCacheValue(value) { - let json2; - try { - json2 = JSON.stringify(value); - } catch (error2) { - throw new TypeError(`cache value is not JSON-serializable: ${error2 instanceof Error ? error2.message : String(error2)}`); - } - if (typeof json2 !== "string") throw new TypeError("cache value is not JSON-serializable: it has no JSON representation"); - return json2; -} -function classifyProbeOutcome(outcome, context) { - switch (outcome.kind) { - case "result": - return classifyResult(outcome.result, context); - case "rpc-error": - return classifyRpcError(outcome, context); - case "http-error": - return classifyHttpError(outcome, context); - case "network-error": - return classifyNetworkError(outcome.error, context); - case "auth-required": - return { - kind: "error", - error: outcome.error - }; - case "closed": - if (context.transportKind === "stdio") return { kind: "legacy" }; - return classifyNetworkError(/* @__PURE__ */ new Error("Connection closed during the version negotiation probe"), context); - case "timeout": - if (context.transportKind === "stdio") return { kind: "legacy" }; - return { - kind: "error", - error: new SdkError(SdkErrorCode.RequestTimeout, `Version negotiation probe timed out after ${outcome.timeoutMs}ms`, { timeout: outcome.timeoutMs }) - }; - } -} -function classifyResult(result, context) { - const parsed = codecForVersion(MODERN_WIRE_REVISION).validateResult("server/discover", result); - if (!parsed.ok) return { kind: "legacy" }; - const supportedVersions = parsed.value.supportedVersions; - const overlap = context.clientModernVersions.find((version2) => supportedVersions.includes(version2)); - if (overlap !== void 0) return { - kind: "modern", - version: overlap, - discover: parsed.value - }; - if (context.fallbackAvailable) return { kind: "legacy" }; - return { - kind: "error", - error: new UnsupportedProtocolVersionError({ - supported: [...supportedVersions], - requested: context.requestedVersion - }) - }; -} -function classifyRpcError(outcome, context) { - const { code, message: message2, data } = outcome; - if (code === UNSUPPORTED_PROTOCOL_VERSION) { - const supported2 = parseSupportedList(data); - if (supported2 === void 0) return { kind: "legacy" }; - const error2 = new UnsupportedProtocolVersionError({ - supported: supported2, - requested: parseRequested(data) ?? context.requestedVersion - }, message2); - const supportedModern = modernProtocolVersions(supported2); - const mutual = context.clientModernVersions.find((version2) => supportedModern.includes(version2)); - if (mutual !== void 0) return { - kind: "corrective", - version: mutual, - error: error2 - }; - if (supportedModern.length > 0) return { - kind: "error", - error: error2 - }; - return context.fallbackAvailable ? { kind: "legacy" } : { - kind: "error", - error: error2 - }; - } - if (NOT_PROBE_RECOGNIZED.has(code)) return { kind: "legacy" }; - return { kind: "legacy" }; -} -function classifyHttpError(outcome, context) { - const rpcError = parseJsonRpcErrorBody(outcome.body); - if (rpcError !== void 0) return classifyRpcError(rpcError, context); - return { kind: "legacy" }; -} -function classifyNetworkError(error2, context) { - if (context.environment === "browser" && isOpaqueFetchTypeError(error2)) return { kind: "legacy" }; - return { - kind: "error", - error: new SdkError(SdkErrorCode.EraNegotiationFailed, `Version negotiation probe failed: ${describeError(error2)}`, { cause: error2 }) - }; -} -function isOpaqueFetchTypeError(error2) { - return error2 instanceof TypeError || error2 instanceof Error && error2.name === "TypeError"; -} -function describeError(error2) { - return error2 instanceof Error ? error2.message : String(error2); -} -function parseSupportedList(data) { - if (typeof data !== "object" || data === null) return void 0; - const supported2 = data.supported; - if (!Array.isArray(supported2) || supported2.length === 0 || !supported2.every((v) => typeof v === "string")) return; - return supported2; -} -function parseRequested(data) { - if (typeof data !== "object" || data === null) return void 0; - const requested = data.requested; - return typeof requested === "string" ? requested : void 0; -} -function parseJsonRpcErrorBody(body) { - if (body === void 0 || body === "") return void 0; - let parsed; - try { - parsed = JSON.parse(body); - } catch { - return; - } - if (typeof parsed !== "object" || parsed === null) return void 0; - const error2 = parsed.error; - if (typeof error2 !== "object" || error2 === null) return void 0; - const { code, message: message2, data } = error2; - if (typeof code !== "number") return void 0; - return { - code, - message: typeof message2 === "string" ? message2 : "", - data - }; -} -function resolveVersionNegotiation(options, supportedProtocolVersionsOption) { - const mode = options?.mode ?? DEFAULT_VERSION_NEGOTIATION_MODE; - if (mode === "legacy") return { kind: "legacy" }; - const probe = options?.probe ?? {}; - if (typeof mode === "object") { - if (!isModernProtocolVersion(mode.pin)) throw new TypeError(`versionNegotiation: { pin: '${mode.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`); - return { - kind: "pin", - version: mode.pin, - probe - }; - } - const explicitModern = supportedProtocolVersionsOption ? modernProtocolVersions(supportedProtocolVersionsOption) : []; - return { - kind: "auto", - modernVersions: explicitModern.length > 0 ? explicitModern : [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - fallbackAvailable: supportedProtocolVersionsOption ? legacyProtocolVersions(supportedProtocolVersionsOption).length > 0 : true, - probe - }; -} -function detectProbeEnvironment() { - const g = globalThis; - return g.window !== void 0 && g.document !== void 0 ? "browser" : "node"; -} -function detectProbeTransportKind(transport) { - return "stderr" in transport && "pid" in transport ? "stdio" : "http"; -} -function disarmSpentCloseGuard(transport) { - const disarm = pendingSpentCloseGuards.get(transport); - pendingSpentCloseGuards.delete(transport); - disarm?.(); -} -function buildProbeRequest(id, protocolVersion, clientInfo, capabilities) { - return { - jsonrpc: "2.0", - id, - method: "server/discover", - params: { _meta: codecForVersion(protocolVersion).outboundEnvelope({ - protocolVersion, - clientInfo, - clientCapabilities: capabilities - }) } - }; -} -function normalizeReply(reply, timeoutMs) { - switch (reply.kind) { - case "response": - return reply.error === void 0 ? { - kind: "result", - result: reply.result - } : { - kind: "rpc-error", - ...reply.error - }; - case "send-error": { - const error2 = reply.error; - if (error2 instanceof SdkHttpError) { - const text = error2.data?.text; - return { - kind: "http-error", - status: error2.data.status, - body: typeof text === "string" ? text : void 0 - }; - } - if (error2 instanceof UnauthorizedError || error2 instanceof Error && error2.name === "UnauthorizedError") return { - kind: "auth-required", - error: error2 - }; - return { - kind: "network-error", - error: error2 - }; - } - case "closed": - return { kind: "closed" }; - case "timeout": - return { - kind: "timeout", - timeoutMs - }; - } -} -async function negotiateEra(negotiation, deps) { - const timeoutMs = negotiation.probe.timeoutMs ?? deps.defaultTimeoutMs; - const maxRetries = Math.max(0, negotiation.probe.maxRetries ?? 0); - const clientModernVersions = negotiation.kind === "pin" ? [negotiation.version] : negotiation.modernVersions; - const fallbackAvailable = negotiation.kind === "auto" && negotiation.fallbackAvailable; - const window = await ProbeWindow.open(deps.transport); - const probe = async () => { - let requestedVersion = clientModernVersions[0]; - let correctiveUsed = false; - let timeoutRetriesRemaining = maxRetries; - for (; ; ) { - const reply = await window.exchange((id) => buildProbeRequest(id, requestedVersion, deps.clientInfo, deps.capabilities), timeoutMs); - if (reply.kind === "timeout" && timeoutRetriesRemaining > 0) { - timeoutRetriesRemaining--; - continue; - } - const outcome = normalizeReply(reply, timeoutMs); - const verdict = classifyProbeOutcome(outcome, { - clientModernVersions, - requestedVersion, - fallbackAvailable, - environment: deps.environment, - transportKind: deps.transportKind - }); - switch (verdict.kind) { - case "modern": - return { - era: "modern", - version: verdict.version, - discover: verdict.discover - }; - case "corrective": - if (correctiveUsed) throw verdict.error; - correctiveUsed = true; - requestedVersion = verdict.version; - continue; - case "legacy": { - const closedCause = outcome.kind === "closed" ? "the connection closed during the server/discover probe" : void 0; - if (negotiation.kind === "pin") throw new SdkError(SdkErrorCode.EraNegotiationFailed, closedCause === void 0 ? `Version negotiation failed: the server did not offer pinned protocol version ${negotiation.version} via server/discover (no fallback in pin mode)` : `Version negotiation failed: ${closedCause} before the server offered pinned protocol version ${negotiation.version} (no fallback in pin mode)`); - if (!negotiation.fallbackAvailable) throw new SdkError(SdkErrorCode.EraNegotiationFailed, closedCause === void 0 ? "Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to" : `Version negotiation failed: ${closedCause} and this client supports no pre-2026-07-28 protocol version to fall back to`); - if (closedCause !== void 0 && deps.disposableProbe !== true) throw new SdkError(SdkErrorCode.EraNegotiationFailed, `Version negotiation failed: ${closedCause} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`); - return { era: "legacy" }; - } - case "error": - throw verdict.error; - } - } - }; - let result; - try { - result = await probe(); - } catch (error2) { - window.detach(); - throw error2; - } - window.release(); - return result; -} -function readStdioServerParams(transport) { - const proto = Object.getPrototypeOf(transport); - if (proto === null || !Object.prototype.hasOwnProperty.call(proto, "_dispose")) return; - const params = transport._serverParams; - return typeof params === "object" && params !== null && typeof params.command === "string" ? params : void 0; -} -async function negotiateStdioViaSibling(negotiation, sessionTransport, params, deps) { - const SiblingTransport = sessionTransport.constructor; - const sibling = new SiblingTransport({ - ...params, - stderr: "ignore" - }); - const originalClose = sessionTransport.close; - let callerClosed = false; - let signalClosed; - const closedSignal = new Promise((_, reject) => { - signalClosed = () => reject(callerCloseAbortError()); - }); - sessionTransport.close = async function() { - callerClosed = true; - signalClosed?.(); - return originalClose.call(sessionTransport); - }; - let result; - try { - const negotiated = negotiateEra(negotiation, { - ...deps, - transport: sibling, - transportKind: "stdio", - disposableProbe: true - }); - negotiated.catch(() => { - }); - result = await Promise.race([negotiated, closedSignal]); - } finally { - await disposeSibling(sibling); - sessionTransport.close = originalClose; - } - if (callerClosed) throw callerCloseAbortError(); - return result; -} -function callerCloseAbortError() { - return new SdkError(SdkErrorCode.EraNegotiationFailed, "Version negotiation failed: the transport was closed during the server/discover probe"); -} -async function disposeSibling(sibling) { - try { - const dispose = sibling._dispose; - await (typeof dispose === "function" ? dispose.call(sibling) : sibling.close()); - } catch { - } -} -function serverInfoFromDiscover(discover) { - const fromMeta = discover._meta?.[SERVER_INFO_META_KEY]; - return isSpecType.Implementation(fromMeta) ? fromMeta : void 0; -} -function applyElicitationDefaults(schema, data) { - if (!schema || data === null || typeof data !== "object") return; - if (schema.type === "object" && schema.properties && typeof schema.properties === "object") { - const obj = data; - const props = schema.properties; - for (const key of Object.keys(props)) { - const propSchema = props[key]; - if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) obj[key] = propSchema.default; - if (obj[key] !== void 0) applyElicitationDefaults(propSchema, obj[key]); - } - } - if (Array.isArray(schema.anyOf)) { - for (const sub of schema.anyOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data); - } - if (Array.isArray(schema.oneOf)) { - for (const sub of schema.oneOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data); - } -} -function getSupportedElicitationModes(capabilities) { - if (!capabilities) return { - supportsFormMode: false, - supportsUrlMode: false - }; - const hasFormCapability = capabilities.form !== void 0; - const hasUrlCapability = capabilities.url !== void 0; - return { - supportsFormMode: hasFormCapability || !hasFormCapability && !hasUrlCapability, - supportsUrlMode: hasUrlCapability - }; -} -function validatePrior(prior) { - if (typeof prior === "object" && prior !== null) { - if (prior.kind === "legacy" && !("supportedVersions" in prior) && !("discover" in prior)) return prior; - if (prior.kind === "modern" && DiscoverResultSchema.safeParse(prior.discover).success) return prior; - } - throw new SdkError(SdkErrorCode.EraNegotiationFailed, "connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }"); -} -async function requestJwtAuthorizationGrant(options) { - const { tokenEndpoint, audience, resource, idToken, clientId, clientSecret, scope, fetchFn = fetch } = options; - const tokenUrl = assertSecureTokenEndpoint(tokenEndpoint); - const params = new URLSearchParams({ - grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", - requested_token_type: "urn:ietf:params:oauth:token-type:id-jag", - audience: String(audience), - resource: String(resource), - subject_token: idToken, - subject_token_type: "urn:ietf:params:oauth:token-type:id_token", - client_id: clientId - }); - if (clientSecret) params.set("client_secret", clientSecret); - if (scope) params.set("scope", scope); - const response = await fetchFn(tokenUrl, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: params.toString() - }); - if (!response.ok) { - const errorBody = await response.json().catch(() => ({})); - const parseResult$1 = OAuthErrorResponseSchema.safeParse(errorBody); - if (parseResult$1.success) { - const { error: error2, error_description } = parseResult$1.data; - throw new Error(`Token exchange failed: ${error2}${error_description ? ` - ${error_description}` : ""}`); - } - throw new Error(`Token exchange failed with status ${response.status}: ${JSON.stringify(errorBody)}`); - } - const parseResult = IdJagTokenExchangeResponseSchema.safeParse(await response.json()); - if (!parseResult.success) throw new Error(`Invalid token exchange response: ${parseResult.error.message}`); - return { - jwtAuthGrant: parseResult.data.access_token, - expiresIn: parseResult.data.expires_in, - scope: parseResult.data.scope - }; -} -async function discoverAndRequestJwtAuthGrant(options) { - const { idpUrl, fetchFn = fetch, ...restOptions } = options; - const metadata = await discoverAuthorizationServerMetadata(String(idpUrl), { fetchFn }); - if (!metadata?.token_endpoint) throw new Error(`Failed to discover token endpoint for IdP: ${idpUrl}`); - return requestJwtAuthorizationGrant({ - ...restOptions, - tokenEndpoint: metadata.token_endpoint, - fetchFn - }); -} -async function exchangeJwtAuthGrant(options) { - const { tokenEndpoint, jwtAuthGrant, clientId, clientSecret, authMethod = "client_secret_basic", fetchFn = fetch } = options; - const tokenUrl = assertSecureTokenEndpoint(tokenEndpoint); - const params = new URLSearchParams({ - grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", - assertion: jwtAuthGrant - }); - const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded" }); - applyClientAuthentication(authMethod, { - client_id: clientId, - client_secret: clientSecret - }, headers, params); - const response = await fetchFn(tokenUrl, { - method: "POST", - headers, - body: params.toString() - }); - if (!response.ok) { - const errorBody = await response.json().catch(() => ({})); - const parseResult$1 = OAuthErrorResponseSchema.safeParse(errorBody); - if (parseResult$1.success) { - const { error: error2, error_description } = parseResult$1.data; - throw new Error(`JWT grant exchange failed: ${error2}${error_description ? ` - ${error_description}` : ""}`); - } - throw new Error(`JWT grant exchange failed with status ${response.status}: ${JSON.stringify(errorBody)}`); - } - const responseBody = await response.json(); - const parseResult = OAuthTokensSchema.safeParse(responseBody); - if (!parseResult.success) throw new Error(`Invalid token response: ${parseResult.error.message}`); - return parseResult.data; -} -function anySignal(a, b) { - if (typeof AbortSignal.any === "function") return AbortSignal.any([a, b]); - const controller = new AbortController(); - if (a.aborted) return controller.abort(a.reason), controller.signal; - if (b.aborted) return controller.abort(b.reason), controller.signal; - const cleanup = () => { - a.removeEventListener("abort", onA); - b.removeEventListener("abort", onB); - }; - function onA() { - cleanup(); - controller.abort(a.reason); - } - function onB() { - cleanup(); - controller.abort(b.reason); - } - a.addEventListener("abort", onA, { once: true }); - b.addEventListener("abort", onB, { once: true }); - return controller.signal; -} -function fromJsonSchema2(schema, validator) { - return fromJsonSchema(schema, validator ?? (_defaultValidator ??= new AjvJsonSchemaValidator())); -} -var OAuthClientFlowError, IssuerMismatchError, RegistrationRejectedError, InsecureTokenEndpointError, AuthorizationServerMismatchError, InsufficientScopeError, UnauthorizedError, AUTHORIZATION_CODE_RESPONSE_TYPE, AUTHORIZATION_CODE_CHALLENGE_METHOD, ClientCredentialsProvider, PrivateKeyJwtProvider, StaticPrivateKeyJwtProvider, CrossAppAccessProvider, CAP_EXEMPT_METHODS, InMemoryResponseCacheStore, MAX_CACHE_TTL_MS, ClientResponseCache, UNSUPPORTED_PROTOCOL_VERSION, NOT_PROBE_RECOGNIZED, DEFAULT_VERSION_NEGOTIATION_MODE, ProbeWindow, pendingSpentCloseGuards, LIST_CHANGED_EVICTIONS, DEFAULT_LIST_MAX_PAGES, Client, withOAuth, withLogging, applyMiddlewares, createMiddleware, SseError, SSEClientTransport, DEFAULT_MAX_STEP_UP_RETRIES, DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS, RESERVED_REQUEST_HEADER_NAMES, StreamableHTTPClientTransport, _defaultValidator; -var init_dist3 = __esm({ - "../freya/node_modules/.pnpm/@modelcontextprotocol+client@2.0.0-beta.5/node_modules/@modelcontextprotocol/client/dist/index.mjs"() { - init_src_CgOncMok(); - init_shimsNode(); - init_index_node(); - init_dist2(); - init_stream(); - OAuthClientFlowError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthClientFlowError" }); - } - 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(message2) { - super(message2); - this.name = new.target.name; - stampErrorBrands(this, new.target); - } - }; - IssuerMismatchError = class extends OAuthClientFlowError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.IssuerMismatchError" }); - } - /** Which check failed — metadata echo (RFC 8414 §3.3) or authorization-response `iss` (RFC 9207). */ - kind; - /** The issuer the client expected (from validated metadata / discovery input). */ - expected; - /** The issuer value that was received. Attacker-controllable on the `'authorization_response'` path. */ - received; - constructor(kind, expected, received) { - super(`Issuer mismatch in ${kind === "metadata" ? "authorization server metadata (RFC 8414 \xA73.3)" : "authorization response (RFC 9207)"}: expected ${JSON.stringify(expected)}, received ${JSON.stringify(received)}`); - this.kind = kind; - this.expected = expected; - this.received = received; - } - }; - RegistrationRejectedError = class extends OAuthClientFlowError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.RegistrationRejectedError" }); - } - /** HTTP status code returned by the registration endpoint. */ - status; - /** Raw response body text (typically an RFC 7591 error JSON document). */ - body; - /** The exact client metadata that was POSTed (after SDK defaults were applied). */ - submittedMetadata; - constructor(args) { - super(`Dynamic Client Registration rejected (HTTP ${args.status}): ${args.body}`); - this.status = args.status; - this.body = args.body; - this.submittedMetadata = args.submittedMetadata; - } - }; - InsecureTokenEndpointError = class extends OAuthClientFlowError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.InsecureTokenEndpointError" }); - } - /** The token endpoint URL that was rejected. */ - tokenEndpoint; - constructor(tokenEndpoint) { - super(`Refusing to send credentials to non-https token endpoint '${tokenEndpoint}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`); - this.tokenEndpoint = tokenEndpoint; - } - }; - AuthorizationServerMismatchError = class extends OAuthClientFlowError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.AuthorizationServerMismatchError" }); - } - constructor(recordedIssuer, currentIssuer) { - super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(recordedIssuer)}, callback resolved ${JSON.stringify(currentIssuer)}); refusing to send authorization_code/code_verifier to a different token endpoint`); - this.recordedIssuer = recordedIssuer; - this.currentIssuer = currentIssuer; - } - }; - InsufficientScopeError = class extends OAuthClientFlowError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.InsufficientScopeError" }); - } - /** The `scope` value from the `WWW-Authenticate` challenge — the scopes the resource server says are required. */ - requiredScope; - /** The `resource_metadata` URL from the `WWW-Authenticate` challenge, if present. */ - resourceMetadataUrl; - /** The `error_description` from the `WWW-Authenticate` challenge, if present. */ - errorDescription; - constructor(init) { - super(`Insufficient scope${init.requiredScope ? `: required "${init.requiredScope}"` : ""}`); - this.requiredScope = init.requiredScope; - this.resourceMetadataUrl = init.resourceMetadataUrl; - this.errorDescription = init.errorDescription; - } - }; - UnauthorizedError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnauthorizedError" }); - } - 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(message2) { - super(message2 ?? "Unauthorized"); - this.name = "UnauthorizedError"; - stampErrorBrands(this, new.target); - } - }; - AUTHORIZATION_CODE_RESPONSE_TYPE = "code"; - AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256"; - ClientCredentialsProvider = class { - _tokens; - _clientInfo; - _clientMetadata; - constructor(options) { - this._clientInfo = { - client_id: options.clientId, - client_secret: options.clientSecret, - issuer: options.expectedIssuer - }; - this._clientMetadata = { - client_name: options.clientName ?? "client-credentials-client", - redirect_uris: [], - grant_types: ["client_credentials"], - token_endpoint_auth_method: "client_secret_basic", - scope: options.scope - }; - } - get redirectUrl() { - } - get clientMetadata() { - return this._clientMetadata; - } - clientInformation() { - return this._clientInfo; - } - tokens() { - return this._tokens; - } - saveTokens(tokens) { - this._tokens = tokens; - } - redirectToAuthorization() { - throw new Error("redirectToAuthorization is not used for client_credentials flow"); - } - saveCodeVerifier() { - } - codeVerifier() { - throw new Error("codeVerifier is not used for client_credentials flow"); - } - prepareTokenRequest(scope) { - const params = new URLSearchParams({ grant_type: "client_credentials" }); - if (scope) params.set("scope", scope); - return params; - } - }; - PrivateKeyJwtProvider = class { - _tokens; - _clientInfo; - _clientMetadata; - addClientAuthentication; - constructor(options) { - this._clientInfo = { - client_id: options.clientId, - issuer: options.expectedIssuer - }; - this._clientMetadata = { - client_name: options.clientName ?? "private-key-jwt-client", - redirect_uris: [], - grant_types: ["client_credentials"], - token_endpoint_auth_method: "private_key_jwt", - scope: options.scope - }; - this.addClientAuthentication = createPrivateKeyJwtAuth({ - issuer: options.clientId, - subject: options.clientId, - privateKey: options.privateKey, - alg: options.algorithm, - lifetimeSeconds: options.jwtLifetimeSeconds, - claims: options.claims - }); - } - get redirectUrl() { - } - get clientMetadata() { - return this._clientMetadata; - } - clientInformation() { - return this._clientInfo; - } - tokens() { - return this._tokens; - } - saveTokens(tokens) { - this._tokens = tokens; - } - redirectToAuthorization() { - throw new Error("redirectToAuthorization is not used for client_credentials flow"); - } - saveCodeVerifier() { - } - codeVerifier() { - throw new Error("codeVerifier is not used for client_credentials flow"); - } - prepareTokenRequest(scope) { - const params = new URLSearchParams({ grant_type: "client_credentials" }); - if (scope) params.set("scope", scope); - return params; - } - }; - StaticPrivateKeyJwtProvider = class { - _tokens; - _clientInfo; - _clientMetadata; - addClientAuthentication; - constructor(options) { - this._clientInfo = { - client_id: options.clientId, - issuer: options.expectedIssuer - }; - this._clientMetadata = { - client_name: options.clientName ?? "static-private-key-jwt-client", - redirect_uris: [], - grant_types: ["client_credentials"], - token_endpoint_auth_method: "private_key_jwt", - scope: options.scope - }; - const assertion = options.jwtBearerAssertion; - this.addClientAuthentication = async (_headers, params) => { - params.set("client_assertion", assertion); - params.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); - }; - } - get redirectUrl() { - } - get clientMetadata() { - return this._clientMetadata; - } - clientInformation() { - return this._clientInfo; - } - tokens() { - return this._tokens; - } - saveTokens(tokens) { - this._tokens = tokens; - } - redirectToAuthorization() { - throw new Error("redirectToAuthorization is not used for client_credentials flow"); - } - saveCodeVerifier() { - } - codeVerifier() { - throw new Error("codeVerifier is not used for client_credentials flow"); - } - prepareTokenRequest(scope) { - const params = new URLSearchParams({ grant_type: "client_credentials" }); - if (scope) params.set("scope", scope); - return params; - } - }; - CrossAppAccessProvider = class { - _tokens; - _clientInfo; - _clientMetadata; - _assertionCallback; - _fetchFn; - _authorizationServerUrl; - _resourceUrl; - _scope; - constructor(options) { - this._clientInfo = { - client_id: options.clientId, - client_secret: options.clientSecret, - issuer: options.expectedIssuer - }; - this._clientMetadata = { - client_name: options.clientName ?? "cross-app-access-client", - redirect_uris: [], - grant_types: ["urn:ietf:params:oauth:grant-type:jwt-bearer"], - token_endpoint_auth_method: "client_secret_basic" - }; - this._assertionCallback = options.assertion; - this._fetchFn = options.fetchFn ?? fetch; - } - get redirectUrl() { - } - get clientMetadata() { - return this._clientMetadata; - } - clientInformation() { - return this._clientInfo; - } - tokens() { - return this._tokens; - } - saveTokens(tokens) { - this._tokens = tokens; - } - redirectToAuthorization() { - throw new Error("redirectToAuthorization is not used for jwt-bearer flow"); - } - saveCodeVerifier() { - } - codeVerifier() { - throw new Error("codeVerifier is not used for jwt-bearer flow"); - } - /** - * Saves the authorization server URL discovered during OAuth flow. - * This is called by the auth() function after RFC 9728 discovery. - */ - saveAuthorizationServerUrl(authorizationServerUrl) { - this._authorizationServerUrl = authorizationServerUrl; - } - /** - * Returns the cached authorization server URL if available. - */ - authorizationServerUrl() { - return this._authorizationServerUrl; - } - /** - * Saves the resource URL discovered during OAuth flow. - * This is called by the auth() function after RFC 9728 discovery. - */ - saveResourceUrl(resourceUrl) { - this._resourceUrl = resourceUrl; - } - /** - * Returns the cached resource URL if available. - */ - resourceUrl() { - return this._resourceUrl; - } - async prepareTokenRequest(scope) { - const authServerUrl = this._authorizationServerUrl; - const resourceUrl = this._resourceUrl; - if (!authServerUrl) throw new Error("Authorization server URL not available. Ensure auth() has been called first."); - if (!resourceUrl) throw new Error("Resource URL not available \u2014 server may not implement RFC 9728 Protected Resource Metadata (required for Cross-App Access), or auth() has not been called"); - this._scope = scope; - const jwtAuthGrant = await this._assertionCallback({ - authorizationServerUrl: authServerUrl, - resourceUrl, - scope: this._scope, - fetchFn: this._fetchFn - }); - const params = new URLSearchParams({ - grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", - assertion: jwtAuthGrant - }); - if (scope) params.set("scope", scope); - return params; - } - }; - CAP_EXEMPT_METHODS = /* @__PURE__ */ new Set([ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "server/discover" - ]); - InMemoryResponseCacheStore = class { - _entries = /* @__PURE__ */ new Map(); - _maxEntries; - _stamp = 0; - /** Count of held entries that are subject to the cap (i.e. not in {@linkcode CAP_EXEMPT_METHODS}). */ - _cappedSize = 0; - constructor(options) { - this._maxEntries = options?.maxEntries ?? 512; - } - /** Number of held entries (for diagnostics / bounding tests). */ - get size() { - return this._entries.size; - } - get(key) { - return this._entries.get(keyOf(key)); - } - set(key, entry) { - const k = keyOf(key); - const exempt = CAP_EXEMPT_METHODS.has(key.method); - const isNew = !this._entries.has(k); - if (!exempt && isNew && this._maxEntries > 0 && this._cappedSize >= this._maxEntries) { - for (const oldKey of this._entries.keys()) if (!CAP_EXEMPT_METHODS.has(oldKey.slice(0, oldKey.indexOf("\0")))) { - this._entries.delete(oldKey); - this._cappedSize--; - break; - } - } - const stamp = ++this._stamp; - this._entries.set(k, { - ...entry, - stamp - }); - if (isNew && !exempt) this._cappedSize++; - return stamp; - } - delete(key) { - if (this._entries.delete(keyOf(key)) && !CAP_EXEMPT_METHODS.has(key.method)) this._cappedSize--; - } - evict(method) { - const prefix = `${method}\0`; - const exempt = CAP_EXEMPT_METHODS.has(method); - for (const k of this._entries.keys()) if (k.startsWith(prefix)) { - this._entries.delete(k); - if (!exempt) this._cappedSize--; - } - } - clear() { - this._entries.clear(); - this._cappedSize = 0; - } - }; - MAX_CACHE_TTL_MS = 864e5; - ClientResponseCache = class { - /** - * Per-logical-key eviction-generation counter. {@linkcode evict} (whole - * method) and {@linkcode evictKey} (single `{method, params}`) bump it - * before touching the store; {@linkcode captureGeneration} reads it before - * the request; {@linkcode write} skips when it moved — so a `list_changed` - * arriving mid-walk, or a `resources/updated` arriving while a - * `readResource()` for the same URI is in flight, is not overwritten by - * the in-flight request's stale write. The map key is `method` for the - * list singletons and `` `${method}\0${params}` `` for per-URI keys. - * - * Growth is bounded by keys the CLIENT has issued a `captureGeneration` - * for: {@linkcode captureGeneration} records the key (so an interleaved - * {@linkcode evictKey} sees there is an in-flight write to suppress); - * {@linkcode evictKey} only bumps a key that is already recorded — a - * server streaming `notifications/resources/updated` for URIs the client - * has never read therefore cannot grow this map. - */ - _evictionGeneration = /* @__PURE__ */ new Map(); - /** - * `name → Tool` index derived from the cached `tools/list` entry, memoized - * against the entry's `stamp` so it re-derives only when the backing entry - * changes (mcp.d's `cachedTool` pattern). - */ - _toolIndex; - /** - * `name → compiled output-schema validator` derived from the cached - * `tools/list` entry; same stamp-keyed memoization as `_toolIndex`. Typed - * `unknown` so this class stays free of any validator-provider dependency - * — the compile callback supplied to {@linkcode outputValidator} owns the - * concrete type. - */ - _toolOutputValidatorIndex; - /** - * The connected server's identity (`serverInfo.name@version`, the - * transport's `sessionId`, or a client-generated per-connection - * surrogate). Set by the `Client` immediately after a successful connect; - * `''` is the pre-connect sentinel. Every storage partition is derived - * from this (see `_partitionFor`), so two clients sharing one store but - * connected to different servers never collide on `tools/list` and a - * server cannot read another server's `'public'` entries. - */ - _serverIdentity = ""; - constructor(_store, _isUserSupplied, _reportError = () => { - }, _cachePartition = "", _now = Date.now) { - this._store = _store; - this._isUserSupplied = _isUserSupplied; - this._reportError = _reportError; - this._cachePartition = _cachePartition; - this._now = _now; - } - /** The clock used for every freshness computation and check. */ - now() { - return this._now(); - } - /** - * Record the connected server's identity. Called by `Client` immediately - * after a successful connect: `serverInfo.name@version` when the server - * identified itself, else the transport's `sessionId`, else a - * client-generated per-connection surrogate (`serverInfo` is a spec - * SHOULD on 2026-07-28, so anonymous servers exist). Surrogate-keyed - * partitions are NOT stable across reconnects — no identity means no - * cross-connection cache reuse, and a shared long-lived store should - * bound its own size accordingly. Every partition derived after this - * call is scoped to this identity; entries written under the pre-connect - * `''` sentinel are no longer reachable. - */ - setServerIdentity(identity) { - this._serverIdentity = identity; - } - /** - * Derive the storage partition for `scope`. The encoding is - * `JSON.stringify([serverIdentity, principal])` — JSON escaping makes it - * collision-free by construction: a malicious server cannot craft a - * `serverInfo.name`/`version` whose concatenated form bleeds into another - * server's namespace or another principal's slot, regardless of `@` / `|` - * / `"` / NUL in the server-controlled strings. `'public'` → - * `[serverIdentity, '']` (shared within this server); `'private'` → - * `[serverIdentity, cachePartition]`. When `cachePartition` is `''` the - * two coincide. - */ - _partitionFor(scope) { - return JSON.stringify([this._serverIdentity, scope === "public" ? "" : this._cachePartition]); - } - /** - * Two-probe lookup: this client's own (private) partition first, then the - * connected server's shared (public) partition. The shared probe is gated - * on `entry.scope === 'public'` — a co-tenant client that omits - * `cachePartition` writes its `'private'`-scoped entries at the public - * partition, and serving those to a correctly-partitioned client would - * leak private bodies (mcp.d's `cachedEntry` two-probe order; the scope - * gate is defence-in-depth on top of the partition split). When - * `cachePartition` is `''` the two partitions are identical and only one - * probe is issued. - */ - async _probe(method, params) { - const key = { - method, - params: params ?? "" - }; - const ownPartition = this._partitionFor("private"); - const own = await this._store.get({ - ...key, - partition: ownPartition - }); - if (own !== void 0) return own; - const sharedPartition = this._partitionFor("public"); - if (sharedPartition === ownPartition) return void 0; - const shared = await this._store.get({ - ...key, - partition: sharedPartition - }); - return shared?.scope === "public" ? shared : void 0; - } - /** - * Bump the per-method generation (so an in-flight {@linkcode write} for the - * same method becomes a no-op) and drop the connected server's two list - * singletons (own + shared partition; `params: ''`). The generation bump - * is unconditional and FIRST — the {@linkcode write} race guard relies on - * the bump, not on the store's deletes completing. - * - * Eviction is scoped to this client's `[serverIdentity, principal]` - * partitions (mirroring {@linkcode evictKey}) — the method-wide - * `store.evict()` is NOT called, so on a shared store one server's - * `list_changed` cannot wipe a co-tenant's entry. A custom store's - * `delete()` may throw or reject; each partition is guarded - * independently so a failure on one does not skip the other, the failure - * is reported via the constructor's sink, and the call resolves so - * dispatch proceeds. - */ - async evict(method) { - this._evictionGeneration.set(method, (this._evictionGeneration.get(method) ?? 0) + 1); - await this._deleteBoth(method, ""); - } - /** - * Guarded two-partition delete of `{method, params}`: each partition's - * `delete` is independently wrapped so a custom store's failure on one is - * reported and does not skip the other, and the call always resolves. - */ - async _deleteBoth(method, params) { - const ownPartition = this._partitionFor("private"); - const sharedPartition = this._partitionFor("public"); - try { - await this._store.delete({ - method, - params, - partition: ownPartition - }); - } catch (error2) { - this._reportError(error2); - } - if (sharedPartition !== ownPartition) try { - await this._store.delete({ - method, - params, - partition: sharedPartition - }); - } catch (error2) { - this._reportError(error2); - } - } - /** - * Drop the single logical entry `{method, params}` from BOTH the private - * and public partitions for this client's connected server (mcp.d's - * `invalidateLogical`). Used for `notifications/resources/updated`'s - * per-URI eviction. The per-key generation is bumped FIRST (so an - * in-flight {@linkcode write} for the same `{method, params}` becomes a - * no-op and cannot re-cache the now-stale body) but only when the key was - * already recorded by {@linkcode captureGeneration} — bounding the map to - * keys the client has actually read. A custom store's `delete()` may - * throw or reject; each partition's delete is guarded independently so a - * failure on one does not skip the other, and the call resolves so - * dispatch proceeds. - */ - async evictKey(method, params) { - const gk = genKey(method, params); - const current = this._evictionGeneration.get(gk); - if (current !== void 0) this._evictionGeneration.set(gk, current + 1); - await this._deleteBoth(method, params); - } - /** - * Snapshot the eviction generation for `{method, params}` before issuing - * the request (a list walk's page 1, or a `resources/read` for `params`). - * Records the key so an interleaved {@linkcode evictKey} for the same - * `{method, params}` knows there is an in-flight write to suppress and - * bumps; without the record, `evictKey`'s recorded-only bump would skip - * and the stale body would be cached. - */ - captureGeneration(method, params) { - const gk = genKey(method, params); - const current = this._evictionGeneration.get(gk) ?? 0; - this._evictionGeneration.set(gk, current); - return current; - } - /** - * Write `value` under `{method}` unless the per-method generation moved - * since `capturedGen` was taken — a `list_changed` that landed mid-walk has - * already invalidated the result the caller is about to write, and - * overwriting the eviction with the stale aggregate would lose the - * invalidation. - * - * The value is stored as its JSON-serialized document; serialization - * doubles as the mutation barrier, so a caller mutating the returned - * aggregate cannot reach the cache or its derived indices. A value that - * is not JSON-serializable (reachable only via in-process transports) - * fails the write loudly into the `reportError` sink. A custom store - * whose `set()` throws or rejects is routed to the same sink and the - * write resolves — cache bookkeeping never costs the caller a result it - * already fetched. - * - * `freshness` carries the client-computed `expiresAt` (absolute ms epoch, - * `now + ttlMs`) and the server-reported `cacheScope`. The storage - * `partition` is derived from the scope via `_partitionFor`: - * `'public'` → `[serverIdentity, '']` (shared within this server); - * `'private'` → `[serverIdentity, cachePartition]` (so a shared store - * never serves a private entry to another identity). Absent `freshness` - * preserves the substrate write (no `expiresAt`, private partition) — the - * `tools/list` retain-for-schema posture: never served by - * {@linkcode read}'s freshness gate, always readable by - * {@linkcode toolDefinition}. - * - * After storing under the derived partition, the same `{method, params}` - * is deleted from the OPPOSITE partition (mirroring {@linkcode evictKey}'s - * two-partition posture). A server that flips a result's `cacheScope` for - * the same key would otherwise leave the previous entry in the other slot - * — and since `_probe` checks own-partition first, a stale private entry - * would shadow the fresh public one (or a stale public entry would keep - * serving co-tenants). Both store calls are independently guarded so a - * custom store's failure on one does not skip the other. - */ - async write(method, value, capturedGen, freshness) { - if ((this._evictionGeneration.get(genKey(method, freshness?.params)) ?? 0) !== capturedGen) return; - const params = freshness?.params ?? ""; - const ownPartition = this._partitionFor("private"); - const sharedPartition = this._partitionFor("public"); - const partition = (freshness?.scope ?? "private") === "public" ? sharedPartition : ownPartition; - try { - await this._store.set({ - method, - params, - partition - }, { - value: encodeCacheValue(value), - expiresAt: freshness?.expiresAt, - scope: freshness?.scope - }); - } catch (error2) { - this._reportError(error2); - } - if (sharedPartition !== ownPartition) try { - await this._store.delete({ - method, - params, - partition: partition === ownPartition ? sharedPartition : ownPartition - }); - } catch (error2) { - this._reportError(error2); - } - } - /** - * Serve the fresh cached result for `{method, params}`, or `undefined`. - * Lookup is the two-probe order (own-partition then this server's shared - * partition, gated on `scope === 'public'`); freshness is - * `entry.expiresAt > now()` (a missing `expiresAt` is never fresh), - * checked BEFORE decoding so stale entries cost no parse. Every hit is - * freshly parsed, so the caller owns the value outright. An entry whose - * document does not parse or is not an object (corrupted external - * store) is reported, - * deleted, and treated as a miss — deleted because a fresh-but-corrupt - * entry would otherwise re-parse and re-report on every read until its - * `expiresAt` passes. - */ - async read(method, params) { - const entry = await this._probe(method, params); - if (entry?.expiresAt === void 0 || !(entry.expiresAt > this.now())) return void 0; - try { - const parsed = JSON.parse(entry.value); - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new TypeError("cached document is not an object"); - return { value: parsed }; - } catch (error2) { - this._reportError(error2); - await this._deleteBoth(method, params ?? ""); - return; - } - } - /** - * Connection reset. The per-instance default store IS cleared - * (connection-scoped); a user-supplied store is NOT — that would defeat - * the only reason to supply one. The generation map and every derived - * index are dropped regardless: they are connection-scoped even when the - * backing store survives, so the next read re-derives from whatever the - * store still holds. The server identity returns to the pre-connect - * sentinel. The default impl is synchronous, so the `MaybePromise` - * return is a plain void here and the caller need not await. - */ - resetForReconnect() { - if (!this._isUserSupplied) this._store.clear(); - this._evictionGeneration.clear(); - this._toolIndex = void 0; - this._toolOutputValidatorIndex = void 0; - this._serverIdentity = ""; - } - /** - * The descriptor for tool `name` taken from the cached `tools/list` entry. - * The `name → Tool` index is memoized against the entry's `stamp` and - * re-derived only when the backing entry changes (mcp.d's `cachedTool`). - * Returns `undefined` only when no `tools/list` response is held at all, - * or the held list does not contain `name`. - * - * Consumed by `callTool()`'s SEP-2243 `_resolveXMcpHeaderScan` (mirroring) - * and, via {@linkcode outputValidator}, its output-schema validation. - */ - async toolDefinition(name) { - const entry = await this._probe("tools/list"); - if (entry === void 0) { - this._toolIndex = void 0; - return; - } - if (this._toolIndex?.stamp !== entry.stamp) { - const list = this._decodeListTools(entry); - const byName = /* @__PURE__ */ new Map(); - if (list !== void 0) for (const tool of list.tools) byName.set(tool.name, tool); - this._toolIndex = { - stamp: entry.stamp, - byName - }; - } - return this._toolIndex.byName.get(name); - } - /** - * The compiled output-schema validator for tool `name`, derived from the - * cached `tools/list` entry — same source and same stamp-keyed - * memoization as {@linkcode toolDefinition}. The `name → validator` index - * re-derives only when the backing entry's stamp changes (a refetched - * `tools/list` recompiles; a `list_changed` eviction drops it). Returns - * `undefined` when no `tools/list` is held, the tool is absent, or it has - * no `outputSchema`. - * - * `compile` is the caller-supplied validator-compile callback (the - * `Client` passes its `_jsonSchemaValidator` wrapper) so this - * class carries no validator-provider dependency. One tool's uncompilable - * `outputSchema` (e.g. an invalid `pattern` regex or unresolvable `$ref`) - * must not poison every other tool's `callTool` — the callback isolates - * that compile error per tool by returning a per-tool error variant which - * the index stores alongside the good ones, and `callTool` surfaces it as - * a typed `InvalidParams` only for that name. Because the error is held on - * this stamp-keyed substrate (not a parallel map), it inherits the - * substrate's invalidation lifecycle: a `list_changed` eviction drops it, - * a refetched `tools/list` re-derives it, and `resetForReconnect` clears - * the lot. - */ - async outputValidator(name, compile) { - const entry = await this._probe("tools/list"); - if (entry === void 0) { - this._toolOutputValidatorIndex = void 0; - return; - } - if (this._toolOutputValidatorIndex?.stamp !== entry.stamp) { - const list = this._decodeListTools(entry) ?? { tools: [] }; - const byName = /* @__PURE__ */ new Map(); - for (const tool of list.tools) { - const compiled = compile(tool); - if (compiled !== void 0) byName.set(tool.name, compiled); - } - this._toolOutputValidatorIndex = { - stamp: entry.stamp, - byName - }; - } - return this._toolOutputValidatorIndex.byName.get(name); - } - /** Parse a held `tools/list` document for the index builders; a document - * that does not parse OR whose `tools` is not an array of objects - * (both mean a corrupted external store) is reported and treated as if - * nothing were held. Callers memoize the outcome against the entry's - * stamp, so a corrupt document costs one parse + report per stamp, not - * per lookup. */ - _decodeListTools(entry) { - try { - const parsed = JSON.parse(entry.value); - if (!Array.isArray(parsed?.tools) || !parsed.tools.every((t) => t !== null && typeof t === "object")) throw new TypeError("cached tools/list document has a malformed tools array"); - return parsed; - } catch (error2) { - this._reportError(error2); - return; - } - } - }; - UNSUPPORTED_PROTOCOL_VERSION = -32022; - NOT_PROBE_RECOGNIZED = /* @__PURE__ */ new Set([ - -32001, - -32020, - -32021 - ]); - DEFAULT_VERSION_NEGOTIATION_MODE = "legacy"; - ProbeWindow = class ProbeWindow2 { - _pending; - _probeCounter = 0; - _savedOnMessage; - _savedOnError; - _savedOnClose; - _closeDelivered = false; - constructor(_transport) { - this._transport = _transport; - this._savedOnMessage = _transport.onmessage; - this._savedOnError = _transport.onerror; - this._savedOnClose = _transport.onclose; - } - static async open(transport) { - const window = new ProbeWindow2(transport); - transport.onmessage = (message2) => { - const pending = window._pending; - if (pending !== void 0 && (isJSONRPCResultResponse(message2) || isJSONRPCErrorResponse(message2)) && message2.id === pending.id) { - window._pending = void 0; - if (isJSONRPCResultResponse(message2)) pending.resolve({ - kind: "response", - result: message2.result - }); - else pending.resolve({ - kind: "response", - error: message2.error - }); - return; - } - }; - transport.onerror = (error2) => { - window._savedOnError?.(error2); - }; - transport.onclose = () => { - const pending = window._pending; - if (pending !== void 0) { - window._pending = void 0; - pending.resolve({ kind: "closed" }); - } - window._closeDelivered = true; - window._savedOnClose?.(); - }; - try { - await transport.start(); - } catch (error2) { - window.detach(); - throw error2; - } - return window; - } - /** - * Send one probe request and await its reply. Probe ids are strings, so they - * never collide with Protocol's numeric ids (e.g. on a shared stdio pipe). - */ - async exchange(buildRequest, timeoutMs) { - const id = `server-discover-probe-${++this._probeCounter}`; - return new Promise((resolve) => { - let settled = false; - const settle = (reply) => { - if (settled) return; - settled = true; - clearTimeout(timer); - if (this._pending?.id === id) this._pending = void 0; - resolve(reply); - }; - const timer = setTimeout(() => settle({ kind: "timeout" }), timeoutMs); - this._pending = { - id, - resolve: settle - }; - this._transport.send(buildRequest(id)).catch((error2) => settle({ - kind: "send-error", - error: error2 - })); - }); - } - /** Detach the window's handlers, restoring any the caller pre-set, leaving the transport's own `start` untouched. */ - detach() { - this._pending = void 0; - this._transport.onmessage = this._savedOnMessage; - this._transport.onerror = this._savedOnError; - if (this._closeDelivered && this._savedOnClose !== void 0) { - const saved = this._savedOnClose; - const transport = this._transport; - let spent = false; - const wrapper = () => { - if (!spent) { - spent = true; - return; - } - saved(); - }; - transport.onclose = wrapper; - pendingSpentCloseGuards.set(transport, () => { - if (transport.onclose === wrapper) transport.onclose = saved; - }); - } else this._transport.onclose = this._savedOnClose; - } - /** Detach the handlers and arm the one-shot `start()` pass-through for the `Protocol.connect()` handover. */ - release() { - this.detach(); - const transport = this._transport; - const originalStart = transport.start; - let armed = true; - transport.start = async function() { - if (armed) { - armed = false; - transport.start = originalStart; - return; - } - return originalStart.call(transport); - }; - } - }; - pendingSpentCloseGuards = /* @__PURE__ */ new WeakMap(); - LIST_CHANGED_EVICTIONS = { - "notifications/tools/list_changed": ["tools/list"], - "notifications/prompts/list_changed": ["prompts/list"], - "notifications/resources/list_changed": ["resources/list", "resources/templates/list"] - }; - DEFAULT_LIST_MAX_PAGES = 64; - Client = class extends Protocol { - _serverCapabilities; - _serverVersion; - _capabilities; - _instructions; - _jsonSchemaValidator; - /** - * The response-cache substrate. Owns the backing store, the per-method - * eviction-generation counter, the user-supplied/default flag, and the - * stamp-memoized derived `name → Tool` / `name → output-validator` - * indices — the cache-coordination state that used to live as separate - * private fields here. The internal aggregating walk writes one entry per - * list verb; `list_changed` evicts the matching method; - * `_resetConnectionState` resets the lot. {@linkcode callTool}'s - * output-schema validation reads the derived `outputValidator` index (the - * substrate's first production caller); the stacked SEP-2243 PR wires - * `Mcp-Param-*` mirroring through `toolDefinition` on top. - */ - _cache; - _defaultCacheTtlMs; - _listMaxPages; - _listChangedDebounceTimers = /* @__PURE__ */ new Map(); - /** - * The constructor `listChanged` configuration. Durable across reconnects: - * read fresh on every connect (legacy or modern), never consumed. - */ - _listChangedConfig; - _enforceStrictCapabilities; - _versionNegotiation; - _supportedProtocolVersionsOption; - _inputRequiredDriverConfig; - /** - * Active subscriptions/listen state, keyed by subscription id (= the - * listen request's JSON-RPC id verbatim). The id is a STRING from a - * Client-owned counter (`'listen:' + N`) — JSON-RPC permits string ids, - * and Protocol's numeric `_requestMessageId` counter only ever issues - * numbers, so listen ids cannot collide with ordinary request ids. - */ - _listenState = /* @__PURE__ */ new Map(); - _nextListenId = 0; - /** The auto-opened subscription backing ClientOptions.listChanged on a modern connection. */ - _autoOpenedSubscription; - /** Backing store for {@linkcode getDiscoverResult}. Per-connection. */ - _discoverResult; - /** - * Clears every per-connection field in one place. Called at the start of - * each fresh (non-resuming) connect and from `close()`, so a stale - * negotiated era / server identity / auto-opened subscription cannot - * survive a reconnect. - */ - _resetConnectionState() { - this._negotiatedProtocolVersion = void 0; - this._serverCapabilities = void 0; - this._serverVersion = void 0; - this._instructions = void 0; - this._discoverResult = void 0; - this._autoOpenedSubscription = void 0; - if (this._listenState.size > 0) { - const reason = new SdkError(SdkErrorCode.ConnectionClosed, "subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset"); - for (const entry of this._listenState.values()) entry.settle({ - cause: "remote", - error: reason - }); - } - this._listenState.clear(); - for (const timer of this._listChangedDebounceTimers.values()) clearTimeout(timer); - this._listChangedDebounceTimers.clear(); - this._cache.resetForReconnect(); - } - async close() { - try { - await super.close(); - } finally { - this._resetConnectionState(); - } - } - /** - * Initializes this client with the given name and version information. - */ - constructor(_clientInfo, options) { - super(options); - this._clientInfo = _clientInfo; - this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this._enforceStrictCapabilities = options?.enforceStrictCapabilities ?? false; - this._versionNegotiation = options?.versionNegotiation; - this._supportedProtocolVersionsOption = options?.supportedProtocolVersions; - this._inputRequiredDriverConfig = resolveInputRequiredDriverConfig(options?.inputRequired); - this._cache = new ClientResponseCache(options?.responseCacheStore ?? new InMemoryResponseCacheStore(), options?.responseCacheStore !== void 0, (error2) => this._reportStoreError(error2), options?.cachePartition ?? ""); - this._defaultCacheTtlMs = options?.defaultCacheTtlMs ?? 0; - this._listMaxPages = options?.listMaxPages ?? DEFAULT_LIST_MAX_PAGES; - if (options?.listChanged) this._listChangedConfig = options.listChanged; - } - buildContext(ctx, _transportInfo) { - return ctx; - } - /** - * Era-keyed direction enforcement for inbound traffic on channels whose - * transport does not classify (e.g. stdio): the 2026-07-28 era has no - * server→client JSON-RPC request channel — server-to-client interactions - * are carried in-band in `input_required` results — and on stdio the - * client must never write JSON-RPC responses. An inbound request arriving - * on a connection that negotiated a modern era is therefore dropped - * (surfaced via `onerror`) rather than answered. Connections on a legacy - * era — and all responses and notifications — keep today's dispatch path. - */ - _shouldDropInbound(message2) { - if (this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion) && isJSONRPCRequest(message2)) return "drop"; - } - /** - * Per-request `_meta` envelope auto-emission (protocol revision 2026-07-28): - * on a connection that negotiated a modern era — auto-negotiated or pinned — - * every outgoing request and notification automatically carries the reserved - * protocol-version / client-info / client-capabilities `_meta` keys (the - * same envelope the connect-time `server/discover` probe sends). - * User-supplied `_meta` keys take precedence over the auto-attached ones. - * - * Legacy-era connections return `undefined`: the envelope seam is a no-op - * and outbound traffic is byte-identical to a 2025 client (the legacy - * `'auto'` fallback included). - */ - _outboundMetaEnvelope() { - const version2 = this._negotiatedProtocolVersion; - if (version2 === void 0) return void 0; - return this._wireCodec().outboundEnvelope({ - protocolVersion: version2, - clientInfo: this._clientInfo, - clientCapabilities: this._capabilities - }); - } - /** - * Wires the multi-round-trip auto-fulfilment engine (protocol revision - * 2026-07-28) into the response funnel: an `input_required` answer is - * fulfilled through the registered elicitation/sampling/roots handlers - * and the original request retried via `flow.retry`, up to - * `inputRequired.maxRounds` rounds. With auto-fulfilment disabled the - * response surfaces as a typed error steering to manual mode. - */ - _resolveNonCompleteResult(decoded, flow) { - if (!this._inputRequiredDriverConfig.autoFulfill) return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type 'input_required' for ${flow.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`, { - resultType: "input_required", - method: flow.request.method - })); - return runInputRequiredFlow({ - getRequestHandler: (method) => this._getRequestHandler(method), - buildContext: (baseCtx) => this.buildContext(baseCtx, void 0), - sessionId: this.transport?.sessionId - }, this._inputRequiredDriverConfig, decoded, flow); - } - /** - * Set up handlers for list changed notifications based on config and server capabilities. - * This should only be called after initialization when server capabilities are known. - * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. - * @internal - */ - _setupListChangedHandlers(config2) { - if (config2.tools && this._serverCapabilities?.tools?.listChanged) this._setupListChangedHandler("tools", "notifications/tools/list_changed", config2.tools, async () => { - return (await this.listTools(void 0, { cacheMode: "refresh" })).tools; - }); - if (config2.prompts && this._serverCapabilities?.prompts?.listChanged) this._setupListChangedHandler("prompts", "notifications/prompts/list_changed", config2.prompts, async () => { - return (await this.listPrompts(void 0, { cacheMode: "refresh" })).prompts; - }); - if (config2.resources && this._serverCapabilities?.resources?.listChanged) this._setupListChangedHandler("resources", "notifications/resources/list_changed", config2.resources, async () => { - return (await this.listResources(void 0, { cacheMode: "refresh" })).resources; - }); - } - /** - * 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 Error("Cannot register capabilities after connecting to transport"); - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } - /** - * Configure protocol version negotiation before connecting (equivalent to - * passing `versionNegotiation` at construction time). Can only be called - * before connecting to a transport. Passing `undefined` clears a previously - * configured negotiation, restoring the default `'legacy'` posture. - * - * See {@linkcode ClientOptions | ClientOptions.versionNegotiation} for the mode semantics. - */ - setVersionNegotiation(options) { - if (this.transport) throw new Error("Cannot configure version negotiation after connecting to transport"); - this._versionNegotiation = options; - } - /** - * Enforces client-side validation for `elicitation/create` and `sampling/createMessage` - * regardless of how the handler was registered. - */ - _wrapHandler(method, handler) { - if (method === "elicitation/create") return async (request, ctx) => { - const codec2 = codecForVersion(this._negotiatedProtocolVersion); - let validatedRequest = codec2.validateRequest("elicitation/create", request); - if (!validatedRequest.ok && validatedRequest.reason === "not-in-era") validatedRequest = codec2.validateInputRequest("elicitation/create", request); - if (!validatedRequest.ok) throw new ProtocolError(validatedRequest.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for elicitation/create in the resolved era" : `Invalid elicitation request: ${validatedRequest.message}`); - const { params } = validatedRequest.value; - params.mode = params.mode ?? "form"; - const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); - if (params.mode === "form" && !supportsFormMode) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Client does not support form-mode elicitation requests"); - if (params.mode === "url" && !supportsUrlMode) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests"); - const result = await handler(request, ctx); - let validationResult = codec2.validateResult("elicitation/create", result); - if (!validationResult.ok && validationResult.reason === "not-in-era") validationResult = codec2.validateInputResponse("elicitation/create", result); - if (!validationResult.ok) throw new ProtocolError(validationResult.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for elicitation/create in the resolved era" : `Invalid elicitation result: ${validationResult.message}`); - const validatedResult = validationResult.value; - const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0; - if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema && this._capabilities.elicitation?.form?.applyDefaults) try { - applyElicitationDefaults(requestedSchema, validatedResult.content); - } catch { - } - return validatedResult; - }; - if (method === "sampling/createMessage") return async (request, ctx) => { - const codec2 = codecForVersion(this._negotiatedProtocolVersion); - let validatedRequest = codec2.validateRequest("sampling/createMessage", request); - if (!validatedRequest.ok && validatedRequest.reason === "not-in-era") validatedRequest = codec2.validateInputRequest("sampling/createMessage", request); - if (!validatedRequest.ok) throw new ProtocolError(validatedRequest.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for sampling/createMessage in the resolved era" : `Invalid sampling request: ${validatedRequest.message}`); - const { params } = validatedRequest.value; - const result = await handler(request, ctx); - const hasTools = Boolean(params.tools || params.toolChoice); - let validatedResult = codec2.samplingResultVariant(hasTools, result); - if (!validatedResult.ok && validatedResult.reason === "not-in-era") validatedResult = codec2.validateInputResponse("sampling/createMessage", result); - if (!validatedResult.ok) throw new ProtocolError(validatedResult.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validatedResult.reason === "not-in-era" ? "No result schema for sampling/createMessage in the resolved era" : `Invalid sampling result: ${validatedResult.message}`); - return validatedResult.value; - }; - return handler; - } - assertCapability(capability, method) { - if (!this._serverCapabilities?.[capability]) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support ${capability} (required for ${method})`); - } - /** - * Connects to a server via the given transport and performs the MCP initialization handshake. - * - * @example Basic usage (stdio) - * ```ts source="./client.examples.ts#Client_connect_stdio" - * const client = new Client({ name: 'my-client', version: '1.0.0' }); - * const transport = new StdioClientTransport({ command: 'my-mcp-server' }); - * await client.connect(transport); - * ``` - * - * @example Streamable HTTP with SSE fallback - * ```ts source="./client.examples.ts#Client_connect_sseFallback" - * const baseUrl = new URL(url); - * - * try { - * // Try modern Streamable HTTP transport first - * const client = new Client({ name: 'my-client', version: '1.0.0' }); - * const transport = new StreamableHTTPClientTransport(baseUrl); - * await client.connect(transport); - * return { client, transport }; - * } catch { - * // Fall back to legacy SSE transport - * const client = new Client({ name: 'my-client', version: '1.0.0' }); - * const transport = new SSEClientTransport(baseUrl); - * await client.connect(transport); - * return { client, transport }; - * } - * ``` - */ - async connect(transport, options) { - if (options?.prior != null) return this._connectFromPrior(transport, validatePrior(options.prior), options); - const negotiation = resolveVersionNegotiation(this._versionNegotiation, this._supportedProtocolVersionsOption); - if (negotiation.kind !== "legacy") return this._connectNegotiated(transport, negotiation, options); - return this._connectPlainLegacy(transport, options); - } - /** - * Plain legacy connect — the pinned 2025 sequence, byte-untouched. The - * `mode: 'legacy'` connect body, shared with the `prior` legacy verdict. - */ - async _connectPlainLegacy(transport, options) { - await super.connect(transport); - if (transport.sessionId !== void 0) { - const negotiatedProtocolVersion = this._negotiatedProtocolVersion; - if (negotiatedProtocolVersion !== void 0) transport.setProtocolVersion?.(negotiatedProtocolVersion); - return; - } - this._resetConnectionState(); - await this._legacyHandshake(transport, options); - } - /** - * The 2025 `initialize` handshake — the body of the plain legacy connect and - * the `'auto'`-mode fallback path (same `initialize` body, zero 2026 headers; - * on the stdio sibling path it opens the session child's fresh pipe, in the - * in-place modes it rides the probed connection). Callers clear the negotiated protocol version before - * the handshake; its completion sets the negotiated (legacy) version. - */ - async _legacyHandshake(transport, options) { - const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); - try { - const offeredVersion = legacyVersions[0]; - if (offeredVersion === void 0) throw new SdkError(SdkErrorCode.EraNegotiationFailed, "Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version"); - const result = await this.request({ - method: "initialize", - params: { - protocolVersion: offeredVersion, - capabilities: this._capabilities, - clientInfo: this._clientInfo - } - }, options); - if (result === void 0) throw new Error(`Server sent invalid initialize result: ${result}`); - if (!legacyVersions.includes(result.protocolVersion)) throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); - this._serverCapabilities = result.capabilities; - this._serverVersion = result.serverInfo; - this._cache.setServerIdentity(this._deriveServerIdentity(transport)); - if (transport.setProtocolVersion) transport.setProtocolVersion(result.protocolVersion); - this._instructions = result.instructions; - await this.notification({ method: "notifications/initialized" }); - this._negotiatedProtocolVersion = result.protocolVersion; - if (this._listChangedConfig) this._setupListChangedHandlers(this._listChangedConfig); - } catch (error2) { - this.close(); - throw error2; - } - } - /** - * Negotiated connect (mode `'auto'` or `{ pin }`): probe with `server/discover` - * before the Protocol machinery attaches — on a disposable sibling process for - * the SDK's stdio transport, in place otherwise — then either establish the - * modern era or perform the plain legacy handshake. - */ - async _connectNegotiated(transport, negotiation, options) { - if (transport.sessionId !== void 0) { - await super.connect(transport); - const negotiatedProtocolVersion = this._negotiatedProtocolVersion; - if (negotiatedProtocolVersion !== void 0 && transport.setProtocolVersion) transport.setProtocolVersion(negotiatedProtocolVersion); - return; - } - this._resetConnectionState(); - let result; - try { - const transportKind = detectProbeTransportKind(transport); - const baseDeps = { - clientInfo: this._clientInfo, - capabilities: this._capabilities, - environment: detectProbeEnvironment(), - defaultTimeoutMs: options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC - }; - const stdioParams = transportKind === "stdio" ? readStdioServerParams(transport) : void 0; - result = stdioParams === void 0 ? await negotiateEra(negotiation, { - ...baseDeps, - transport, - transportKind - }) : await negotiateStdioViaSibling(negotiation, transport, stdioParams, baseDeps); - } catch (error2) { - await transport.close().catch(() => { - }); - disarmSpentCloseGuard(transport); - throw error2; - } - disarmSpentCloseGuard(transport); - await super.connect(transport); - if (result.era === "legacy") { - await this._legacyHandshake(transport, options); - return; - } - this._serverCapabilities = result.discover.capabilities; - this._serverVersion = serverInfoFromDiscover(result.discover); - this._cache.setServerIdentity(this._deriveServerIdentity(transport)); - this._instructions = result.discover.instructions; - this._discoverResult = result.discover; - this._negotiatedProtocolVersion = result.version; - if (transport.setProtocolVersion) transport.setProtocolVersion(result.version); - if (this._listChangedConfig) { - const config2 = this._listChangedConfig; - const advertised = this._serverCapabilities; - const effective = { - ...config2.tools && advertised?.tools?.listChanged && { tools: config2.tools }, - ...config2.prompts && advertised?.prompts?.listChanged && { prompts: config2.prompts }, - ...config2.resources && advertised?.resources?.listChanged && { resources: config2.resources } - }; - let handlersRegistered = true; - try { - this._setupListChangedHandlers(effective); - } catch (error2) { - handlersRegistered = false; - this.onerror?.(error2 instanceof Error ? error2 : new Error(String(error2))); - } - const filter = handlersRegistered ? { - ...effective.tools && { toolsListChanged: true }, - ...effective.prompts && { promptsListChanged: true }, - ...effective.resources && { resourcesListChanged: true } - } : {}; - if (Object.keys(filter).length > 0) { - const ackAbort = new AbortController(); - const onConnectAbort = () => ackAbort.abort(options?.signal?.reason); - if (options?.signal?.aborted) onConnectAbort(); - options?.signal?.addEventListener("abort", onConnectAbort); - try { - this._autoOpenedSubscription = await this.listen(filter, { - timeout: options?.timeout, - signal: ackAbort.signal - }); - } catch (error2) { - if (options?.signal?.aborted) { - await this.close().catch(() => { - }); - throw error2; - } - this.onerror?.(error2 instanceof Error ? error2 : new Error(String(error2))); - } finally { - options?.signal?.removeEventListener("abort", onConnectAbort); - } - } - } - } - /** - * Connect from a validated {@linkcode PriorDiscovery}: the modern arm - * adopts the `DiscoverResult` (zero round trips; `EraNegotiationFailed` - * on no 2026-07-28+ overlap), the legacy arm runs the plain legacy connect. - */ - async _connectFromPrior(transport, prior, options) { - if (prior.kind === "legacy") return this._connectPlainLegacy(transport, options); - const discover = prior.discover; - this._resetConnectionState(); - const explicit = this._supportedProtocolVersionsOption; - const version2 = (explicit && modernProtocolVersions(explicit).length > 0 ? modernProtocolVersions(explicit) : SUPPORTED_MODERN_PROTOCOL_VERSIONS).find((v) => discover.supportedVersions.includes(v)); - if (version2 === void 0) throw new SdkError(SdkErrorCode.EraNegotiationFailed, "connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback."); - await super.connect(transport); - this._discoverResult = discover; - this._serverCapabilities = discover.capabilities; - this._serverVersion = serverInfoFromDiscover(discover); - this._cache.setServerIdentity(this._deriveServerIdentity(transport)); - this._instructions = discover.instructions; - this._negotiatedProtocolVersion = version2; - transport.setProtocolVersion?.(version2); - if (this._listChangedConfig) try { - this._setupListChangedHandlers(this._listChangedConfig); - } catch (error2) { - this.onerror?.(error2 instanceof Error ? error2 : new Error(String(error2))); - } - } - /** - * After initialization has completed, this will be populated with the server's reported capabilities. - */ - getServerCapabilities() { - return this._serverCapabilities; - } - /** - * The connected server's self-reported name and version, when it - * identified itself: required on the legacy `initialize` result; a spec - * SHOULD in the discover result's `_meta` on 2026-07-28, so a successful - * modern connect against an anonymous server leaves this `undefined`. - */ - getServerVersion() { - return this._serverVersion; - } - /** - * The connected server's identity for response-cache partitioning. The - * `serverInfo` `name@version` pair when available (required on - * `initialize`; a SHOULD in the discover result's `_meta` since spec PR - * #3002); falls back to the transport's `sessionId`, then to a - * per-connection surrogate. The surrogate matters since #3002 made - * identity optional: without it, two identity-less servers reached over - * sessionId-less transports would share the cache's pre-connect `''` - * partition and read each other's entries — no stable identity means no - * cross-connection cache reuse. The value itself is server-controlled — - * the collision-safety of the storage partition comes from - * {@linkcode ClientResponseCache}'s JSON-array encoding around it, not - * from any character it does or does not contain. - */ - _deriveServerIdentity(transport) { - const v = this._serverVersion; - if (v !== void 0) return `${v.name}@${v.version}`; - return transport.sessionId ?? `anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`; - } - /** - * After initialization has completed, this will be populated with the protocol version negotiated - * during the initialize handshake. When manually reconstructing a transport for reconnection, pass this - * value to the new transport so it continues sending the required `mcp-protocol-version` header. - */ - getNegotiatedProtocolVersion() { - return this._negotiatedProtocolVersion; - } - /** - * After initialization has completed, this returns the protocol era of the - * connection: `'modern'` when the connection negotiated a 2026-07-28+ - * revision (via `server/discover`), `'legacy'` for the 2025-era - * `initialize` handshake, or `undefined` before the connection is - * established. - */ - getProtocolEra() { - const version2 = this._negotiatedProtocolVersion; - if (version2 === void 0) return void 0; - return isModernProtocolVersion(version2) ? "modern" : "legacy"; - } - /** - * After initialization has completed, this may be populated with information about the server's instructions. - */ - getInstructions() { - return this._instructions; - } - /** - * The {@linkcode DiscoverResult} from the last `'auto'`/pinned probe, - * {@linkcode discover} call, or `connect({ prior })` that adopted a - * modern verdict (a legacy verdict leaves this `undefined` — there is no - * `DiscoverResult` on that path). Persistable via `JSON.stringify`; wrap - * as `{ kind: 'modern', discover }` and feed to {@linkcode ConnectOptions} - * `prior`. - */ - getDiscoverResult() { - return this._discoverResult; - } - assertCapabilityForMethod(method) { - switch (method) { - case "logging/setLevel": - if (!this._serverCapabilities?.logging) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "prompts/get": - case "prompts/list": - if (!this._serverCapabilities?.prompts) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - case "resources/subscribe": - case "resources/unsubscribe": - if (!this._serverCapabilities?.resources) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); - if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resource subscriptions (required for ${method})`); - break; - case "tools/call": - case "tools/list": - if (!this._serverCapabilities?.tools) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); - break; - case "completion/complete": - if (!this._serverCapabilities?.completions) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); - break; - case "initialize": - break; - case "server/discover": - break; - case "ping": - break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/roots/list_changed": - if (!this._capabilities.roots?.listChanged) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support roots list changed notifications (required for ${method})`); - break; - case "notifications/initialized": - break; - case "notifications/cancelled": - break; - case "notifications/progress": - break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "sampling/createMessage": - if (!this._capabilities.sampling) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support sampling capability (required for ${method})`); - break; - case "elicitation/create": - if (!this._capabilities.elicitation) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation capability (required for ${method})`); - break; - case "roots/list": - if (!this._capabilities.roots) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support roots capability (required for ${method})`); - break; - case "ping": - break; - } - } - async ping(options) { - return this.request({ method: "ping" }, options); - } - /** - * Send `server/discover` (2026-07-28+) and record the result for - * {@linkcode getDiscoverResult}. - */ - async discover(options) { - const result = await this._requestWithSchema({ method: "server/discover" }, DiscoverResultSchema, options); - this._discoverResult = result; - return result; - } - /** Requests argument autocompletion suggestions from the server for a prompt or resource. */ - async complete(params, options) { - return this.request({ - method: "completion/complete", - params - }, options); - } - /** - * Sets the minimum severity level for log messages sent by the server. - * - * @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 setLoggingLevel(level, options) { - return this.request({ - method: "logging/setLevel", - params: { level } - }, options); - } - /** Retrieves a prompt by name from the server, passing the given arguments for template substitution. */ - async getPrompt(params, options) { - return this.request({ - method: "prompts/get", - params - }, options); - } - /** - * Lists available prompts. - * - * Called without a `cursor` (the common case), this walks every page and - * returns the complete aggregated list with no `nextCursor`; the - * aggregate is also written to the {@linkcode ResponseCacheStore}. Pass an - * explicit `{ cursor }` to fetch a single page and walk pagination - * yourself — the per-page path returns the server's raw page (with - * `nextCursor` for the next call) and does not write the response cache. - * The auto-aggregate path is capped by - * {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); the per-page path - * is not. - * - * Returns an empty list if the server does not advertise prompts capability - * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). - * - * @example - * ```ts source="./client.examples.ts#Client_listPrompts_pagination" - * // No cursor → all pages aggregated for you. - * const { prompts } = await client.listPrompts(); - * console.log( - * 'Available prompts:', - * prompts.map(p => p.name) - * ); - * ``` - */ - async listPrompts(params, options) { - if (!this._serverCapabilities?.prompts && !this._enforceStrictCapabilities) { - console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"); - return { prompts: [] }; - } - if (params?.cursor !== void 0) return this.request({ - method: "prompts/list", - params - }, options); - const hit = await this._serveFromCache("prompts/list", void 0, options); - if (hit !== void 0) return hit; - return this._listAllPages("prompts/list", params, options, (acc, page) => acc.prompts.push(...page.prompts)); - } - /** - * Lists available resources. - * - * Called without a `cursor` (the common case), this walks every page and - * returns the complete aggregated list with no `nextCursor`; the - * aggregate is also written to the {@linkcode ResponseCacheStore}. Pass an - * explicit `{ cursor }` to fetch a single page and walk pagination - * yourself — the per-page path returns the server's raw page (with - * `nextCursor` for the next call) and does not write the response cache. - * The auto-aggregate path is capped by - * {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); the per-page path - * is not. - * - * Returns an empty list if the server does not advertise resources capability - * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). - * - * @example - * ```ts source="./client.examples.ts#Client_listResources_pagination" - * // No cursor → all pages aggregated for you. - * const { resources } = await client.listResources(); - * console.log( - * 'Available resources:', - * resources.map(r => r.name) - * ); - * ``` - */ - async listResources(params, options) { - if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) { - console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"); - return { resources: [] }; - } - if (params?.cursor !== void 0) return this.request({ - method: "resources/list", - params - }, options); - const hit = await this._serveFromCache("resources/list", void 0, options); - if (hit !== void 0) return hit; - return this._listAllPages("resources/list", params, options, (acc, page) => acc.resources.push(...page.resources)); - } - /** - * Lists available resource URI templates for dynamic resources. - * - * Called without a `cursor`, this walks every page and returns the - * complete aggregated list with no `nextCursor`; the aggregate is - * also written to the {@linkcode ResponseCacheStore}. Pass an explicit - * `{ cursor }` to fetch a single page — see - * {@linkcode listResources | listResources()} for the per-page contract. - * - * Returns an empty list if the server does not advertise resources capability - * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). - */ - async listResourceTemplates(params, options) { - if (!this._serverCapabilities?.resources && !this._enforceStrictCapabilities) { - console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"); - return { resourceTemplates: [] }; - } - if (params?.cursor !== void 0) return this.request({ - method: "resources/templates/list", - params - }, options); - const hit = await this._serveFromCache("resources/templates/list", void 0, options); - if (hit !== void 0) return hit; - return this._listAllPages("resources/templates/list", params, options, (acc, page) => acc.resourceTemplates.push(...page.resourceTemplates)); - } - /** - * Walk every page of a paginated list verb, aggregate, and write ONE - * entry to the response cache. Internal — backs the public `list*` - * methods' no-`cursor` auto-aggregate path. Page 1's result object is - * mutated in place (its items array is extended; `nextCursor` is - * cleared); page-1 metadata (`ttlMs`, `cacheScope`, `_meta`) is preserved. - * A `nextCursor` that repeats stops the walk (defence against a - * non-converging server, mcp.d's `drainList` guard); - * {@linkcode ClientOptions.listMaxPages} is a hard cap — hitting it - * throws, so a partial aggregate is never cached. The - * captured-generation guard skips the write when a `list_changed` landed - * mid-walk, so the eviction is never overwritten by a stale aggregate. - * `finalize` runs on the complete aggregate before the cache write — the - * SEP-2243 invalid-`x-mcp-header` exclusion hooks here so the cached - * `tools/list` entry is already filtered. - * - * The caller's `baseParams` (everything except `cursor`) is threaded into - * every page request — page 1 sends `{...baseParams}`, later pages - * `{...baseParams, cursor}` — so a typed, documented `_meta` (e.g. W3C - * trace context) supplied to the public `list*()` reaches every wire - * request the walk issues. - */ - async _listAllPages(method, baseParams, options, append, finalize2) { - const bypass = options?.cacheMode === "bypass"; - const generation = this._cache.captureGeneration(method); - const acc = await this.request({ - method, - ...baseParams && { params: { ...baseParams } } - }, options); - let cursor = acc.nextCursor; - const seen = /* @__PURE__ */ new Set(); - let pages = 1; - while (cursor !== void 0 && !seen.has(cursor)) { - if (this._listMaxPages !== 0 && pages >= this._listMaxPages) throw new SdkError(SdkErrorCode.ListPaginationExceeded, `${method}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`, { - method, - listMaxPages: this._listMaxPages - }); - seen.add(cursor); - const page = await this.request({ - method, - params: { - ...baseParams, - cursor - } - }, options); - append(acc, page); - cursor = page.nextCursor; - pages++; - } - delete acc.nextCursor; - finalize2?.(acc); - if (bypass) return acc; - await this._cache.write(method, acc, generation, this._freshness(acc)); - return acc; - } - /** - * Compute the {@linkcode ClientResponseCache.write} freshness payload from - * a cacheable result body. The single seam through which the client reads - * `ttlMs`/`cacheScope` (mcp.d's `cachedFetch` engine). The fields pass - * through the loose result schema, so they are read off the runtime body; - * a missing `ttlMs` falls back to - * {@linkcode ClientOptions | ClientOptions.defaultCacheTtlMs}; an explicit server-sent - * `ttlMs` (including `0` — the spec's "immediately stale") is honoured - * as-is. The default of `0` means `expiresAt === now()` ⇒ never served, - * only stored. A missing `cacheScope` is treated as `'private'` — the - * spec's `'public'` grant ("any client … MAY serve to any user") is too - * strong to infer by default, and matches this SDK's server-side stamp - * default. - */ - _freshness(result, params) { - const body = result; - const ttlMs = typeof body.ttlMs === "number" ? body.ttlMs : this._defaultCacheTtlMs; - const scope = body.cacheScope === "public" ? "public" : "private"; - return { - expiresAt: this._cache.now() + Math.min(Math.max(0, ttlMs), MAX_CACHE_TTL_MS), - scope, - params - }; - } - /** - * The cache-serving front of every cacheable verb (mcp.d's `cachedFetch` - * read half): under `cacheMode: 'use'` (the default), a fresh held entry - * is served and the round trip is skipped. `'refresh'` and `'bypass'` - * always fetch (the caller decides whether to write). Freshness and - * decoding live in {@linkcode ClientResponseCache.read}; every hit is - * freshly parsed, so the caller owns it outright. A custom store - * whose `get()` rejects is routed to `onerror` and treated as a miss — - * cache bookkeeping never blocks a request from reaching the wire. - */ - async _serveFromCache(method, params, options) { - if (options?.cacheMode === "bypass" || options?.cacheMode === "refresh") return void 0; - const hit = await this._cache.read(method, params).catch((error2) => void this._reportStoreError(error2)); - if (hit !== void 0) { - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)); - } - return hit.value; - } - } - /** Route a custom-store failure to `onerror` without aborting the surrounding dispatch. */ - _reportStoreError(e) { - this.onerror?.(e instanceof Error ? e : new Error(String(e))); - } - /** - * Compile a single tool's `outputSchema`. Passed as the compile callback to - * {@linkcode ClientResponseCache.outputValidator} so the cache class stays - * free of any validator-provider dependency, and called directly for the - * `options.toolDefinition` path of {@linkcode callTool} (a one-off - * caller-supplied definition is compiled in isolation and never enters the - * cache, so it cannot poison the listed tool of the same name). - * - * Returns `undefined` when the tool has no `outputSchema`, or a - * discriminated `{ok}` result otherwise. SEP-2106: ANY throw from the - * validator engine — unsupported `$schema` dialect, invalid `pattern` - * regex, unresolvable `$ref`, or any other engine error — is captured as - * `{ok: false, compileError}` so one bad schema does not poison the rest - * of the listing; `callTool()` surfaces it as an `InvalidParams` error - * before the request. The `{ok}` discriminator (not - * `compileError !== undefined`) means a custom provider that does - * `throw undefined` is still treated as a captured failure. - */ - _compileOutputValidator(tool) { - if (!tool.outputSchema) return void 0; - try { - return { - ok: true, - validator: this._jsonSchemaValidator.getValidator(tool.outputSchema) - }; - } catch (error2) { - return { - ok: false, - compileError: error2 - }; - } - } - /** - * Resolve the SEP-2243 `x-mcp-header` declaration scan for a tool name. - * - * The caller-supplied `toolDefinition` escape hatch wins; otherwise the - * cached `tools/list` entry (via the cache's `toolDefinition`) is the - * source. Freshness is the response cache's lifecycle: `list_changed` - * evicts, otherwise the held schema is the best information available - * regardless of age, and a stale schema is recovered through the - * `HEADER_MISMATCH` → evict-refetch-retry path in {@linkcode callTool}. - * On a miss the call proceeds without `Mcp-Param-*` headers (the spec's - * "client SHOULD send without custom headers" guidance) and relies on the - * same recovery. - */ - async _resolveXMcpHeaderScan(name, override) { - const tool = override ?? await this._cache.toolDefinition(name); - return tool === void 0 ? void 0 : scanXMcpHeaderDeclarations(tool.inputSchema); - } - /** - * Reads the contents of a resource by URI. - * - * Honours the result's `ttlMs`/`cacheScope` (SEP-2549): a still-fresh - * cached body for the same `uri` is returned without a round trip - * (`cacheMode: 'use'`, the default). The cache key is `{method, uri}` - * partitioned by the resolved scope — `'private'` (the default when the - * server omits the field) is stored under this client's - * {@linkcode ClientOptions | ClientOptions.cachePartition}, so a shared - * store cannot serve one principal's resource body to another. Unlike the - * list verbs, a result whose resolved TTL is ≤0 is **not** stored - * (`resources/read` has no derived index and the URI keyspace is - * unbounded). - */ - async readResource(params, options) { - const hit = await this._serveFromCache("resources/read", params.uri, options); - if (hit !== void 0) return hit; - const generation = this._cache.captureGeneration("resources/read", params.uri); - const result = await this.request({ - method: "resources/read", - params - }, options); - if (options?.cacheMode !== "bypass") { - const freshness = this._freshness(result, params.uri); - if (freshness.expiresAt > this._cache.now()) await this._cache.write("resources/read", result, generation, freshness); - else if (options?.cacheMode === "refresh") await this._cache.evictKey("resources/read", params.uri); - } - return result; - } - /** Subscribes to change notifications for a resource. The server must support resource subscriptions. */ - async subscribeResource(params, options) { - return this.request({ - method: "resources/subscribe", - params - }, options); - } - /** Unsubscribes from change notifications for a resource. */ - async unsubscribeResource(params, options) { - return this.request({ - method: "resources/unsubscribe", - params - }, options); - } - /** - * Opens a `subscriptions/listen` stream (protocol revision 2026-07-28). - * - * Resolves once the server's `notifications/subscriptions/acknowledged` - * arrives (the standard request timeout applies to this ack phase). Change - * notifications delivered on the stream are dispatched to the existing - * {@linkcode setNotificationHandler} registrations — the same handlers the - * 2025-era unsolicited notifications fire on a legacy connection — so - * `listen()` is era-transparent for consumers that already register those. - * - * `close()` tears the subscription down by aborting the listen request's - * `requestSignal` (closes the SSE stream where the transport honors it) - * AND sending `notifications/cancelled` referencing the listen request id - * — both, unconditionally, so any spec-compliant server on any transport - * sees the cancel. No automatic re-listen — call `listen()` again to - * re-establish. - * - * On a 2025-era connection this throws a typed - * {@linkcode SdkErrorCode.MethodNotSupportedByProtocolVersion} steering to - * `resources/subscribe` and `ClientOptions.listChanged` (the legacy - * unsolicited delivery model still applies there); no transparent shim. - */ - async listen(filter, options) { - if (this.transport === void 0) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); - const negotiated = this._negotiatedProtocolVersion; - if (negotiated === void 0 || !isModernProtocolVersion(negotiated)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${negotiated ?? "none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`, { - method: "subscriptions/listen", - protocolVersion: negotiated - }); - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = new AbortController(); - const listenId = `listen:${this._nextListenId++}`; - let state = "opening"; - let ackTimer; - let onCallerAbort; - let resolveOpening; - let rejectOpening; - const opening = new Promise((resolve, reject) => { - resolveOpening = resolve; - rejectOpening = reject; - }); - let resolveClosed; - const closed = new Promise((resolve) => { - resolveClosed = resolve; - }); - const settle = (outcome) => { - if (state === "closed") return; - const wasOpening = state === "opening"; - if (ackTimer !== void 0) { - clearTimeout(ackTimer); - ackTimer = void 0; - } - if ("ack" in outcome) { - state = "open"; - resolveOpening(outcome.ack); - return; - } - state = "closed"; - if (onCallerAbort !== void 0) options?.signal?.removeEventListener("abort", onCallerAbort); - this._listenState.delete(listenId); - requestAbort.abort(); - resolveClosed(outcome.cause); - if (wasOpening) rejectOpening(outcome.error ?? new SdkError(SdkErrorCode.ConnectionClosed, "subscriptions/listen closed before the server acknowledged")); - }; - const wireTeardown = async () => { - requestAbort.abort(); - await this.notification({ - method: "notifications/cancelled", - params: { requestId: listenId } - }).catch(() => { - }); - }; - const close = async () => { - if (state === "closed") return; - settle({ cause: "local" }); - await wireTeardown(); - }; - this._listenState.set(listenId, { settle }); - const ackTimeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - ackTimer = setTimeout(() => { - settle({ - cause: "remote", - error: new SdkError(SdkErrorCode.RequestTimeout, "subscriptions/listen ack timed out", { timeout: ackTimeout }) - }); - wireTeardown().catch(() => { - }); - }, ackTimeout); - if (options?.signal) { - const callerSignal = options.signal; - onCallerAbort = () => { - if (state === "closed") return; - const reason = callerSignal.reason; - settle({ - cause: "local", - error: reason instanceof Error ? reason : new Error(String(reason ?? "Aborted")) - }); - wireTeardown().catch(() => { - }); - }; - callerSignal.addEventListener("abort", onCallerAbort, { once: true }); - } - const jsonrpcRequest = { - jsonrpc: "2.0", - id: listenId, - method: "subscriptions/listen", - params: { - _meta: { ...this._outboundMetaEnvelope() }, - notifications: filter - } - }; - try { - await this.transport.send(jsonrpcRequest, { - requestSignal: requestAbort.signal, - onRequestStreamEnd: () => settle({ - cause: "remote", - error: /* @__PURE__ */ new Error("subscriptions/listen: stream ended") - }) - }); - } catch (error2) { - settle({ - cause: "remote", - error: error2 instanceof Error ? error2 : new Error(String(error2)) - }); - } - return { - honoredFilter: await opening, - close, - closed - }; - } - /** - * The subscription auto-opened by `ClientOptions.listChanged` on a modern - * connection — the listen filter is the intersection of the configured - * sub-options and the server-advertised `listChanged` capabilities. - * `undefined` on a legacy connection, before connect, or when that - * intersection is empty (auto-open skipped). Exposed so the consumer can - * `close()` it. - */ - get autoOpenedSubscription() { - return this._autoOpenedSubscription; - } - /** - * Transport-level demux for `subscriptions/listen` notifications, before - * any decoding/era-gating/handler dispatch. Consumes the leading - * `notifications/subscriptions/acknowledged` referencing a live - * subscription id (resolves the ack waiter) and an inbound - * `notifications/cancelled` referencing a live string-typed subscription - * id (server-side teardown on stdio). Change notifications carrying a - * subscription id pass through to the existing registered handlers via - * `super`. An unmatched ack/cancelled is NOT consumed: it reaches - * `setNotificationHandler` / `fallbackNotificationHandler` instead of - * being silently swallowed. - */ - _onnotification(raw, extra) { - const evicted = Object.hasOwn(LIST_CHANGED_EVICTIONS, raw.method) ? LIST_CHANGED_EVICTIONS[raw.method] : void 0; - if (raw.method === "notifications/resources/updated") { - const uri = raw.params?.uri; - if (typeof uri === "string") this._cache.evictKey("resources/read", uri); - } else if (evicted !== void 0) for (const method of evicted) this._cache.evict(method); - if (raw.method === "notifications/subscriptions/acknowledged") { - const subscriptionId = raw.params?._meta?.[SUBSCRIPTION_ID_META_KEY]; - const entry = typeof subscriptionId === "string" ? this._listenState.get(subscriptionId) : void 0; - if (entry !== void 0) { - const honored = this._wireCodec().validateNotification("notifications/subscriptions/acknowledged", raw); - entry.settle({ ack: honored.ok ? honored.value.params.notifications : {} }); - return; - } - } - if (raw.method === "notifications/cancelled") { - const cancelledId = raw.params?.requestId; - const entry = typeof cancelledId === "string" ? this._listenState.get(cancelledId) : void 0; - if (entry !== void 0) { - entry.settle({ - cause: "remote", - error: /* @__PURE__ */ new Error("subscriptions/listen: server cancelled the subscription") - }); - return; - } - } - super._onnotification(raw, extra); - } - /** - * Transport-level demux for `subscriptions/listen` responses. A JSON-RPC - * ERROR for the listen id is the server's pre-ack capacity/params - * rejection; a JSON-RPC RESULT for the listen id is the spec's - * `SubscriptionsListenResult` — the server's GRACEFUL-close signal (sent - * on shutdown). A string-id response that matches a live `_listenState` - * entry is consumed here (Protocol's `_responseHandlers` map is keyed by - * NUMBER and never holds a listen id, so passing a string-id response - * through would surface as "unknown message ID" via `onerror`). - */ - _onresponse(response) { - const id = response.id; - const entry = typeof id === "string" ? this._listenState.get(id) : void 0; - if (entry !== void 0) { - if (isJSONRPCErrorResponse(response)) entry.settle({ - cause: "remote", - error: ProtocolError.fromError(response.error.code, response.error.message, response.error.data) - }); - else entry.settle({ - cause: "graceful", - error: new SdkError(SdkErrorCode.ConnectionClosed, "subscriptions/listen: server closed the subscription gracefully before acknowledging") - }); - return; - } - super._onresponse(response); - } - /** - * Settle every live per-listen state machine on a transport-initiated - * close (the server dropping the connection on stdio/InMemory) before - * Protocol's `_onclose` tears the transport down. The base - * `_responseHandlers` settlement does not reach `_listenState` (listen - * ids are never registered there), so without this override a remote - * close would leave an in-flight `listen()` / open `McpSubscription` - * hanging. - */ - _onclose() { - if (this._listenState.size > 0) { - const reason = new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed"); - for (const entry of this._listenState.values()) entry.settle({ - cause: "remote", - error: reason - }); - this._listenState.clear(); - } - super._onclose(); - } - /** - * Calls a tool on the connected server and returns the result. Automatically validates structured output - * if the tool has an `outputSchema`. - * - * Tool results have two error surfaces: `result.isError` for tool-level failures (the tool ran but reported - * a problem), and thrown {@linkcode ProtocolError} for protocol-level failures or {@linkcode SdkError} for - * SDK-level issues (timeouts, missing capabilities). - * - * @example Basic usage - * ```ts source="./client.examples.ts#Client_callTool_basic" - * const result = await client.callTool({ - * name: 'calculate-bmi', - * arguments: { weightKg: 70, heightM: 1.75 } - * }); - * - * // Tool-level errors are returned in the result, not thrown - * if (result.isError) { - * console.error('Tool error:', result.content); - * return; - * } - * - * console.log(result.content); - * ``` - * - * @example Structured output - * ```ts source="./client.examples.ts#Client_callTool_structuredOutput" - * const result = await client.callTool({ - * name: 'calculate-bmi', - * arguments: { weightKg: 70, heightM: 1.75 } - * }); - * - * // Machine-readable output for the client application. SEP-2106: structuredContent is - * // `unknown` (any JSON value). Check for presence with `!== undefined` and narrow before use. - * if (result.structuredContent !== undefined) { - * const sc: unknown = result.structuredContent; // e.g. { bmi: 22.86 } - * if (typeof sc === 'object' && sc !== null && 'bmi' in sc) { - * console.log(sc.bmi); - * } - * } - * ``` - */ - async callTool(params, options) { - const mirroringActive = this.getProtocolEra() === "modern" && detectProbeEnvironment() !== "browser"; - const buildSendOptions = async () => { - if (!mirroringActive) return options; - let scan; - try { - scan = await this._resolveXMcpHeaderScan(params.name, options?.toolDefinition); - } catch (error2) { - this._reportStoreError(error2); - } - if (!scan?.valid || scan.declarations.length === 0) return options; - const paramHeaders = buildMcpParamHeaders(scan.declarations, params.arguments); - return Object.keys(paramHeaders).length === 0 ? options : { - ...options, - headers: { - ...options?.headers, - ...paramHeaders - } - }; - }; - let compiled = options?.toolDefinition === void 0 ? await this._cache.outputValidator(params.name, (tool) => this._compileOutputValidator(tool)).catch((error2) => void this._reportStoreError(error2)) : this._compileOutputValidator(options.toolDefinition); - const assertCompiled = () => { - if (compiled === void 0 || compiled.ok) return; - const err = compiled.compileError; - const message2 = (err instanceof Error ? err.message : String(err)).slice(0, 200); - throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool '${params.name}' has an invalid outputSchema: ${message2}`); - }; - assertCompiled(); - let result; - try { - result = await this.request({ - method: "tools/call", - params - }, await buildSendOptions()); - } catch (error2) { - const isHeaderMismatch = error2 instanceof ProtocolError && error2.code === HEADER_MISMATCH_ERROR_CODE; - if (!mirroringActive || !isHeaderMismatch || options?.toolDefinition !== void 0) throw error2; - const refreshOptions = { - signal: options?.signal, - timeout: options?.timeout, - cacheMode: "refresh" - }; - await this._cache.evict("tools/list"); - await this.listTools(void 0, refreshOptions).catch((error_) => this._reportStoreError(error_)); - compiled = await this._cache.outputValidator(params.name, (tool) => this._compileOutputValidator(tool)).catch((error_) => void this._reportStoreError(error_)); - assertCompiled(); - result = await this.request({ - method: "tools/call", - params - }, await buildSendOptions()); - } - const validator = compiled !== void 0 && compiled.ok ? compiled.validator : void 0; - if (validator) { - if (result.structuredContent === void 0 && !result.isError) throw new ProtocolError(ProtocolErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); - if (result.structuredContent !== void 0 && !result.isError) try { - const validationResult = validator(result.structuredContent); - if (!validationResult.valid) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); - } catch (error2) { - if (error2 instanceof ProtocolError) throw error2; - throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Failed to validate structured content: ${error2 instanceof Error ? error2.message : String(error2)}`); - } - } - return result; - } - /** - * Lists available tools. - * - * Called without a `cursor` (the common case), this walks every page and - * returns the complete aggregated list with no `nextCursor`; the - * aggregate is also written to the {@linkcode ResponseCacheStore} (the - * source for {@linkcode callTool | callTool()}'s output-schema validation - * and SEP-2243 `Mcp-Param-*` header mirroring). Pass an explicit - * `{ cursor }` to fetch a single page and walk pagination yourself — the - * per-page path returns the server's raw page (with `nextCursor` for the - * next call) and does not write the response cache. The auto-aggregate - * path is capped by {@linkcode ClientOptions | ClientOptions.listMaxPages} (default 64); - * the per-page path is not. - * - * Returns an empty list if the server does not advertise tools capability - * (or throws if {@linkcode ClientOptions.enforceStrictCapabilities} is enabled). - * - * @example - * ```ts source="./client.examples.ts#Client_listTools_pagination" - * // No cursor → all pages aggregated for you. - * const { tools } = await client.listTools(); - * console.log( - * 'Available tools:', - * tools.map(t => t.name) - * ); - * ``` - */ - async listTools(params, options) { - if (!this._serverCapabilities?.tools && !this._enforceStrictCapabilities) { - console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"); - return { tools: [] }; - } - if (params?.cursor !== void 0) { - const page = await this.request({ - method: "tools/list", - params - }, options); - this._excludeInvalidXMcpHeaderTools(page); - return page; - } - const hit = await this._serveFromCache("tools/list", void 0, options); - if (hit !== void 0) return hit; - return this._listAllPages("tools/list", params, options, (acc, page) => acc.tools.push(...page.tools), (acc) => this._excludeInvalidXMcpHeaderTools(acc)); - } - /** - * SEP-2243 (protocol revision 2026-07-28): a Streamable HTTP client MUST - * exclude tool definitions whose `x-mcp-header` declarations violate the - * constraints, and SHOULD log a warning naming the tool and the reason. - * Applied to the CACHED aggregated `tools/list` result (so the entry - * mirroring reads never holds an unmirrorable tool) AND to every public - * per-page {@linkcode listTools | listTools()} return (the spec's MUST - * has no carve-out for paginated reads). The gate is era-only on - * non-stdio transports — `detectProbeTransportKind` cannot distinguish a - * real HTTP transport from in-memory/custom transports (it only - * positively recognizes stdio), and over-excluding on a non-HTTP modern - * connection is harmless: those transports never carry per-request - * headers, so an excluded tool would have been uncallable on a Streamable - * HTTP arm of the same server. Mutates `result.tools` in place. - */ - _excludeInvalidXMcpHeaderTools(result) { - if (this.getProtocolEra() !== "modern" || !this.transport || detectProbeTransportKind(this.transport) === "stdio") return; - const filtered = result.tools.filter((tool) => { - const scan = scanXMcpHeaderDeclarations(tool.inputSchema); - if (!scan.valid) { - console.warn(`[mcp-sdk] excluding tool '${tool.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${scan.reason}`); - return false; - } - return true; - }); - if (filtered.length !== result.tools.length) result.tools = filtered; - } - /** - * Set up a single list changed handler. - * @internal - */ - _setupListChangedHandler(listType, notificationMethod, options, fetcher) { - const parseResult = parseSchema(ListChangedOptionsBaseSchema, options); - if (!parseResult.success) throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); - if (typeof options.onChanged !== "function") throw new TypeError(`Invalid ${listType} listChanged options: onChanged must be a function`); - const { autoRefresh, debounceMs } = parseResult.data; - const { onChanged } = options; - const refresh = async () => { - if (!autoRefresh) { - onChanged(null, null); - return; - } - try { - onChanged(null, await fetcher()); - } catch (error2) { - onChanged(error2 instanceof Error ? error2 : new Error(String(error2)), null); - } - }; - const handler = () => { - if (debounceMs) { - const existingTimer = this._listChangedDebounceTimers.get(listType); - if (existingTimer) clearTimeout(existingTimer); - const timer = setTimeout(refresh, debounceMs); - this._listChangedDebounceTimers.set(listType, timer); - } else refresh(); - }; - this.setNotificationHandler(notificationMethod, handler); - } - /** - * Notifies the server that the client's root list has changed. Requires the `roots.listChanged` capability. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to passing paths via tool parameters, resource URIs, or configuration. - */ - async sendRootsListChanged() { - return this.notification({ method: "notifications/roots/list_changed" }); - } - }; - withOAuth = (provider, baseUrl) => (next) => { - return async (input, init) => { - const makeRequest = async () => { - const headers = new Headers(init?.headers); - const tokens = await provider.tokens(); - if (tokens) headers.set("Authorization", `Bearer ${tokens.access_token}`); - return await next(input, { - ...init, - headers - }); - }; - let response = await makeRequest(); - if (response.status === 401) try { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - const result = await auth(provider, { - serverUrl: baseUrl || (typeof input === "string" ? new URL(input).origin : input.origin), - resourceMetadataUrl, - scope, - fetchFn: next - }); - if (result === "REDIRECT") throw new UnauthorizedError("Authentication requires user authorization - redirect initiated"); - if (result !== "AUTHORIZED") throw new UnauthorizedError(`Authentication failed with result: ${result}`); - response = await makeRequest(); - } catch (error2) { - if (error2 instanceof UnauthorizedError) throw error2; - throw new UnauthorizedError(`Failed to re-authenticate: ${error2 instanceof Error ? error2.message : String(error2)}`); - } - if (response.status === 401) throw new UnauthorizedError(`Authentication failed for ${typeof input === "string" ? input : input.toString()}`); - return response; - }; - }; - withLogging = (options = {}) => { - const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; - const defaultLogger = (input) => { - const { method, url: url2, status, statusText, duration: duration3, requestHeaders, responseHeaders, error: error2 } = input; - let message2 = error2 ? `HTTP ${method} ${url2} failed: ${error2.message} (${duration3}ms)` : `HTTP ${method} ${url2} ${status} ${statusText} (${duration3}ms)`; - if (includeRequestHeaders && requestHeaders) { - const reqHeaders = [...requestHeaders.entries()].map(([key, value]) => `${key}: ${value}`).join(", "); - message2 += ` - Request Headers: {${reqHeaders}}`; - } - if (includeResponseHeaders && responseHeaders) { - const resHeaders = [...responseHeaders.entries()].map(([key, value]) => `${key}: ${value}`).join(", "); - message2 += ` - Response Headers: {${resHeaders}}`; - } - if (error2 || status >= 400) console.error(message2); - else console.log(message2); - }; - const logFn = logger || defaultLogger; - return (next) => async (input, init) => { - const startTime = performance.now(); - const method = init?.method || "GET"; - const url2 = typeof input === "string" ? input : input.toString(); - const requestHeaders = includeRequestHeaders ? new Headers(init?.headers) : void 0; - try { - const response = await next(input, init); - const duration3 = performance.now() - startTime; - if (response.status >= statusLevel) logFn({ - method, - url: url2, - status: response.status, - statusText: response.statusText, - duration: duration3, - requestHeaders, - responseHeaders: includeResponseHeaders ? response.headers : void 0 - }); - return response; - } catch (error2) { - logFn({ - method, - url: url2, - status: 0, - statusText: "Network Error", - duration: performance.now() - startTime, - requestHeaders, - error: error2 - }); - throw error2; - } - }; - }; - applyMiddlewares = (...middleware) => { - return (next) => { - let handler = next; - for (const mw of middleware) handler = mw(handler); - return handler; - }; - }; - createMiddleware = (handler) => { - return (next) => (input, init) => handler(next, input, init); - }; - SseError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SseError" }); - } - 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, message2, event) { - super(`SSE error: ${message2}`); - this.code = code; - this.event = event; - stampErrorBrands(this, new.target); - } - }; - SSEClientTransport = class { - _eventSource; - _endpoint; - _abortController; - _url; - _resourceMetadataUrl; - _scope; - _eventSourceInit; - _requestInit; - _authProvider; - _oauthProvider; - _skipIssuerMetadataValidation; - _fetch; - _fetchWithInit; - _protocolVersion; - onclose; - onerror; - onmessage; - constructor(url2, opts) { - this._url = url2; - this._resourceMetadataUrl = void 0; - this._scope = void 0; - this._eventSourceInit = opts?.eventSourceInit; - this._requestInit = opts?.requestInit; - this._skipIssuerMetadataValidation = opts?.skipIssuerMetadataValidation; - if (isOAuthClientProvider(opts?.authProvider)) { - this._oauthProvider = opts.authProvider; - this._authProvider = adaptOAuthProvider(opts.authProvider, { skipIssuerMetadataValidation: opts.skipIssuerMetadataValidation }); - } else this._authProvider = opts?.authProvider; - this._fetch = opts?.fetch; - this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); - } - _last401Response; - async _commonHeaders() { - const headers = {}; - const token = await this._authProvider?.token(); - if (token) headers["Authorization"] = `Bearer ${token}`; - if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion; - const extraHeaders = normalizeHeaders(this._requestInit?.headers); - return new Headers({ - ...headers, - ...extraHeaders - }); - } - _startOrAuth() { - const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch; - return new Promise((resolve, reject) => { - this._eventSource = new EventSource(this._url.href, { - ...this._eventSourceInit, - fetch: async (url2, init) => { - const headers = await this._commonHeaders(); - headers.set("Accept", "text/event-stream"); - const response = await fetchImpl(url2, { - ...init, - headers - }); - if (response.status === 401) { - this._last401Response = response; - if (response.headers.has("www-authenticate")) { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - } - } - return response; - } - }); - this._abortController = new AbortController(); - this._eventSource.onerror = (event) => { - if (event.code === 401 && this._authProvider) { - if (this._authProvider.onUnauthorized && this._last401Response) { - const response = this._last401Response; - this._last401Response = void 0; - this._eventSource?.close(); - this._authProvider.onUnauthorized({ - response, - serverUrl: this._url, - fetchFn: this._fetchWithInit - }).then(() => this._startOrAuth().then(resolve, reject), (error$2) => { - this.onerror?.(error$2); - reject(error$2); - }); - return; - } - const error$1 = new UnauthorizedError(); - reject(error$1); - this.onerror?.(error$1); - return; - } - const error2 = new SseError(event.code, event.message, event); - reject(error2); - this.onerror?.(error2); - }; - this._eventSource.onopen = () => { - }; - this._eventSource.addEventListener("endpoint", (event) => { - const messageEvent = event; - try { - this._endpoint = new URL(messageEvent.data, this._url); - if (this._endpoint.origin !== this._url.origin) throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); - } catch (error2) { - reject(error2); - this.onerror?.(error2); - this.close(); - return; - } - resolve(); - }); - this._eventSource.onmessage = (event) => { - const messageEvent = event; - let message2; - try { - message2 = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); - } catch (error2) { - this.onerror?.(error2); - return; - } - this.onmessage?.(message2); - }; - }); - } - async start() { - if (this._eventSource) throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically."); - return await this._startOrAuth(); - } - async finishAuth(codeOrParams, iss) { - if (!this._oauthProvider) throw new UnauthorizedError("finishAuth requires an OAuthClientProvider"); - const { authorizationCode, iss: issParam } = await resolveAuthorizationCallbackParams(codeOrParams, iss, this._oauthProvider, this._url, { - fetchFn: this._fetchWithInit, - resourceMetadataUrl: this._resourceMetadataUrl - }); - if (await auth(this._oauthProvider, { - serverUrl: this._url, - authorizationCode, - iss: issParam, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit, - skipIssuerMetadataValidation: this._skipIssuerMetadataValidation - }) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize"); - } - async close() { - this._abortController?.abort(); - this._eventSource?.close(); - this.onclose?.(); - } - async send(message2) { - return this._send(message2, false); - } - async _send(message2, isAuthRetry) { - if (!this._endpoint) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); - try { - const headers = await this._commonHeaders(); - headers.set("content-type", "application/json"); - const init = { - ...this._requestInit, - method: "POST", - headers, - body: JSON.stringify(message2), - signal: this._abortController?.signal - }; - const response = await (this._fetch ?? fetch)(this._endpoint, init); - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - if (response.headers.has("www-authenticate")) { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - } - if (this._authProvider.onUnauthorized && !isAuthRetry) { - await this._authProvider.onUnauthorized({ - response, - serverUrl: this._url, - fetchFn: this._fetchWithInit - }); - await response.text?.().catch(() => { - }); - return this._send(message2, true); - } - await response.text?.().catch(() => { - }); - if (isAuthRetry) throw new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, "Server returned 401 after re-authentication", { - status: 401, - statusText: response.statusText - }); - throw new UnauthorizedError(); - } - const text = await response.text?.().catch(() => null); - throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); - } - await response.text?.().catch(() => { - }); - } catch (error2) { - this.onerror?.(error2); - throw error2; - } - } - setProtocolVersion(version2) { - this._protocolVersion = version2; - } - }; - DEFAULT_MAX_STEP_UP_RETRIES = 1; - DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { - initialReconnectionDelay: 1e3, - maxReconnectionDelay: 3e4, - reconnectionDelayGrowFactor: 1.5, - maxRetries: 2 - }; - RESERVED_REQUEST_HEADER_NAMES = /* @__PURE__ */ new Set([ - "authorization", - "content-type", - "mcp-protocol-version", - "mcp-method", - "mcp-name", - "mcp-session-id" - ]); - StreamableHTTPClientTransport = class { - _abortController; - _url; - _resourceMetadataUrl; - _scope; - _requestInit; - _authProvider; - _oauthProvider; - _skipIssuerMetadataValidation; - _fetch; - _fetchWithInit; - _sessionId; - _reconnectionOptions; - _protocolVersion; - _onInsufficientScope; - _maxStepUpRetries; - _serverRetryMs; - _reconnectionScheduler; - _cancelReconnection; - onclose; - onerror; - onmessage; - /** - * Streamable HTTP opens one POST (and SSE response stream) per outbound - * request and honors `TransportSendOptions.requestSignal`. On a 2026-era - * connection the protocol layer aborts that per-request stream as the - * spec cancellation signal instead of POSTing `notifications/cancelled`. - */ - hasPerRequestStream = true; - constructor(url2, opts) { - this._url = url2; - this._resourceMetadataUrl = void 0; - this._scope = void 0; - this._requestInit = opts?.requestInit; - this._skipIssuerMetadataValidation = opts?.skipIssuerMetadataValidation; - if (isOAuthClientProvider(opts?.authProvider)) { - this._oauthProvider = opts.authProvider; - this._authProvider = adaptOAuthProvider(opts.authProvider, { skipIssuerMetadataValidation: opts.skipIssuerMetadataValidation }); - } else this._authProvider = opts?.authProvider; - this._fetch = opts?.fetch; - this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); - this._sessionId = opts?.sessionId; - this._protocolVersion = opts?.protocolVersion; - this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; - this._reconnectionScheduler = opts?.reconnectionScheduler; - this._onInsufficientScope = opts?.onInsufficientScope ?? "reauthorize"; - this._maxStepUpRetries = Math.max(0, opts?.maxStepUpRetries ?? DEFAULT_MAX_STEP_UP_RETRIES); - } - /** - * SEP-2350 step-up: compute the union scope, decide whether refresh must be - * bypassed, and run {@linkcode auth}. Returns the auth result so the caller - * can decide whether to retry. Shared by the POST `_send` path and the GET - * `_startOrAuthSse` path so both apply the same `'throw'` short-circuit, - * the same superset-gated refresh bypass, and the same retry cap. - */ - async _stepUpAuthorize(challenge, stepUpRetries) { - if (this._onInsufficientScope === "throw") throw new InsufficientScopeError({ - requiredScope: challenge.scope, - resourceMetadataUrl: challenge.resourceMetadataUrl, - errorDescription: challenge.errorDescription - }); - if (!this._oauthProvider) throw new InsufficientScopeError({ - requiredScope: challenge.scope, - resourceMetadataUrl: challenge.resourceMetadataUrl, - errorDescription: challenge.errorDescription - }); - if (stepUpRetries >= this._maxStepUpRetries) throw new SdkHttpError(SdkErrorCode.ClientHttpForbidden, `Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`, { - status: 403, - statusText: challenge.statusText ?? "Forbidden", - text: challenge.text - }); - if (challenge.resourceMetadataUrl) this._resourceMetadataUrl = challenge.resourceMetadataUrl; - const tokens = await this._oauthProvider.tokens(); - const unionScope = computeScopeUnion(this._scope, tokens?.scope, challenge.scope); - this._scope = unionScope; - const forceReauthorization = isStrictScopeSuperset(unionScope, tokens?.scope); - return auth(this._oauthProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: unionScope, - forceReauthorization, - fetchFn: this._fetchWithInit, - skipIssuerMetadataValidation: this._skipIssuerMetadataValidation - }); - } - async _commonHeaders() { - const headers = {}; - const token = await this._authProvider?.token(); - if (token) headers["Authorization"] = `Bearer ${token}`; - if (this._sessionId) headers["mcp-session-id"] = this._sessionId; - if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion; - const extraHeaders = normalizeHeaders(this._requestInit?.headers); - return new Headers({ - ...headers, - ...extraHeaders - }); - } - /** - * Body-derived per-request headers: when an outgoing request carries a - * protocol-version claim in its `_meta` envelope (the version negotiation - * probe is the first such sender), `MCP-Protocol-Version` and `Mcp-Method` - * derive from the message itself. The connection-level version slot is - * neither consulted nor mutated; messages without an envelope claim are - * untouched, so no 2026 header can appear on a legacy exchange. - */ - _applyBodyDerivedHeaders(headers, message2) { - if (Array.isArray(message2) || !isJSONRPCRequest(message2)) return; - const envelopeVersion = message2.params?._meta?.[PROTOCOL_VERSION_META_KEY]; - if (typeof envelopeVersion !== "string") return; - headers.set("mcp-protocol-version", envelopeVersion); - headers.set("mcp-method", message2.method); - const params = message2.params; - const nameHeader = message2.method === "resources/read" ? typeof params?.uri === "string" ? params.uri : void 0 : typeof params?.name === "string" ? params.name : void 0; - if (nameHeader !== void 0) headers.set("mcp-name", encodeMcpParamValue(nameHeader)); - } - /** - * `true` when the outbound message is a single request carrying a - * modern-era protocol-version envelope claim — the same predicate that - * gates body-derived `mcp-method`/`mcp-name` emission. Used to confine the - * 400-body-as-ProtocolError delivery to modern-era exchanges only. - */ - _isModernEnvelopedRequest(message2) { - if (Array.isArray(message2) || !isJSONRPCRequest(message2)) return false; - const v = message2.params?._meta?.[PROTOCOL_VERSION_META_KEY]; - return typeof v === "string" && isModernProtocolVersion(v); - } - async _startOrAuthSse(options, isAuthRetry = false, stepUpRetries = 0) { - const { resumptionToken, requestSignal } = options; - const isIntentionalAbort = () => this._abortController?.signal.aborted === true || requestSignal?.aborted === true; - try { - const headers = await this._commonHeaders(); - const types = [...headers.get("accept")?.split(",").map((s3) => s3.trim().toLowerCase()) ?? [], "text/event-stream"]; - headers.set("accept", [...new Set(types)].join(", ")); - if (resumptionToken) headers.set("last-event-id", resumptionToken); - const transportSignal = this._abortController?.signal; - const signal = requestSignal !== void 0 && transportSignal !== void 0 ? anySignal(transportSignal, requestSignal) : requestSignal ?? transportSignal; - const response = await (this._fetch ?? fetch)(this._url, { - ...this._requestInit, - method: "GET", - headers, - signal - }); - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - if (response.headers.has("www-authenticate")) { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = computeScopeUnion(this._scope, scope); - } - if (this._authProvider.onUnauthorized && !isAuthRetry) { - await this._authProvider.onUnauthorized({ - response, - serverUrl: this._url, - fetchFn: this._fetchWithInit - }); - await response.text?.().catch(() => { - }); - return this._startOrAuthSse(options, true, stepUpRetries); - } - await response.text?.().catch(() => { - }); - if (isAuthRetry) throw new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, "Server returned 401 after re-authentication", { - status: 401, - statusText: response.statusText - }); - throw new UnauthorizedError(); - } - if (response.status === 403) { - const { resourceMetadataUrl, scope, error: error2, errorDescription } = extractWWWAuthenticateParams(response); - if (error2 === "insufficient_scope") { - const text = await response.text?.().catch(() => null); - if (await this._stepUpAuthorize({ - scope, - resourceMetadataUrl, - errorDescription, - statusText: response.statusText, - text - }, stepUpRetries) !== "AUTHORIZED") throw new UnauthorizedError(); - return this._startOrAuthSse(options, isAuthRetry, stepUpRetries + 1); - } - } - await response.text?.().catch(() => { - }); - if (response.status === 405) { - options.onRequestStreamEnd?.(); - return; - } - throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToOpenStream, `Failed to open SSE stream: ${response.statusText}`, { - status: response.status, - statusText: response.statusText - }); - } - this._handleSseStream(response.body, options, true); - } catch (error2) { - if (!isIntentionalAbort()) this.onerror?.(error2); - throw error2; - } - } - /** - * Calculates the next reconnection delay using a backoff algorithm - * - * @param attempt Current reconnection attempt count for the specific stream - * @returns Time to wait in milliseconds before next reconnection attempt - */ - _getNextReconnectionDelay(attempt) { - if (this._serverRetryMs !== void 0) return this._serverRetryMs; - const initialDelay = this._reconnectionOptions.initialReconnectionDelay; - const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; - const maxDelay = this._reconnectionOptions.maxReconnectionDelay; - return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); - } - /** - * Schedule a reconnection attempt using server-provided retry interval or backoff - * - * @param lastEventId The ID of the last received event for resumability - * @param attemptCount Current reconnection attempt count for this specific stream - */ - _scheduleReconnection(options, attemptCount = 0) { - const maxRetries = this._reconnectionOptions.maxRetries; - if (attemptCount >= maxRetries) { - this.onerror?.(/* @__PURE__ */ new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); - options.onRequestStreamEnd?.(); - return; - } - const delay = this._getNextReconnectionDelay(attemptCount); - const reconnect = () => { - this._cancelReconnection = void 0; - if (this._abortController?.signal.aborted || options.requestSignal?.aborted) return; - this._startOrAuthSse(options).catch((error2) => { - if (this._abortController?.signal.aborted || options.requestSignal?.aborted) return; - this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect SSE stream: ${error2 instanceof Error ? error2.message : String(error2)}`)); - try { - this._scheduleReconnection(options, attemptCount + 1); - } catch (scheduleError) { - this.onerror?.(scheduleError instanceof Error ? scheduleError : new Error(String(scheduleError))); - } - }); - }; - if (this._reconnectionScheduler) { - const cancel = this._reconnectionScheduler(reconnect, delay, attemptCount); - this._cancelReconnection = typeof cancel === "function" ? cancel : void 0; - } else { - const handle = setTimeout(reconnect, delay); - this._cancelReconnection = () => clearTimeout(handle); - } - } - _handleSseStream(stream, options, isReconnectable) { - if (!stream) { - options.onRequestStreamEnd?.(); - return; - } - const { onresumptiontoken, replayMessageId, requestSignal, onRequestStreamEnd } = options; - const isIntentionalAbort = () => this._abortController?.signal.aborted === true || requestSignal?.aborted === true; - let lastEventId; - let hasPrimingEvent = false; - let receivedResponse = false; - const processStream = async () => { - try { - const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ onRetry: (retryMs) => { - this._serverRetryMs = retryMs; - } })).getReader(); - while (true) { - const { value: event, done } = await reader.read(); - if (done) break; - if (event.id) { - lastEventId = event.id; - hasPrimingEvent = true; - onresumptiontoken?.(event.id); - } - if (!event.data) continue; - if (!event.event || event.event === "message") try { - const message2 = JSONRPCMessageSchema.parse(JSON.parse(event.data)); - if (isJSONRPCResultResponse(message2) || isJSONRPCErrorResponse(message2)) { - receivedResponse = true; - if (replayMessageId !== void 0) message2.id = replayMessageId; - } - this.onmessage?.(message2); - } catch (error2) { - this.onerror?.(error2); - } - } - if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !isIntentionalAbort()) this._scheduleReconnection({ - resumptionToken: lastEventId, - onresumptiontoken, - replayMessageId, - requestSignal, - onRequestStreamEnd - }, 0); - else if (!isIntentionalAbort()) onRequestStreamEnd?.(); - } catch (error2) { - if (isIntentionalAbort()) return; - this.onerror?.(/* @__PURE__ */ new Error(`SSE stream disconnected: ${error2}`)); - if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !isIntentionalAbort()) try { - this._scheduleReconnection({ - resumptionToken: lastEventId, - onresumptiontoken, - replayMessageId, - requestSignal, - onRequestStreamEnd - }, 0); - } catch (error$1) { - this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect: ${error$1 instanceof Error ? error$1.message : String(error$1)}`)); - onRequestStreamEnd?.(); - } - else onRequestStreamEnd?.(); - } - }; - processStream(); - } - async start() { - if (this._abortController) throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically."); - this._abortController = new AbortController(); - } - async finishAuth(codeOrParams, iss) { - if (!this._oauthProvider) throw new UnauthorizedError("finishAuth requires an OAuthClientProvider"); - const { authorizationCode, iss: issParam } = await resolveAuthorizationCallbackParams(codeOrParams, iss, this._oauthProvider, this._url, { - fetchFn: this._fetchWithInit, - resourceMetadataUrl: this._resourceMetadataUrl - }); - if (await auth(this._oauthProvider, { - serverUrl: this._url, - authorizationCode, - iss: issParam, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit, - skipIssuerMetadataValidation: this._skipIssuerMetadataValidation - }) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize"); - } - async close() { - try { - this._cancelReconnection?.(); - } finally { - this._cancelReconnection = void 0; - this._abortController?.abort(); - this.onclose?.(); - } - } - async send(message2, options) { - return this._send(message2, options, false); - } - async _send(message2, options, isAuthRetry, stepUpRetries = 0) { - try { - const { resumptionToken, onresumptiontoken } = options || {}; - if (resumptionToken) { - this._startOrAuthSse({ - resumptionToken, - replayMessageId: isJSONRPCRequest(message2) ? message2.id : void 0, - requestSignal: options?.requestSignal - }).catch((error2) => this.onerror?.(error2)); - return; - } - const headers = await this._commonHeaders(); - this._applyBodyDerivedHeaders(headers, message2); - const isHandshake = Array.isArray(message2) ? message2.some((m) => isInitializeRequest(m)) : isInitializeRequest(message2); - if (isHandshake) headers.delete("mcp-session-id"); - if (options?.headers !== void 0) for (const [name, value] of Object.entries(options.headers)) { - if (RESERVED_REQUEST_HEADER_NAMES.has(name.toLowerCase())) continue; - headers.set(name, value); - } - headers.set("content-type", "application/json"); - const types = [ - ...headers.get("accept")?.split(",").map((s3) => s3.trim().toLowerCase()) ?? [], - "application/json", - "text/event-stream" - ]; - headers.set("accept", [...new Set(types)].join(", ")); - const transportSignal = this._abortController?.signal; - const signal = options?.requestSignal !== void 0 && transportSignal !== void 0 ? anySignal(transportSignal, options.requestSignal) : options?.requestSignal ?? transportSignal; - const init = { - ...this._requestInit, - method: "POST", - headers, - body: JSON.stringify(message2), - signal - }; - const response = await (this._fetch ?? fetch)(this._url, init); - if (isHandshake && response.ok) this._sessionId = response.headers.get("mcp-session-id") || void 0; - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - if (response.headers.has("www-authenticate")) { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = computeScopeUnion(this._scope, scope); - } - if (this._authProvider.onUnauthorized && !isAuthRetry) { - await this._authProvider.onUnauthorized({ - response, - serverUrl: this._url, - fetchFn: this._fetchWithInit - }); - await response.text?.().catch(() => { - }); - return this._send(message2, options, true, stepUpRetries); - } - await response.text?.().catch(() => { - }); - if (isAuthRetry) throw new SdkHttpError(SdkErrorCode.ClientHttpAuthentication, "Server returned 401 after re-authentication", { - status: 401, - statusText: response.statusText - }); - throw new UnauthorizedError(); - } - const text = await response.text?.().catch(() => null); - if (response.status === 403) { - const { resourceMetadataUrl, scope, error: error2, errorDescription } = extractWWWAuthenticateParams(response); - if (error2 === "insufficient_scope") { - if (await this._stepUpAuthorize({ - scope, - resourceMetadataUrl, - errorDescription, - statusText: response.statusText, - text - }, stepUpRetries) !== "AUTHORIZED") throw new UnauthorizedError(); - return this._send(message2, options, isAuthRetry, stepUpRetries + 1); - } - } - if (response.status === 400 && typeof text === "string" && this._isModernEnvelopedRequest(message2)) try { - const parsed = JSONRPCMessageSchema.parse(JSON.parse(text)); - const requests = (Array.isArray(message2) ? message2 : [message2]).filter((m) => isJSONRPCRequest(m)); - if (isJSONRPCErrorResponse(parsed) && requests.some((r) => r.id === parsed.id)) { - this.onmessage?.(parsed); - return; - } - } catch { - } - throw new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, `Error POSTing to endpoint: ${text}`, { - status: response.status, - statusText: response.statusText, - text - }); - } - if (response.status === 202) { - await response.text?.().catch(() => { - }); - if (isInitializedNotification(message2)) this._startOrAuthSse({ resumptionToken: void 0 }).catch((error2) => this.onerror?.(error2)); - return; - } - const hasRequests = (Array.isArray(message2) ? message2 : [message2]).some((msg) => "method" in msg && "id" in msg && msg.id !== void 0); - const contentType = response.headers.get("content-type"); - const responseMediaType = mediaTypeEssence(contentType); - if (hasRequests) if (responseMediaType === "text/event-stream") this._handleSseStream(response.body, { - onresumptiontoken, - requestSignal: options?.requestSignal, - onRequestStreamEnd: options?.onRequestStreamEnd - }, false); - else if (responseMediaType === "application/json") { - const data = await response.json(); - const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)]; - for (const msg of responseMessages) this.onmessage?.(msg); - } else { - await response.text?.().catch(() => { - }); - throw new SdkError(SdkErrorCode.ClientHttpUnexpectedContent, `Unexpected content type: ${contentType}`, { contentType }); - } - else await response.text?.().catch(() => { - }); - } catch (error2) { - if (options?.requestSignal?.aborted !== true) this.onerror?.(error2); - throw error2; - } - } - get sessionId() { - return this._sessionId; - } - /** - * Terminates the current session by sending a `DELETE` request to the server. - * - * Clients that no longer need a particular session - * (e.g., because the user is leaving the client application) SHOULD send an - * HTTP `DELETE` to the MCP endpoint with the `Mcp-Session-Id` header to explicitly - * terminate the session. - * - * The server MAY respond with HTTP `405 Method Not Allowed`, indicating that - * the server does not allow clients to terminate sessions. - */ - async terminateSession() { - if (!this._sessionId) return; - try { - const headers = await this._commonHeaders(); - const init = { - ...this._requestInit, - method: "DELETE", - headers, - signal: this._abortController?.signal - }; - const response = await (this._fetch ?? fetch)(this._url, init); - await response.text?.().catch(() => { - }); - if (!response.ok && response.status !== 405) throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToTerminateSession, `Failed to terminate session: ${response.statusText}`, { - status: response.status, - statusText: response.statusText - }); - this._sessionId = void 0; - } catch (error2) { - this.onerror?.(error2); - throw error2; - } - } - setProtocolVersion(version2) { - this._protocolVersion = version2; - } - get protocolVersion() { - return this._protocolVersion; - } - /** - * Resume an SSE stream from a previous event ID. - * Opens a `GET` SSE connection with `Last-Event-ID` header to replay missed events. - * - * @param lastEventId The event ID to resume from - * @param options Optional callback to receive new resumption tokens - */ - async resumeStream(lastEventId, options) { - await this._startOrAuthSse({ - resumptionToken: lastEventId, - onresumptiontoken: options?.onresumptiontoken - }); - } - }; - } -}); - -// ../freya/packages/core/dist/domain/model/Agent.js -function createAgent(config2, deploymentId) { - return { - id: config2.id, - config: config2, - deploymentId, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }; -} - -// ../freya/packages/core/dist/domain/model/Session.js -function createSession(id, agentId, userId, transportId) { - return { - id, - agentId, - userId, - transportId, - messages: [], - status: "active", - turnCount: 0, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - metadata: {} - }; -} -function addMessage(session, message2) { - return { - ...session, - messages: [...session.messages, message2], - turnCount: message2.role === "assistant" ? session.turnCount + 1 : session.turnCount, - updatedAt: /* @__PURE__ */ new Date() - }; -} - -// ../freya/packages/core/dist/domain/model/Message.js -function createUserMessage(id, content, transportOrigin) { - return { - id, - role: "user", - content, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin, - metadata: {} - }; -} -function createAssistantMessage(id, content, toolInvocations) { - return { - id, - role: "assistant", - content, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "agent", - toolInvocations, - metadata: {} - }; -} - -// ../freya/packages/core/dist/domain/events/DomainEvent.js -function createEvent(id, type, agentId, payload, sessionId) { - return { id, type, timestamp: /* @__PURE__ */ new Date(), agentId, sessionId, payload }; -} - -// ../freya/packages/core/dist/domain/services/ContextBuilderService.js -function buildContext(params) { - const { config: config2, ontology, memories, messages, tools, ontologyRenderer, transport } = params; - const parts = []; - parts.push(config2.systemPrompt); - if (transport) { - parts.push(` - -[Channel: ${transport}]`); - } - const ontologyText = ontologyRenderer.render(ontology); - if (ontologyText && ontology.entityTypes.length > 0) { - parts.push("\n---\n"); - parts.push(ontologyText); - } - if (memories.length > 0) { - parts.push("\n---\n# Relevant Context from Memory\n"); - for (const memory of memories) { - parts.push(`[${memory.entityType}] ${memory.content}`); - } - } - const systemPrompt = parts.join("\n"); - const systemTokens = Math.ceil(systemPrompt.length / 4); - const messageTokens = messages.reduce((sum, m) => sum + Math.ceil(m.content.length / 4), 0); - const toolTokens = tools.reduce((sum, t) => sum + Math.ceil(JSON.stringify(t.inputSchema).length / 4), 0); - return { - systemPrompt, - messages, - tools, - tokenEstimate: systemTokens + messageTokens + toolTokens - }; -} - -// ../freya/packages/core/dist/domain/services/ModelPricingService.js -var MODEL_PRICING_PER_1M_TOKENS = { - "claude-sonnet-4-6": [3, 15], - "claude-opus-4-6": [15, 75], - "claude-haiku-4-5-20251001": [0.25, 1.25], - // Bedrock-prefixed deployment-surface ids. Real Bedrock model-id - // strings vary by AWS region and may carry different date suffixes — - // callers should normalize before calling, or unknown ids will return - // 0 (callers can detect via `isKnownPricedModel`). - "anthropic.claude-sonnet-4-6-20251022-v1:0": [3, 15], - "anthropic.claude-opus-4-6-20251022-v1:0": [15, 75], - "anthropic.claude-haiku-4-5-20251001-v1:0": [0.25, 1.25] -}; -var CACHE_WRITE_MULTIPLIER = 1.25; -var CACHE_READ_MULTIPLIER = 0.1; -function estimateCostUSD(modelId, usageOrInputTokens, outputTokens) { - const usage = typeof usageOrInputTokens === "number" ? { inputTokens: usageOrInputTokens, outputTokens: outputTokens ?? 0 } : usageOrInputTokens; - const rates = MODEL_PRICING_PER_1M_TOKENS[modelId]; - if (!rates) - return 0; - const [inputRate, outputRate] = rates; - const safe = (v) => Math.max(0, Number.isFinite(v) ? v : 0); - const safeInput = safe(usage.inputTokens); - const safeOutput = safe(usage.outputTokens); - const safeCacheRead = safe(usage.cacheReadTokens); - const safeCacheWrite = safe(usage.cacheWriteTokens); - const totalUsdPer1M = safeInput * inputRate + safeOutput * outputRate + safeCacheRead * inputRate * CACHE_READ_MULTIPLIER + safeCacheWrite * inputRate * CACHE_WRITE_MULTIPLIER; - return totalUsdPer1M / 1e6; -} - -// ../freya/packages/core/dist/domain/services/TurnBudgetService.js -var LEGACY_INPUT_RATE_PER_1K = 3e-3; -var LEGACY_OUTPUT_RATE_PER_1K = 0.015; -function createBudgetTracker(budget, optionsOrClock = {}) { - const options = "now" in optionsOrClock && typeof optionsOrClock.now === "function" ? { clock: optionsOrClock } : optionsOrClock; - const clock = options.clock ?? { now: () => Date.now() }; - const modelId = options.modelId; - let calls = 0; - let totalTokens = 0; - let totalInputTokens = 0; - let totalOutputTokens = 0; - let totalCacheReadTokens = 0; - let totalCacheWriteTokens = 0; - const startTime = clock.now(); - const sanitize = (v) => Math.max(0, Number.isFinite(v) ? v : 0); - return { - recordCall(usage) { - calls++; - const inputTokens = sanitize(usage.inputTokens); - const outputTokens = sanitize(usage.outputTokens); - const cacheReadTokens = sanitize(usage.cacheReadTokens); - const cacheWriteTokens = sanitize(usage.cacheWriteTokens); - totalInputTokens += inputTokens; - totalOutputTokens += outputTokens; - totalCacheReadTokens += cacheReadTokens; - totalCacheWriteTokens += cacheWriteTokens; - totalTokens += inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens; - }, - isExhausted() { - return this.getStatus().exhausted; - }, - getStatus() { - const elapsedMs = clock.now() - startTime; - const estimatedCostUsd = modelId !== void 0 ? estimateCostUSD(modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) : totalInputTokens * LEGACY_INPUT_RATE_PER_1K / 1e3 + totalOutputTokens * LEGACY_OUTPUT_RATE_PER_1K / 1e3; - let exhausted = false; - let exhaustedReason; - if (budget.maxCalls !== void 0 && calls >= budget.maxCalls) { - exhausted = true; - exhaustedReason = `LLM call limit reached (${calls}/${budget.maxCalls})`; - } else if (budget.maxTokens !== void 0 && totalTokens >= budget.maxTokens) { - exhausted = true; - exhaustedReason = `Token limit reached (${totalTokens}/${budget.maxTokens})`; - } else if (budget.maxTimeMs !== void 0 && elapsedMs >= budget.maxTimeMs) { - exhausted = true; - exhaustedReason = `Time limit reached (${elapsedMs}ms/${budget.maxTimeMs}ms)`; - } else if (budget.maxCostUsd !== void 0 && estimatedCostUsd >= budget.maxCostUsd) { - exhausted = true; - exhaustedReason = `Cost limit reached ($${estimatedCostUsd.toFixed(4)}/$${budget.maxCostUsd})`; - } - return { - calls, - tokens: totalTokens, - timeMs: elapsedMs, - estimatedCostUsd, - exhausted, - ...exhaustedReason ? { exhaustedReason } : {} - }; - } - }; -} -function budgetFromMaxTurns(maxTurns) { - return { maxCalls: maxTurns }; -} - -// ../freya/packages/core/dist/domain/services/HooksService.js -var DEFAULT_PRIORITY = 100; -var InMemoryHookRegistry = class { - byPhase = /* @__PURE__ */ new Map(); - register(hook) { - const list = this.byPhase.get(hook.phase) ?? []; - if (list.some((h) => h.name === hook.name)) { - throw new Error(`Hook with name "${hook.name}" is already registered for phase "${hook.phase}"`); - } - list.push(hook); - this.byPhase.set(hook.phase, list); - } - unregister(name) { - for (const [phase, list] of this.byPhase) { - const filtered = list.filter((h) => h.name !== name); - if (filtered.length !== list.length) { - this.byPhase.set(phase, filtered); - } - } - } - hooksFor(phase) { - const list = this.byPhase.get(phase) ?? []; - const sorted = [...list].sort((a, b) => (a.priority ?? DEFAULT_PRIORITY) - (b.priority ?? DEFAULT_PRIORITY)); - return sorted; - } -}; -var HookExecutionError = class extends Error { - hookName; - phase; - cause; - constructor(hookName, phase, cause) { - const message2 = cause instanceof Error ? cause.message : String(cause); - super(`Hook "${hookName}" failed in phase "${phase}": ${message2}`); - this.hookName = hookName; - this.phase = phase; - this.cause = cause; - this.name = "HookExecutionError"; - } -}; -function makeFireHook(deps) { - const annotate = deps.onAnnotation ?? (() => { - }); - return async function fire(phase, initialPayload) { - const hooks = deps.registry.hooksFor(phase); - let payload = initialPayload; - for (const hook of hooks) { - const ctx = { - phase, - agent: deps.agent, - sessionId: deps.sessionId, - turnId: deps.turnId, - userContext: deps.userContext, - payload, - emit: deps.onEvent, - annotate - }; - let outcome; - try { - outcome = await hook.run(ctx); - } catch (err) { - throw new HookExecutionError(hook.name, phase, err); - } - if (outcome.kind === "short_circuit") { - deps.onEvent(createEvent(crypto.randomUUID(), "turn.short_circuited", deps.agent.id, { hookName: hook.name, phase, reason: outcome.reason }, deps.sessionId)); - return { - payload, - shortCircuited: true, - correctionRequested: false, - reason: outcome.reason, - finalResponse: outcome.finalResponse, - hookName: hook.name - }; - } - if (outcome.kind === "request_correction") { - if (phase !== "pre_capture") { - throw new HookExecutionError(hook.name, phase, new Error(`request_correction outcome is only valid from "pre_capture", got "${phase}"`)); - } - return { - payload, - shortCircuited: false, - correctionRequested: true, - correctionPrompt: outcome.correctionPrompt, - hookName: hook.name - }; - } - if (outcome.payload) { - payload = { ...payload, ...outcome.payload }; - } - } - return { - payload, - shortCircuited: false, - correctionRequested: false - }; - }; -} - -// ../freya/packages/core/dist/domain/services/OntologyValidationService.js -function parseResponseForClaims(content, ontology) { - if (ontology.entityTypes.length === 0) - return []; - const claims = []; - for (const entityType of ontology.entityTypes) { - const entityName = entityType.name; - const pattern = new RegExp(`\\b${escapeRegex(entityName)}\\b`, "gi"); - const matches2 = [...content.matchAll(pattern)]; - if (matches2.length === 0) - continue; - for (const match of matches2) { - const matchIndex = match.index; - const windowStart = Math.max(0, matchIndex - 20); - const windowEnd = Math.min(content.length, matchIndex + entityName.length + 200); - const window = content.slice(windowStart, windowEnd); - const properties = extractProperties(window, entityType); - claims.push({ - text: window.trim(), - entityType: entityName, - properties: Object.keys(properties).length > 0 ? properties : void 0 - }); - } - } - return claims; -} -function extractProperties(text, entityType) { - const properties = {}; - for (const prop of entityType.properties) { - const patterns = [ - new RegExp(`\\b${escapeRegex(prop.name)}\\s+(?:is|:|=)\\s+(\\S+)`, "i"), - new RegExp(`\\b${escapeRegex(prop.name)}\\s+(\\S+)`, "i") - ]; - for (const pattern of patterns) { - const match = text.match(pattern); - if (match) { - const value = match[1].replace(/[.,;!?)]+$/, ""); - if (value) { - properties[prop.name] = value; - break; - } - } - } - } - return properties; -} -function validateClaims(claims, ontology) { - const result = { - valid: [], - fixable: [], - friction: [] - }; - for (const claim of claims) { - validateSingleClaim(claim, ontology, result); - } - return result; -} -function validateSingleClaim(claim, ontology, result) { - const entityResolution = resolveEntityType(claim.entityType, ontology); - if (entityResolution.status === "unknown") { - result.friction.push({ - claim, - frictionType: "unknown_entity", - context: `Entity type "${claim.entityType}" is not defined in the ontology. Known types: ${ontology.entityTypes.map((e) => e.name).join(", ")}` - }); - return; - } - if (entityResolution.status === "fixable") { - result.fixable.push({ - claim, - suggestion: `Use "${entityResolution.resolved.name}" instead of "${claim.entityType}"` - }); - return; - } - const resolvedEntity = entityResolution.resolved; - if (!claim.properties || Object.keys(claim.properties).length === 0) { - result.valid.push(claim); - return; - } - let hasIssue = false; - for (const [propName, propValue] of Object.entries(claim.properties)) { - const propResolution = resolveProperty(propName, propValue, resolvedEntity); - if (propResolution.status === "fixable") { - result.fixable.push({ - claim, - suggestion: propResolution.suggestion - }); - hasIssue = true; - break; - } - if (propResolution.status === "unknown_property") { - result.friction.push({ - claim, - frictionType: "unknown_property", - context: `Property "${propName}" does not exist on entity type "${resolvedEntity.name}". Known properties: ${resolvedEntity.properties.map((p) => p.name).join(", ")}`, - propertyName: propName, - availableProperties: resolvedEntity.properties.map((p) => p.name) - }); - hasIssue = true; - continue; - } - if (propResolution.status === "invalid_value") { - const matchedProp = resolvedEntity.properties.find((p) => p.name === propName) ?? resolvedEntity.properties.find((p) => p.name.toLowerCase() === propName.toLowerCase()); - result.friction.push({ - claim, - frictionType: "invalid_value", - context: propResolution.context, - propertyName: propName, - allowedValues: matchedProp?.enumValues ?? [] - }); - hasIssue = true; - continue; - } - } - if (!hasIssue) { - result.valid.push(claim); - } -} -function resolveEntityType(claimedType, ontology) { - if (!claimedType) - return { status: "exact" }; - const exact = ontology.entityTypes.find((e) => e.name === claimedType); - if (exact) - return { status: "exact", resolved: exact }; - const caseMatch = ontology.entityTypes.find((e) => e.name.toLowerCase() === claimedType.toLowerCase()); - if (caseMatch) - return { status: "exact", resolved: caseMatch }; - for (const entity of ontology.entityTypes) { - const claimedLower = claimedType.toLowerCase(); - const entityLower = entity.name.toLowerCase(); - if (claimedLower.includes(entityLower) || entityLower.includes(claimedLower)) { - return { status: "fixable", resolved: entity }; - } - } - for (const entity of ontology.entityTypes) { - if (editDistance(claimedType.toLowerCase(), entity.name.toLowerCase()) <= 2) { - return { status: "fixable", resolved: entity }; - } - } - return { status: "unknown" }; -} -function resolveProperty(propName, propValue, entityType) { - const exact = entityType.properties.find((p) => p.name === propName); - if (exact) { - return validatePropertyValue(exact, propValue, entityType); - } - const caseMatch = entityType.properties.find((p) => p.name.toLowerCase() === propName.toLowerCase()); - if (caseMatch) { - return validatePropertyValue(caseMatch, propValue, entityType); - } - for (const prop of entityType.properties) { - if (editDistance(propName.toLowerCase(), prop.name.toLowerCase()) <= 2) { - return { - status: "fixable", - suggestion: `Use property "${prop.name}" instead of "${propName}" on entity type "${entityType.name}"` - }; - } - } - return { status: "unknown_property" }; -} -function validatePropertyValue(prop, value, entityType) { - if (prop.type === "enum" && prop.enumValues) { - const lowerValue = value.toLowerCase(); - const match = prop.enumValues.find((v) => v.toLowerCase() === lowerValue); - if (!match) { - return { - status: "invalid_value", - context: `Property "${prop.name}" on "${entityType.name}" only allows: ${prop.enumValues.join(", ")}. Got: "${value}"` - }; - } - } - return { status: "valid" }; -} -function editDistance(a, b) { - if (a.length === 0) - return b.length; - if (b.length === 0) - return a.length; - const matrix = []; - for (let i = 0; i <= b.length; i++) { - matrix[i] = [i]; - } - for (let j = 0; j <= a.length; j++) { - matrix[0][j] = j; - } - for (let i = 1; i <= b.length; i++) { - for (let j = 1; j <= a.length; j++) { - if (b[i - 1] === a[j - 1]) { - matrix[i][j] = matrix[i - 1][j - 1]; - } else { - matrix[i][j] = Math.min( - matrix[i - 1][j - 1] + 1, - // substitution - matrix[i][j - 1] + 1, - // insertion - matrix[i - 1][j] + 1 - ); - } - } - } - return matrix[b.length][a.length]; -} -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - -// ../freya/packages/core/dist/domain/services/MemoryCaptureService.js -var DEFAULT_CAPTURE_CONFIDENCE_THRESHOLD = 0.7; -var HEDGE_PATTERN = new RegExp([ - "\\bmight\\b", - "\\bmaybe\\b", - "\\bperhaps\\b", - "\\bpossibly\\b", - "\\bI\\s+think\\b", - "\\bI\\s+believe\\b", - "\\bnot\\s+sure\\b", - "\\bnot\\s+certain\\b", - "\\bprobably\\b", - "\\bunlikely\\b", - "\\bsomewhat\\b", - "\\bsort\\s+of\\b", - "\\bkind\\s+of\\b", - "\\bappears\\s+to\\b", - "\\bseems\\s+to\\b", - "\\bcould\\s+be\\b" -].join("|"), "gi"); -var HEDGE_PENALTY_PER_MATCH = 0.15; -var MAX_HEDGE_PENALTY_MATCHES = 3; -var CONFIDENCE_FLOOR = 0.1; -function countHedgeMarkers(text) { - if (!text) - return 0; - const matches2 = text.match(HEDGE_PATTERN); - if (!matches2) - return 0; - return Math.min(matches2.length, MAX_HEDGE_PENALTY_MATCHES); -} -function scoreClaimConfidence(claim) { - const propCount = claim.properties ? Object.keys(claim.properties).length : 0; - const propertyScore = 0.5 + 0.1 * Math.min(propCount, 5); - const hedgeCount = countHedgeMarkers(claim.text); - const hedgePenalty = HEDGE_PENALTY_PER_MATCH * hedgeCount; - const raw = propertyScore - hedgePenalty; - return Math.min(1, Math.max(CONFIDENCE_FLOOR, raw)); -} -function coerceStructured(claim, entityType) { - const structured = {}; - if (!claim.properties) - return structured; - for (const [k, v] of Object.entries(claim.properties)) { - const prop = entityType.properties.find((p) => p.name === k || p.name.toLowerCase() === k.toLowerCase()); - if (!prop) { - structured[k] = v; - continue; - } - if (prop.type === "number") { - const n = Number(v); - structured[prop.name] = Number.isFinite(n) ? n : v; - } else if (prop.type === "boolean") { - const lv = v.toLowerCase(); - if (lv === "true") - structured[prop.name] = true; - else if (lv === "false") - structured[prop.name] = false; - else - structured[prop.name] = v; - } else { - structured[prop.name] = v; - } - } - return structured; -} -function extractMemoriesFromResponse(params) { - const { response, ontology, agent, sessionId, turnId } = params; - if (ontology.entityTypes.length === 0 || response.length === 0) { - return { toCapture: [], dropped: [] }; - } - const threshold = agent.config.captureConfidenceThreshold ?? DEFAULT_CAPTURE_CONFIDENCE_THRESHOLD; - const claims = parseResponseForClaims(response, ontology); - if (claims.length === 0) { - return { toCapture: [], dropped: [] }; - } - const { valid } = validateClaims(claims, ontology); - const toCapture = []; - const dropped = []; - const dedupKeys = /* @__PURE__ */ new Set(); - for (const claim of valid) { - if (!claim.entityType) - continue; - const entity = ontology.entityTypes.find((e) => e.name === claim.entityType); - if (!entity) - continue; - const confidence = scoreClaimConfidence(claim); - const structured = coerceStructured(claim, entity); - const content = claim.text; - const lookup = pickPredecessorLookup(structured, entity); - const dedupKey = lookup ? `${entity.name}::${lookup.key}::${stringifyLookupValue(lookup.value)}` : `${entity.name}::__no_key__::${content}`; - if (dedupKeys.has(dedupKey)) - continue; - dedupKeys.add(dedupKey); - if (confidence < threshold) { - dropped.push({ - entityType: entity.name, - content, - confidence, - threshold, - reason: "low_confidence", - ...Object.keys(structured).length > 0 ? { structured } : {} - }); - continue; - } - const missingRequired = entity.properties.find((p) => p.required && !(p.name in structured)); - if (missingRequired) { - dropped.push({ - entityType: entity.name, - content, - confidence, - threshold, - reason: "missing_required_property", - ...Object.keys(structured).length > 0 ? { structured } : {} - }); - continue; - } - const source = { - type: "auto_capture", - sessionId, - turnId, - // Auditing handle: include the agent's id so "who captured this" - // is recoverable from `source.author` without joining via agentId. - author: `memory-capture-service:${agent.id}` - }; - toCapture.push({ - id: crypto.randomUUID(), - agentId: agent.id, - scope: "namespace", - scopeId: agent.config.memoryNamespaces[0] ?? "default", - entityType: entity.name, - content, - structured, - confidence, - source, - status: "active", - portable: false, - createdAt: /* @__PURE__ */ new Date(), - version: 1 - }); - } - return { toCapture, dropped }; -} -function pickPredecessorLookup(structured, entityType) { - const candidates = predecessorLookupCandidates(structured, entityType); - return candidates[0] ?? null; -} -function predecessorLookupCandidates(structured, entityType) { - const out = []; - if ("id" in structured && isPrimitive(structured.id)) { - out.push({ key: "id", value: structured.id }); - } - const keys = Object.keys(structured).sort(); - for (const k of keys) { - if (k === "id") - continue; - const v = structured[k]; - if (!isPrimitive(v)) - continue; - if (entityType) { - const prop = entityType.properties.find((p) => p.name === k || p.name.toLowerCase() === k.toLowerCase()); - if (prop && prop.type === "enum") - continue; - } - out.push({ key: k, value: v }); - } - return out; -} -function isPrimitive(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean"; -} -function stringifyLookupValue(v) { - if (typeof v === "string") - return v.toLowerCase(); - return String(v); -} -async function findPredecessor(candidate, memory, ontology) { - const entityType = ontology?.entityTypes.find((e) => e.name === candidate.entityType); - const lookups = predecessorLookupCandidates(candidate.structured, entityType); - if (lookups.length === 0) - return { kind: "none" }; - let entries; - try { - entries = await memory.getByEntityType(candidate.agentId, candidate.entityType); - } catch { - return { kind: "none" }; - } - const sameScope = entries.filter((e) => e.scope === candidate.scope && e.scopeId === candidate.scopeId); - const candidateId = candidate.structured.id; - const candidateHasPrimitiveId = isPrimitive(candidateId); - for (const lookup of lookups) { - const target = stringifyLookupValue(lookup.value); - const matches2 = sameScope.filter((e) => { - if (e.id === candidate.id) - return false; - if (e.status !== "active") - return false; - const v = e.structured[lookup.key]; - if (v === void 0 || !isPrimitive(v) || stringifyLookupValue(v) !== target) - return false; - if (lookup.key !== "id" && candidateHasPrimitiveId) { - const eId = e.structured.id; - if (isPrimitive(eId) && stringifyLookupValue(eId) !== stringifyLookupValue(candidateId)) { - return false; - } - } - return true; - }); - if (matches2.length === 0) - continue; - const sorted = [...matches2].sort((a, b) => { - const dt = b.createdAt.getTime() - a.createdAt.getTime(); - if (dt !== 0) - return dt; - const dv = (b.version ?? 0) - (a.version ?? 0); - if (dv !== 0) - return dv; - return a.id.localeCompare(b.id); - }); - if (sorted.length >= 2) { - return { kind: "ambiguous", entries: sorted }; - } - return { kind: "one", entry: sorted[0] }; - } - return { kind: "none" }; -} -async function captureFromResponse(params) { - const { memory, ...rest } = params; - const { toCapture, dropped } = extractMemoriesFromResponse(rest); - const captured = []; - const errors = []; - const frictionEvents = []; - const availableEntityTypes = rest.ontology.entityTypes.map((e) => e.name); - for (const candidate of toCapture) { - try { - const predecessor = await findPredecessor(candidate, memory, rest.ontology); - await memory.store(candidate); - captured.push(candidate); - switch (predecessor.kind) { - case "none": - break; - case "one": { - try { - await memory.supersede(predecessor.entry.id, candidate.id); - } catch (err) { - errors.push(`supersede(${predecessor.entry.id} \u2192 ${candidate.id}) failed: ${err instanceof Error ? err.message : String(err)}`); - } - break; - } - case "ambiguous": { - const conflictIds = predecessor.entries.map((e) => e.id).sort(); - const eventId = `conflicting_facts:${rest.sessionId}:${rest.agent.id}:${candidate.entityType}:${conflictIds.join(",")}`; - let claimText; - try { - claimText = JSON.stringify({ - entityType: candidate.entityType, - candidate: candidate.structured, - conflictingEntryIds: conflictIds - }); - } catch { - claimText = ""; - } - frictionEvents.push(createEvent(eventId, "ontology.friction", rest.agent.id, { - claim: claimText, - attemptedEntityType: candidate.entityType, - availableEntityTypes, - frictionType: "conflicting_facts", - count: predecessor.entries.length, - // First-class field — consumers shouldn't have to parse - // `claim` (JSON-encoded) to get the conflict set. This - // is what a human reviewer needs to act: WHICH entries - // conflict, not just how many. - conflictingEntryIds: conflictIds - }, rest.sessionId)); - break; - } - } - } catch (err) { - errors.push(`store(${candidate.id}) failed: ${err instanceof Error ? err.message : String(err)}`); - } - } - return { captured, dropped, errors, frictionEvents }; -} - -// ../freya/packages/core/dist/domain/services/AgentSessionService.js -var MAX_CORRECTION_RETRIES_PER_TURN = 2; -async function executeTurn(agent, sessionId, userMessage, deps, budget) { - const events = []; - const allToolResults = []; - let totalInputTokens = 0; - let totalOutputTokens = 0; - let totalCacheReadTokens = 0; - let totalCacheWriteTokens = 0; - let llmCalls = 0; - const tracing = deps.trace === true; - const trace = []; - const turnId = crypto.randomUUID(); - const annotationsBuf = []; - let currentPhase = "init"; - const rawFire = makeFireHook({ - registry: deps.hooks ?? new InMemoryHookRegistry(), - agent, - sessionId, - turnId, - onEvent: (e) => events.push(e), - onAnnotation: (key, value) => annotationsBuf.push({ phase: currentPhase, key, value }) - }); - const fire = async (phase, payload) => { - currentPhase = phase; - try { - return await rawFire(phase, payload); - } catch (err) { - if (!(err instanceof HookExecutionError)) - throw err; - const message2 = err.message; - annotationsBuf.push({ - phase, - key: "blocking.hook_exception", - value: message2 - }); - events.push({ - id: crypto.randomUUID(), - type: "turn.annotated", - agentId: agent.id, - sessionId, - timestamp: /* @__PURE__ */ new Date(), - payload: { - key: "blocking.hook_exception", - phase, - error: message2 - } - }); - return { - payload, - shortCircuited: false, - correctionRequested: false - }; - } - }; - let session = await deps.sessions.get(sessionId); - if (!session) { - session = createSession(sessionId, agent.id, userMessage.metadata.userId ?? "unknown", userMessage.transportOrigin); - } - session = addMessage(session, userMessage); - events.push(createEvent(crypto.randomUUID(), "message.received", agent.id, { messageId: userMessage.id }, sessionId)); - let ontology = await deps.ontologyService.compose(agent.id); - const recallResult = await deps.memory.recall({ - agentId: agent.id, - query: userMessage.content, - limit: 20 - }); - let memories = recallResult.entries; - const effectiveBudget = budget ?? budgetFromMaxTurns(agent.config.maxTurns || 10); - const tracker = createBudgetTracker(effectiveBudget, { modelId: agent.config.modelId }); - const hardCap = Math.max(effectiveBudget.maxCalls != null ? effectiveBudget.maxCalls * 2 : 100, 1); - let totalLLMCalls = 0; - let finalResponse = null; - let budgetExhaustedDuringLoop = false; - let earlyExit = null; - try { - const preTurn = await fire("pre_turn", { userMessage, ontology, memories, session }); - if (preTurn.shortCircuited) { - earlyExit = { finalResponse: preTurn.finalResponse ?? null, reason: preTurn.reason }; - } else { - ontology = preTurn.payload.ontology; - memories = preTurn.payload.memories; - } - const toolDefs = []; - if (!earlyExit) { - for (const scope of agent.config.toolScopes) { - const discovered = await deps.tools.discoverTools(scope); - toolDefs.push(...discovered); - } - } - const MAX_CONTEXT_MESSAGES = 20; - const windowedMessages = session.messages.length > MAX_CONTEXT_MESSAGES ? session.messages.slice(-MAX_CONTEXT_MESSAGES) : session.messages; - let context = !earlyExit ? buildContext({ - config: agent.config, - ontology, - memories, - messages: windowedMessages, - tools: toolDefs, - ontologyRenderer: deps.ontologyRenderer, - transport: userMessage.transportOrigin - }) : { systemPrompt: "", messages: [], tools: [], tokenEstimate: 0 }; - if (!earlyExit) { - const preContext = await fire("pre_context", { - context, - recall: recallResult, - recallQuery: userMessage.content, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - if (preContext.shortCircuited) { - earlyExit = { finalResponse: preContext.finalResponse ?? null, reason: preContext.reason }; - } else { - context = preContext.payload.context; - } - } - let turnMessages = [...windowedMessages]; - if (tracing) { - trace.push({ step: "start", timestamp: Date.now(), data: { sessionMessages: session.messages.length, windowedMessages: windowedMessages.length, hardCap, budget: effectiveBudget } }); - } - let correctionsUsed = 0; - correctionLoop: while (!earlyExit) { - finalResponse = null; - llmLoop: while (totalLLMCalls < hardCap) { - const preLlm = await fire("pre_llm", { - messages: turnMessages, - systemPrompt: context.systemPrompt, - tools: toolDefs, - callNumber: totalLLMCalls + 1 - }); - if (preLlm.shortCircuited) { - earlyExit = { finalResponse: preLlm.finalResponse ?? null, reason: preLlm.reason }; - break llmLoop; - } - if (tracing) { - trace.push({ step: "llm_call", timestamp: Date.now(), data: { turnMessages: preLlm.payload.messages.length, toolDefs: preLlm.payload.tools.length, callNumber: totalLLMCalls + 1 } }); - } - const llmResponse = await deps.llm.complete({ - model: agent.config.modelId, - systemPrompt: preLlm.payload.systemPrompt, - messages: preLlm.payload.messages, - tools: preLlm.payload.tools - }); - totalLLMCalls++; - llmCalls++; - totalInputTokens += llmResponse.usage.inputTokens; - totalOutputTokens += llmResponse.usage.outputTokens; - totalCacheReadTokens += llmResponse.usage.cacheReadTokens ?? 0; - totalCacheWriteTokens += llmResponse.usage.cacheWriteTokens ?? 0; - tracker.recordCall(llmResponse.usage); - if (tracing) { - trace.push({ step: "llm_response", timestamp: Date.now(), data: { contentLength: llmResponse.content.length, toolCalls: llmResponse.toolCalls.length, stopReason: llmResponse.stopReason, usage: llmResponse.usage } }); - } - const postLlm = await fire("post_llm", { response: llmResponse, callNumber: totalLLMCalls }); - const effectiveResponse = postLlm.payload.response; - if (postLlm.shortCircuited) { - earlyExit = { finalResponse: postLlm.finalResponse ?? null, reason: postLlm.reason }; - finalResponse = effectiveResponse; - break llmLoop; - } - if (effectiveResponse.stopReason === "tool_use" && effectiveResponse.toolCalls.length > 0) { - let toolLoopShortCircuit = false; - for (const call of effectiveResponse.toolCalls) { - const preTool = await fire("pre_tool", { call }); - if (preTool.shortCircuited) { - earlyExit = { finalResponse: preTool.finalResponse ?? null, reason: preTool.reason }; - finalResponse = effectiveResponse; - toolLoopShortCircuit = true; - break; - } - const effectiveCall = preTool.payload.call; - events.push(createEvent(crypto.randomUUID(), "tool.invoked", agent.id, { tool: effectiveCall.toolName }, sessionId)); - const rawResult = await deps.tools.execute(effectiveCall); - const availableEntityTypes = ontology.entityTypes.map((e) => e.name); - const postTool = await fire("post_tool", { - call: effectiveCall, - result: rawResult, - availableEntityTypes - }); - const result2 = postTool.payload.result; - allToolResults.push(result2); - events.push(createEvent(crypto.randomUUID(), "tool.completed", agent.id, { tool: effectiveCall.toolName, status: result2.status }, sessionId)); - const toolUseId = effectiveCall.id; - turnMessages = [ - ...turnMessages, - { - id: crypto.randomUUID(), - role: "assistant", - content: effectiveResponse.content, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "agent", - toolInvocations: [{ toolName: effectiveCall.toolName, input: effectiveCall.input, output: result2.output, durationMs: result2.durationMs, status: result2.status }], - metadata: { toolUseId } - }, - { - id: crypto.randomUUID(), - role: "tool", - content: typeof result2.output === "string" ? result2.output : JSON.stringify(result2.output), - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "tool", - metadata: { toolName: effectiveCall.toolName, callId: toolUseId } - } - ]; - if (postTool.shortCircuited) { - earlyExit = { finalResponse: postTool.finalResponse ?? null, reason: postTool.reason }; - finalResponse = effectiveResponse; - toolLoopShortCircuit = true; - break; - } - } - if (toolLoopShortCircuit) - break llmLoop; - if (tracker.isExhausted()) { - if (tracing) { - trace.push({ step: "budget_check", timestamp: Date.now(), data: { exhausted: true, status: tracker.getStatus() } }); - } - finalResponse = effectiveResponse; - budgetExhaustedDuringLoop = true; - break llmLoop; - } - if (tracing) { - trace.push({ step: "budget_check", timestamp: Date.now(), data: { exhausted: false, status: tracker.getStatus() } }); - } - } else { - finalResponse = effectiveResponse; - break llmLoop; - } - } - if (earlyExit) - break correctionLoop; - const candidateContent = finalResponse?.content ?? (tracker.getStatus().exhausted || budgetExhaustedDuringLoop ? "[Agent budget exhausted]" : "[Agent reached max turns without completing]"); - const candidateMessage = createAssistantMessage(crypto.randomUUID(), candidateContent, allToolResults.map((r) => ({ - toolName: r.toolName, - input: {}, - output: r.output, - durationMs: r.durationMs, - status: r.status - }))); - const preCapture = await fire("pre_capture", { - response: candidateMessage, - toolResults: allToolResults, - ontology - }); - if (preCapture.correctionRequested) { - if (correctionsUsed < MAX_CORRECTION_RETRIES_PER_TURN) { - correctionsUsed++; - turnMessages = [ - ...turnMessages, - candidateMessage, - createUserMessage(crypto.randomUUID(), preCapture.correctionPrompt ?? "Please correct your response.", "system") - ]; - continue correctionLoop; - } - events.push(createEvent(crypto.randomUUID(), "turn.correction_cap_exceeded", agent.id, { - hookName: preCapture.hookName, - correctionsUsed, - cap: MAX_CORRECTION_RETRIES_PER_TURN - }, sessionId)); - } - if (preCapture.shortCircuited) { - earlyExit = { finalResponse: preCapture.finalResponse ?? candidateMessage, reason: preCapture.reason }; - } - break correctionLoop; - } - const budgetStatus = tracker.getStatus(); - const budgetExhausted = budgetExhaustedDuringLoop || budgetStatus.exhausted; - const fallbackContent = budgetExhausted ? "[Agent budget exhausted]" : earlyExit ? `[Agent short-circuited${earlyExit.reason ? `: ${earlyExit.reason}` : ""}]` : "[Agent reached max turns without completing]"; - const builtContent = earlyExit ? fallbackContent : finalResponse?.content ?? fallbackContent; - const responseMessage = earlyExit?.finalResponse ?? createAssistantMessage(crypto.randomUUID(), builtContent, allToolResults.map((r) => ({ - toolName: r.toolName, - input: {}, - output: r.output, - durationMs: r.durationMs, - status: r.status - }))); - session = addMessage(session, responseMessage); - await deps.sessions.save(session); - events.push(createEvent(crypto.randomUUID(), "message.sent", agent.id, { messageId: responseMessage.id }, sessionId)); - let memoriesCaptured = []; - let droppedCandidates = []; - try { - const captureResult = await captureFromResponse({ - response: responseMessage.content, - ontology, - agent, - sessionId, - turnId, - memory: deps.memory - }); - memoriesCaptured = captureResult.captured; - droppedCandidates = captureResult.dropped; - for (const errMsg of captureResult.errors) { - annotationsBuf.push({ - phase: "post_capture", - key: "memory.capture_error", - value: errMsg - }); - } - for (const fe of captureResult.frictionEvents) { - events.push(fe); - } - } catch (err) { - annotationsBuf.push({ - phase: "post_capture", - key: "memory.capture_error", - value: err instanceof Error ? err.message : String(err) - }); - } - const availableEntityTypesAtCapture = ontology.entityTypes.map((e) => e.name); - let recentlyCaptured; - if (memoriesCaptured.length > 0) { - for (const entry of memoriesCaptured) { - try { - const chain = await deps.memory.getSupersedeChain(entry.id); - if (chain.length === 0) - continue; - const propertyNames = Object.keys(entry.structured).sort(); - const nonIdKeys = propertyNames.filter((p) => p !== "id"); - const propertyName = nonIdKeys[0] ?? propertyNames[0]; - if (!propertyName) - continue; - const coverage = chain.filter((p) => propertyName in p.structured).length; - if (coverage < Math.ceil(chain.length / 2)) - continue; - const priorValues = [...chain].reverse().map((prior) => prior.structured[propertyName]); - recentlyCaptured = { - chainAnchor: entry.id, - entityType: entry.entityType, - propertyName, - currentValue: entry.structured[propertyName], - priorValues - }; - break; - } catch { - continue; - } - } - } - const postCapture = await fire("post_capture", { - captured: memoriesCaptured, - availableEntityTypes: availableEntityTypesAtCapture, - droppedCandidates, - ...recentlyCaptured ? { recentlyCaptured } : {} - }); - if (postCapture.shortCircuited && !earlyExit) { - earlyExit = { finalResponse: postCapture.finalResponse ?? null, reason: postCapture.reason }; - } - const estimatedCostUSD = estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }); - if (tracing) { - trace.push({ step: "complete", timestamp: Date.now(), data: { budgetExhausted, responseLength: responseMessage.content.length, totalLLMCalls, hardCap } }); - } - const result = { - response: responseMessage, - session, - memoriesCaptured, - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - estimatedCostUSD - }, - budgetExhausted, - budgetStatus: { - calls: budgetStatus.calls, - tokens: budgetStatus.tokens, - timeMs: budgetStatus.timeMs, - ...budgetStatus.exhaustedReason ? { reason: budgetStatus.exhaustedReason } : {} - }, - ...tracing ? { trace } : {} - }; - await fire("post_turn", { - result, - availableEntityTypes: availableEntityTypesAtCapture - }); - return result; - } catch (err) { - const partialResult = { - response: createAssistantMessage(crypto.randomUUID(), `[Agent error: ${err instanceof Error ? err.message : String(err)}]`, []), - session, - memoriesCaptured: [], - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - // Even on the error path, surface real cost when tokens were - // consumed before the throw — billing observers/cost trackers - // running at post_turn should see the spend that already happened. - estimatedCostUSD: estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) - } - }; - try { - await fire("post_turn", { - result: partialResult, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - } catch { - } - throw err; - } -} - -// ../freya/packages/core/dist/domain/services/IdentifierRedactionService.js -var OPAQUE_ID_DEFAULT_MIN = 32; -var OPAQUE_ID_DEFAULT_PATTERN = new RegExp(`\\b[A-Za-z0-9]{${OPAQUE_ID_DEFAULT_MIN},}\\b`, "g"); - -// ../freya/packages/runtime/dist/streaming.js -async function* executeStreamingTurn(agent, sessionId, userMessage, deps, budget, signal) { - const events = []; - const allToolResults = []; - let totalInputTokens = 0; - let totalOutputTokens = 0; - let totalCacheReadTokens = 0; - let totalCacheWriteTokens = 0; - let llmCalls = 0; - const effectiveBudget = budget ?? budgetFromMaxTurns(agent.config.maxTurns || 10); - const tracker = createBudgetTracker(effectiveBudget, { modelId: agent.config.modelId }); - const hardCap = Math.max(effectiveBudget.maxCalls != null ? effectiveBudget.maxCalls * 2 : 100, 1); - let budgetExhaustedDuringLoop = false; - const turnId = crypto.randomUUID(); - const annotations = []; - let currentPhase = "init"; - const rawFire = makeFireHook({ - registry: deps.hooks ?? new InMemoryHookRegistry(), - agent, - sessionId, - turnId, - onEvent: (e) => events.push(e), - // Wire annotations through to a local buffer so callers / tests can see - // them; without this they were silently dropped (the default is a no-op). - onAnnotation: (key, value) => annotations.push({ phase: currentPhase, key, value }) - }); - const fire = async (phase, payload) => { - currentPhase = phase; - try { - return await rawFire(phase, payload); - } catch (err) { - if (!(err instanceof HookExecutionError)) - throw err; - const message2 = err.message; - annotations.push({ - phase, - key: "streaming.hook_exception", - value: message2 - }); - events.push(annotationEvent(agent.id, sessionId, "streaming.hook_exception", { - phase, - error: message2 - })); - return { - payload, - shortCircuited: false, - correctionRequested: false - }; - } - }; - const userId = userMessage.metadata?.userId ?? "unknown"; - let session = await deps.sessions.get(sessionId); - if (!session) { - session = createSession(sessionId, agent.id, userId, userMessage.transportOrigin); - } - session = addMessage(session, userMessage); - events.push(createEvent(crypto.randomUUID(), "message.received", agent.id, { messageId: userMessage.id }, sessionId)); - let ontology = await deps.ontologyService.compose(agent.id); - const recallResult = await deps.memory.recall({ - agentId: agent.id, - query: userMessage.content, - limit: 20 - }); - let memories = recallResult.entries; - let streamingStarted = false; - let earlyExitReason; - let earlyExitResponse = null; - let earlyShortCircuit = false; - try { - const preTurn = await fire("pre_turn", { - userMessage, - ontology, - memories, - session - }); - if (preTurn.shortCircuited) { - earlyExitReason = preTurn.reason; - earlyExitResponse = preTurn.finalResponse ?? null; - yield systemMessage("pre_turn", preTurn.reason, preTurn.finalResponse); - earlyShortCircuit = true; - } else { - ontology = preTurn.payload.ontology; - memories = preTurn.payload.memories; - } - const toolDefs = []; - if (!earlyShortCircuit) { - for (const scope of agent.config.toolScopes) { - const discovered = await deps.tools.discoverTools(scope); - toolDefs.push(...discovered); - } - } - const MAX_CONTEXT_MESSAGES = 20; - const windowedMessages = session.messages.length > MAX_CONTEXT_MESSAGES ? session.messages.slice(-MAX_CONTEXT_MESSAGES) : session.messages; - let context = !earlyShortCircuit ? buildContext({ - config: agent.config, - ontology, - memories, - messages: windowedMessages, - tools: toolDefs, - ontologyRenderer: deps.ontologyRenderer, - transport: userMessage.transportOrigin - }) : { systemPrompt: "", messages: [], tools: [], tokenEstimate: 0 }; - if (!earlyShortCircuit) { - const preContext = await fire("pre_context", { - context, - recall: recallResult, - recallQuery: userMessage.content, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - if (preContext.shortCircuited) { - earlyExitReason = preContext.reason; - earlyExitResponse = preContext.finalResponse ?? null; - yield systemMessage("pre_context", preContext.reason, preContext.finalResponse); - earlyShortCircuit = true; - } else { - context = preContext.payload.context; - } - } - let currentMessages = [...windowedMessages]; - let lastAssistantContent = ""; - while (!earlyShortCircuit && llmCalls < hardCap) { - const preLlm = await fire("pre_llm", { - messages: currentMessages, - systemPrompt: context.systemPrompt, - tools: toolDefs, - callNumber: llmCalls + 1 - }); - if (preLlm.shortCircuited) { - if (!streamingStarted) { - earlyExitReason = preLlm.reason; - earlyExitResponse = preLlm.finalResponse ?? null; - yield systemMessage("pre_llm", preLlm.reason, preLlm.finalResponse); - earlyShortCircuit = true; - break; - } - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "pre_llm", - reason: preLlm.reason - })); - break; - } - let fullContent = ""; - const toolCalls = []; - let chunkUsage = { - inputTokens: 0, - outputTokens: 0 - }; - for await (const chunk of deps.llm.stream({ - model: agent.config.modelId, - systemPrompt: preLlm.payload.systemPrompt, - messages: preLlm.payload.messages, - tools: preLlm.payload.tools, - signal - })) { - if (chunk.type === "text" && chunk.content) { - fullContent += chunk.content; - streamingStarted = true; - yield chunk.content; - } else if (chunk.type === "tool_call" && chunk.toolCall) { - toolCalls.push(chunk.toolCall); - } else if (chunk.type === "done") { - if (chunk.usage) { - chunkUsage = { - inputTokens: chunk.usage.inputTokens, - outputTokens: chunk.usage.outputTokens, - ...chunk.usage.cacheReadTokens !== void 0 && { cacheReadTokens: chunk.usage.cacheReadTokens }, - ...chunk.usage.cacheWriteTokens !== void 0 && { cacheWriteTokens: chunk.usage.cacheWriteTokens } - }; - } - break; - } - } - llmCalls++; - lastAssistantContent = fullContent; - const llmResponse = { - content: fullContent, - toolCalls, - usage: chunkUsage, - stopReason: toolCalls.length > 0 ? "tool_use" : "end_turn" - }; - tracker.recordCall(llmResponse.usage); - const postLlm = await fire("post_llm", { - response: llmResponse, - callNumber: llmCalls - }); - totalInputTokens += llmResponse.usage.inputTokens; - totalOutputTokens += llmResponse.usage.outputTokens; - totalCacheReadTokens += llmResponse.usage.cacheReadTokens ?? 0; - totalCacheWriteTokens += llmResponse.usage.cacheWriteTokens ?? 0; - const effectiveResponse = postLlm.payload.response; - if (postLlm.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "post_llm", - reason: postLlm.reason - })); - break; - } - if (effectiveResponse.toolCalls.length === 0) - break; - const availableEntityTypes = ontology.entityTypes.map((e) => e.name); - let toolLoopBreak = false; - for (const call of effectiveResponse.toolCalls) { - const preTool = await fire("pre_tool", { call }); - if (preTool.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "pre_tool", - reason: preTool.reason - })); - toolLoopBreak = true; - break; - } - const effectiveCall = preTool.payload.call; - events.push(createEvent(crypto.randomUUID(), "tool.invoked", agent.id, { tool: effectiveCall.toolName }, sessionId)); - const result2 = await deps.tools.execute(effectiveCall); - const postTool = await fire("post_tool", { - call: effectiveCall, - result: result2, - availableEntityTypes - }); - const effectiveResult = postTool.payload.result; - allToolResults.push(effectiveResult); - events.push(createEvent(crypto.randomUUID(), "tool.completed", agent.id, { tool: effectiveCall.toolName, status: effectiveResult.status }, sessionId)); - currentMessages = [ - ...currentMessages, - { - id: crypto.randomUUID(), - role: "assistant", - content: fullContent, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "agent", - toolInvocations: [ - { - toolName: effectiveCall.toolName, - input: effectiveCall.input, - output: effectiveResult.output, - durationMs: effectiveResult.durationMs, - status: effectiveResult.status - } - ], - // Thread the original tool-call id so the LLM adapter can emit a - // `tool_use` block whose id matches the `tool_result` below. Without - // this, the Anthropic adapter synthesises two *independent* ids - // (random vs Date.now()) and the provider rejects the continuation - // call with "tool_result ... has no corresponding tool_use block". - // Mirrors the blocking codepath (executeTurn) which sets the same. - metadata: { toolUseId: effectiveCall.id } - }, - { - id: crypto.randomUUID(), - role: "tool", - content: typeof effectiveResult.output === "string" ? effectiveResult.output : JSON.stringify(effectiveResult.output), - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "tool", - metadata: { toolName: effectiveCall.toolName, callId: effectiveCall.id } - } - ]; - if (postTool.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "post_tool", - reason: postTool.reason - })); - toolLoopBreak = true; - break; - } - } - if (toolLoopBreak) - break; - if (tracker.isExhausted()) { - budgetExhaustedDuringLoop = true; - const status = tracker.getStatus(); - events.push(annotationEvent(agent.id, sessionId, "streaming.budget_exhausted", { - reason: status.exhaustedReason, - calls: status.calls - })); - yield ` -[Agent budget exhausted${status.exhaustedReason ? `: ${status.exhaustedReason}` : ""}]`; - break; - } - } - const candidateMessage = earlyShortCircuit ? earlyExitResponse ?? createAssistantMessage(crypto.randomUUID(), `[Agent short-circuited${earlyExitReason ? `: ${earlyExitReason}` : ""}]`, []) : createAssistantMessage(crypto.randomUUID(), budgetExhaustedDuringLoop && lastAssistantContent.trim().length === 0 ? "[Agent budget exhausted]" : lastAssistantContent, allToolResults.map((r) => ({ - toolName: r.toolName, - input: {}, - output: r.output, - durationMs: r.durationMs, - status: r.status - }))); - let responseMessage = candidateMessage; - let memoriesCaptured = []; - let droppedCandidates = []; - if (!earlyShortCircuit) { - const preCapture = await fire("pre_capture", { - response: candidateMessage, - toolResults: allToolResults, - ontology - }); - if (preCapture.correctionRequested) { - events.push(annotationEvent(agent.id, sessionId, "streaming.correction_requested", { - hookName: preCapture.hookName, - correctionPrompt: preCapture.correctionPrompt - })); - } else if (preCapture.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "pre_capture", - reason: preCapture.reason - })); - } - responseMessage = preCapture.shortCircuited && preCapture.finalResponse ? preCapture.finalResponse : candidateMessage; - try { - const captureResult = await captureFromResponse({ - response: responseMessage.content, - ontology, - agent, - sessionId, - turnId, - memory: deps.memory - }); - memoriesCaptured = captureResult.captured; - droppedCandidates = captureResult.dropped; - for (const errMsg of captureResult.errors) { - events.push(annotationEvent(agent.id, sessionId, "streaming.memory_capture_error", { - error: errMsg - })); - } - for (const fe of captureResult.frictionEvents) { - events.push(fe); - } - } catch (err) { - events.push(annotationEvent(agent.id, sessionId, "streaming.memory_capture_error", { - error: err instanceof Error ? err.message : String(err) - })); - } - const availableEntityTypesAtCapture = ontology.entityTypes.map((e) => e.name); - let recentlyCaptured; - if (memoriesCaptured.length > 0) { - for (const entry of memoriesCaptured) { - try { - const chain = await deps.memory.getSupersedeChain(entry.id); - if (chain.length === 0) - continue; - const propertyNames = Object.keys(entry.structured).sort(); - const nonIdKeys = propertyNames.filter((p) => p !== "id"); - const propertyName = nonIdKeys[0] ?? propertyNames[0]; - if (!propertyName) - continue; - const coverage = chain.filter((p) => propertyName in p.structured).length; - if (coverage < Math.ceil(chain.length / 2)) - continue; - const priorValues = [...chain].reverse().map((prior) => prior.structured[propertyName]); - recentlyCaptured = { - chainAnchor: entry.id, - entityType: entry.entityType, - propertyName, - currentValue: entry.structured[propertyName], - priorValues - }; - break; - } catch { - continue; - } - } - } - const postCapture = await fire("post_capture", { - captured: memoriesCaptured, - availableEntityTypes: availableEntityTypesAtCapture, - droppedCandidates, - ...recentlyCaptured ? { recentlyCaptured } : {} - }); - if (postCapture.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "post_capture", - reason: postCapture.reason - })); - } - } - session = addMessage(session, responseMessage); - await deps.sessions.save(session); - events.push(createEvent(crypto.randomUUID(), "message.sent", agent.id, { messageId: responseMessage.id }, sessionId)); - const finalBudgetStatus = tracker.getStatus(); - const budgetExhausted = budgetExhaustedDuringLoop || finalBudgetStatus.exhausted; - const result = { - response: responseMessage, - session, - memoriesCaptured, - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - // Compute via the shared `estimateCostUSD` helper so blocking + - // streaming produce identical numbers for the same model + tokens. - // Cache tokens flow through the optional usage fields so cached - // agents get accurate cost (cache_read at 0.1× input rate, cache_write - // at 1.25×). - estimatedCostUSD: estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) - }, - budgetExhausted, - budgetStatus: { - calls: finalBudgetStatus.calls, - tokens: finalBudgetStatus.tokens, - timeMs: finalBudgetStatus.timeMs, - ...finalBudgetStatus.exhaustedReason ? { reason: finalBudgetStatus.exhaustedReason } : {} - } - }; - try { - await fire("post_turn", { - result, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - } catch { - } - } catch (err) { - const partialBudgetStatus = tracker.getStatus(); - const partialResult = { - response: createAssistantMessage(crypto.randomUUID(), `[Agent error: ${err instanceof Error ? err.message : String(err)}]`, []), - session, - memoriesCaptured: [], - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - // Even on the error path, attribute real cost for tokens already - // consumed before the throw — billing observers / cost-trackers - // at post_turn should see the spend that already happened. - estimatedCostUSD: estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) - }, - budgetExhausted: budgetExhaustedDuringLoop || partialBudgetStatus.exhausted, - budgetStatus: { - calls: partialBudgetStatus.calls, - tokens: partialBudgetStatus.tokens, - timeMs: partialBudgetStatus.timeMs, - ...partialBudgetStatus.exhaustedReason ? { reason: partialBudgetStatus.exhaustedReason } : {} - } - }; - try { - await fire("post_turn", { - result: partialResult, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - } catch { - } - throw err; - } -} -function systemMessage(phase, reason, finalResponse) { - if (finalResponse?.content) - return finalResponse.content; - return `[Agent short-circuited at ${phase}${reason ? `: ${reason}` : ""}]`; -} -function annotationEvent(agentId, sessionId, key, data) { - return { - id: crypto.randomUUID(), - type: "turn.annotated", - agentId, - sessionId, - timestamp: /* @__PURE__ */ new Date(), - payload: { key, ...data } - }; -} - -// ../freya/packages/runtime/dist/create-agent-runtime.js -function createAgentRuntime(adapters, agents = /* @__PURE__ */ new Map()) { - const agentMap = new Map(agents); - const ontologyService = { - async compose(agentId) { - const agent = agentMap.get(agentId); - if (!agent) - throw new Error(`Agent not found: ${agentId}`); - const scopes = agent.config.ontologyScopes; - return adapters.ontologyRepo.compose(scopes); - }, - render(ontology) { - return renderOntologySimple(ontology); - }, - async validate(entityType, data) { - const firstAgent = agentMap.values().next().value; - if (!firstAgent) - return true; - const ontology = await adapters.ontologyRepo.compose(firstAgent.config.ontologyScopes); - const result = adapters.ontologyRepo.validateEntry(entityType, data, ontology); - return result.valid; - } - }; - const ontologyRenderer = { - render: renderOntologySimple - }; - const registry2 = { - async getAgent(agentId) { - return agentMap.get(agentId) ?? null; - }, - async listAgents() { - return Array.from(agentMap.values()); - }, - async registerAgent(config2, deploymentId) { - const agent = createAgent(config2, deploymentId); - agentMap.set(agent.id, agent); - return agent; - } - }; - return { - async handleMessage({ agentId, sessionId, message: message2, budget }) { - const agent = agentMap.get(agentId); - if (!agent) - throw new Error(`Agent not found: ${agentId}`); - const result = await executeTurn(agent, sessionId, message2, { - llm: adapters.llm, - tools: adapters.toolExecutor, - memory: adapters.memory, - sessions: adapters.sessions, - ontologyService, - ontologyRenderer, - transport: adapters.transport ?? noopTransport, - embedding: adapters.embedding - }, budget); - return { - message: result.response, - session: result.session, - memoriesCaptured: result.memoriesCaptured, - delegations: [], - usage: result.usage - }; - }, - handleMessageStream({ agentId, sessionId, message: message2, budget, hooks, signal }) { - const agent = agentMap.get(agentId); - if (!agent) - throw new Error(`Agent not found: ${agentId}`); - return executeStreamingTurn(agent, sessionId, message2, { - llm: adapters.llm, - tools: adapters.toolExecutor, - memory: adapters.memory, - sessions: adapters.sessions, - ontologyService, - ontologyRenderer, - embedding: adapters.embedding, - ...hooks ? { hooks } : {} - }, budget, signal); - }, - async startSession({ agentId, userId, transportId }) { - const session = createSession(crypto.randomUUID(), agentId, userId, transportId); - await adapters.sessions.save(session); - return session; - }, - async getAgent(agentId) { - return agentMap.get(agentId) ?? null; - }, - registry: registry2 - }; -} -function renderOntologySimple(ontology) { - if (ontology.entityTypes.length === 0) - return ""; - const lines = ["# Domain Ontology"]; - for (const entity of ontology.entityTypes) { - const props = entity.properties.map((p) => p.name).join(", "); - const rels = ontology.relationships.filter((r) => r.fromType === entity.name).map((r) => `${r.name}\u2192${r.toType}`).join(", "); - let line = `## ${entity.name}: [${props}]`; - if (rels) - line += ` | ${rels}`; - if (entity.description && entity.description !== entity.name) { - line += ` -${entity.description}`; - } - lines.push(line); - } - return lines.join("\n"); -} -var noopTransport = { - async send() { - }, - async stream() { - } -}; - -// ../freya/packages/llm/dist/adapters/anthropic.js -function toAnthropicMessages(messages) { - const result = []; - for (const m of messages) { - if (m.role === "user") { - result.push({ role: "user", content: m.content }); - } else if (m.role === "assistant") { - if (m.toolInvocations && m.toolInvocations.length > 0) { - const contentBlocks = []; - if (m.content) { - contentBlocks.push({ type: "text", text: m.content }); - } - const toolUseId = m.metadata?.toolUseId || m.toolInvocations[0].toolName + "_" + Math.random().toString(36).slice(2); - for (const tool of m.toolInvocations) { - contentBlocks.push({ - type: "tool_use", - id: toolUseId, - name: tool.toolName, - input: tool.input - }); - } - result.push({ role: "assistant", content: contentBlocks }); - } else { - result.push({ role: "assistant", content: m.content }); - } - } else if (m.role === "tool") { - const toolName = m.metadata?.toolName || "unknown"; - const callId = m.metadata?.callId || toolName + "_" + Date.now(); - result.push({ - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: callId, - content: m.content - } - ] - }); - } - } - return result; -} -function toAnthropicTools(tools) { - return tools.map((t) => ({ - name: t.name, - description: t.description, - input_schema: t.inputSchema - })); -} -var AnthropicLLM = class { - config; - constructor(config2) { - this.config = config2; - } - async complete(params) { - const body = { - model: params.model || this.config.defaultModel || "claude-sonnet-4-6", - max_tokens: params.maxTokens || this.config.maxTokens || 4096, - system: params.systemPrompt, - messages: toAnthropicMessages(params.messages) - }; - if (params.temperature !== void 0) { - body.temperature = params.temperature; - } - if (params.tools && params.tools.length > 0) { - body.tools = toAnthropicTools(params.tools); - } - const baseUrl = this.config.baseUrl || "https://api.anthropic.com"; - const response = await fetch(`${baseUrl}/v1/messages`, { - method: "POST", - headers: { - "Content-Type": "application/json", - "x-api-key": this.config.apiKey, - "anthropic-version": "2023-06-01" - }, - body: JSON.stringify(body) - }); - if (!response.ok) { - const errorBody = await response.text(); - throw new Error(`Anthropic API error: ${response.status} ${errorBody}`); - } - const data = await response.json(); - let content = ""; - const toolCalls = []; - for (const block of data.content || []) { - if (block.type === "text") { - content += block.text; - } else if (block.type === "tool_use") { - toolCalls.push({ - id: block.id, - toolName: block.name, - input: block.input, - timestamp: /* @__PURE__ */ new Date() - }); - } - } - return { - content, - toolCalls, - usage: { - inputTokens: data.usage?.input_tokens || 0, - outputTokens: data.usage?.output_tokens || 0 - }, - stopReason: data.stop_reason === "tool_use" ? "tool_use" : data.stop_reason === "max_tokens" ? "max_tokens" : "end_turn" - }; - } - async *stream(params) { - const body = { - model: params.model || this.config.defaultModel || "claude-sonnet-4-6", - max_tokens: params.maxTokens || this.config.maxTokens || 4096, - system: params.systemPrompt, - messages: toAnthropicMessages(params.messages), - stream: true - }; - if (params.temperature !== void 0) { - body.temperature = params.temperature; - } - if (params.tools && params.tools.length > 0) { - body.tools = toAnthropicTools(params.tools); - } - const baseUrl = this.config.baseUrl || "https://api.anthropic.com"; - const response = await fetch(`${baseUrl}/v1/messages`, { - method: "POST", - headers: { - "Content-Type": "application/json", - "x-api-key": this.config.apiKey, - "anthropic-version": "2023-06-01" - }, - body: JSON.stringify(body), - // Aborting this signal tears down the HTTP request to Anthropic, which - // stops token generation server-side — true cancellation, not just - // closing the consumer's reader. - signal: params.signal - }); - if (!response.ok) { - const errorBody = await response.text(); - throw new Error(`Anthropic streaming error: ${response.status} ${errorBody}`); - } - const reader = response.body?.getReader(); - if (!reader) - throw new Error("No response body for streaming"); - const decoder2 = new TextDecoder(); - let buffer = ""; - let inputTokens = 0; - let outputTokens = 0; - let cacheReadTokens = 0; - let cacheWriteTokens = 0; - let sawUsage = false; - const pendingToolBlocks = /* @__PURE__ */ new Map(); - const sanitizeTokens = (v) => { - if (typeof v !== "number" || !Number.isFinite(v) || v < 0) - return null; - return v; - }; - const doneChunk = () => { - if (!sawUsage) - return { type: "done" }; - const usage = { - inputTokens, - outputTokens - }; - if (cacheReadTokens > 0) - usage.cacheReadTokens = cacheReadTokens; - if (cacheWriteTokens > 0) - usage.cacheWriteTokens = cacheWriteTokens; - return { type: "done", usage }; - }; - while (true) { - const { done, value } = await reader.read(); - if (done) - break; - buffer += decoder2.decode(value, { stream: true }); - const lines = buffer.split("\n"); - buffer = lines.pop() || ""; - for (const line of lines) { - if (!line.startsWith("data: ")) - continue; - const data = line.slice(6).trim(); - if (data === "[DONE]") { - yield doneChunk(); - return; - } - try { - const event = JSON.parse(data); - if (event.type === "message_start") { - const u = event.message?.usage; - if (u) { - const inp = sanitizeTokens(u.input_tokens); - const out = sanitizeTokens(u.output_tokens); - const cr = sanitizeTokens(u.cache_read_input_tokens); - const cw = sanitizeTokens(u.cache_creation_input_tokens); - if (inp !== null || out !== null || cr !== null || cw !== null) { - sawUsage = true; - if (inp !== null) - inputTokens = inp; - if (out !== null) - outputTokens = out; - if (cr !== null) - cacheReadTokens = cr; - if (cw !== null) - cacheWriteTokens = cw; - } - } - } else if (event.type === "content_block_delta") { - if (event.delta?.type === "text_delta") { - yield { type: "text", content: event.delta.text }; - } else if (event.delta?.type === "input_json_delta") { - const idx = event.index; - const pending = idx !== void 0 ? pendingToolBlocks.get(idx) : void 0; - if (pending && typeof event.delta.partial_json === "string") { - pending.jsonBuffer += event.delta.partial_json; - } - } - } else if (event.type === "content_block_start") { - if (event.content_block?.type === "tool_use") { - const idx = event.index; - if (idx !== void 0) { - pendingToolBlocks.set(idx, { - id: event.content_block.id, - toolName: event.content_block.name, - jsonBuffer: "" - }); - } - } - } else if (event.type === "content_block_stop") { - const idx = event.index; - const pending = idx !== void 0 ? pendingToolBlocks.get(idx) : void 0; - if (pending) { - let input = {}; - if (pending.jsonBuffer.trim().length > 0) { - try { - const parsed = JSON.parse(pending.jsonBuffer); - if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) { - input = parsed; - } - } catch { - } - } - yield { - type: "tool_call", - toolCall: { - id: pending.id, - toolName: pending.toolName, - input, - timestamp: /* @__PURE__ */ new Date() - } - }; - pendingToolBlocks.delete(idx); - } - } else if (event.type === "message_delta") { - const u = event.usage; - if (u) { - const out = sanitizeTokens(u.output_tokens); - if (out !== null) { - sawUsage = true; - outputTokens = out; - } - } - } else if (event.type === "message_stop") { - yield doneChunk(); - return; - } - } catch { - } - } - } - if (buffer.length > 0) { - for (const line of buffer.split("\n")) { - if (!line.startsWith("data: ")) - continue; - const data = line.slice(6).trim(); - if (data === "[DONE]" || data.length === 0) - continue; - try { - const event = JSON.parse(data); - if (event.type === "message_delta") { - const u = event.usage; - if (u) { - const out = sanitizeTokens(u.output_tokens); - if (out !== null) { - sawUsage = true; - outputTokens = out; - } - } - } - } catch { - } - } - } - yield doneChunk(); - } -}; - -// ../freya/packages/llm/dist/adapters/fake-embedding.js -var FakeEmbedding = class { - callCount = 0; - async embed(text) { - this.callCount++; - const vec = new Array(8).fill(0); - for (let i = 0; i < text.length; i++) { - vec[i % vec.length] += text.charCodeAt(i) / 1e3; - } - const magnitude = Math.sqrt(vec.reduce((s3, v) => s3 + v * v, 0)); - return magnitude > 0 ? vec.map((v) => v / magnitude) : vec; - } - async embedBatch(texts) { - return Promise.all(texts.map((t) => this.embed(t))); - } - getCallCount() { - return this.callCount; - } -}; - -// ../freya/packages/memory/dist/adapters/in-memory-repo.js -var InMemoryMemoryRepository = class { - entries = []; - events = []; - async store(entry) { - this.entries.push(entry); - this.events.push({ - id: crypto.randomUUID(), - entryId: entry.id, - action: "created", - newValue: entry.content, - author: entry.source.author, - timestamp: /* @__PURE__ */ new Date() - }); - } - async recall(params) { - const limit = params.limit ?? 10; - const queryLower = params.query.toLowerCase(); - const entries = this.entries.filter((e) => { - if (e.agentId !== params.agentId) - return false; - if (e.status !== "active") - return false; - if (params.scope && e.scope !== params.scope) - return false; - if (params.scopeId && e.scopeId !== params.scopeId) - return false; - if (params.entityType && e.entityType !== params.entityType) - return false; - return e.content.toLowerCase().includes(queryLower); - }).slice(0, limit); - const textMatchCount = entries.length; - return { - entries, - source: textMatchCount > 0 ? "text" : "none", - vectorCapable: false, - vectorMatchCount: 0, - textMatchCount - }; - } - async supersede(entryId, newEntryId) { - const entry = this.entries.find((e) => e.id === entryId); - if (entry) { - const idx = this.entries.indexOf(entry); - this.entries[idx] = { - ...entry, - status: "superseded", - supersededBy: newEntryId - }; - this.events.push({ - id: crypto.randomUUID(), - entryId, - action: "superseded", - previousValue: entry.content, - author: "system", - timestamp: /* @__PURE__ */ new Date() - }); - } - } - async getEventLog(entryId) { - return this.events.filter((e) => e.entryId === entryId); - } - async getByEntityType(agentId, entityType) { - return this.entries.filter((e) => e.agentId === agentId && e.entityType === entityType && e.status === "active"); - } - /** - * Walk the supersede chain backward from `entryId`. - * - * At each step we find entries whose `supersededBy` points at the current - * node, take the most recent one (by `createdAt` desc — handles the - * unusual case of multiple predecessors pointing at the same successor), - * and continue from there. A visited-set protects against pathological - * cycles (a node whose `supersededBy` ultimately loops back to itself or - * to an ancestor in the walk). - * - * Capped at 50 versions — long-lived facts can rack up a lot of versions, - * and the detector use case only needs "what shapes have we seen recently". - */ - async getSupersedeChain(entryId) { - const CAP = 50; - const chain = []; - const visited = /* @__PURE__ */ new Set(); - let cursor = entryId; - visited.add(cursor); - const anchor = this.entries.find((e) => e.id === entryId); - if (anchor === void 0) - return []; - while (chain.length < CAP) { - const predecessors = this.entries.filter((e) => e.supersededBy === cursor && e.agentId === anchor.agentId && e.scope === anchor.scope && e.scopeId === anchor.scopeId && e.status === "superseded").sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); - if (predecessors.length === 0) - break; - const prior = predecessors[0]; - if (visited.has(prior.id)) { - break; - } - visited.add(prior.id); - chain.push(prior); - cursor = prior.id; - } - return chain; - } - // Test helpers - getAll() { - return [...this.entries]; - } - getAllEvents() { - return [...this.events]; - } - clear() { - this.entries = []; - this.events = []; - } -}; - -// ../freya/packages/memory/dist/adapters/in-memory-session-repo.js -var InMemorySessionRepository = class { - sessions = /* @__PURE__ */ new Map(); - async get(id) { - return this.sessions.get(id) ?? null; - } - async save(session) { - this.sessions.set(session.id, session); - } - async findByUser(userId, agentId, limit) { - const matches2 = Array.from(this.sessions.values()).filter((s3) => s3.userId === userId && s3.agentId === agentId).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); - return limit ? matches2.slice(0, limit) : matches2; - } - async findByUserLightweight(userId, agentId, limit) { - const matches2 = Array.from(this.sessions.values()).filter((s3) => s3.userId === userId && s3.agentId === agentId).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()); - const limited = limit ? matches2.slice(0, limit) : matches2; - return limited.map((s3) => { - const firstUserMsg = s3.messages.find((m) => m.role === "user"); - const lastMsg = s3.messages.length > 0 ? s3.messages[s3.messages.length - 1] : void 0; - return { - id: s3.id, - agentId: s3.agentId, - userId: s3.userId, - status: s3.status, - turnCount: s3.turnCount, - messageCount: s3.messages.length, - createdAt: s3.createdAt, - updatedAt: s3.updatedAt, - firstMessage: firstUserMsg ? firstUserMsg.content.substring(0, 100) : void 0, - lastMessage: lastMsg ? lastMsg.content.substring(0, 100) : void 0 - }; - }); - } - // Test helpers - clear() { - this.sessions.clear(); - } - getAll() { - return Array.from(this.sessions.values()); - } -}; - -// ../freya/packages/ontology/dist/composer/composer.js -function composeLayers(layers) { - const entityMap = /* @__PURE__ */ new Map(); - const allRelationships = []; - for (const layer of layers) { - for (const entity of layer.entityTypes) { - const existing = entityMap.get(entity.name); - if (existing) { - const existingPropNames = new Set(existing.properties.map((p) => p.name)); - const newProps = entity.properties.filter((p) => !existingPropNames.has(p.name)); - entityMap.set(entity.name, { - ...existing, - properties: [...existing.properties, ...newProps], - description: entity.description || existing.description - }); - } else { - entityMap.set(entity.name, entity); - } - } - allRelationships.push(...layer.relationships); - } - const relationshipMap = /* @__PURE__ */ new Map(); - for (const rel of allRelationships) { - relationshipMap.set(rel.id, rel); - } - return { - layers, - entityTypes: Array.from(entityMap.values()), - relationships: Array.from(relationshipMap.values()), - version: layers.map((l) => `${l.name}@${l.version}`).join("+") - }; -} - -// ../freya/packages/ontology/dist/validator/validator.js -function validateAgainstOntology(entityType, data, ontology) { - const errors = []; - const warnings = []; - const entity = ontology.entityTypes.find((e) => e.name === entityType); - if (!entity) { - return { - valid: false, - errors: [{ field: "entityType", message: `Unknown entity type: ${entityType}`, code: "unknown_entity" }], - warnings: [] - }; - } - for (const prop of entity.properties) { - if (prop.required && !(prop.name in data)) { - errors.push({ - field: prop.name, - message: `Required property missing: ${prop.name}`, - code: "missing_required" - }); - } - } - for (const [key, value] of Object.entries(data)) { - const prop = entity.properties.find((p) => p.name === key); - if (!prop) { - warnings.push(`Property "${key}" not defined in ontology for ${entityType}`); - continue; - } - if (prop.type === "enum" && prop.enumValues && value !== void 0) { - if (!prop.enumValues.includes(String(value))) { - errors.push({ - field: key, - message: `Invalid value "${value}" for enum ${key}. Expected one of: ${prop.enumValues.join(", ")}`, - code: "invalid_enum" - }); - } - } - if (value !== void 0 && value !== null) { - const typeValid = checkType(value, prop.type); - if (!typeValid) { - errors.push({ - field: key, - message: `Expected ${prop.type} for ${key}, got ${typeof value}`, - code: "invalid_type" - }); - } - } - } - return { - valid: errors.length === 0, - errors, - warnings - }; -} -function checkType(value, expectedType) { - switch (expectedType) { - case "string": - case "enum": - return typeof value === "string"; - case "number": - return typeof value === "number"; - case "boolean": - return typeof value === "boolean"; - case "date": - return typeof value === "string" || value instanceof Date; - case "reference": - return typeof value === "string"; - default: - return true; - } -} - -// ../freya/packages/ontology/dist/adapters/in-memory-ontology-repo.js -var InMemoryOntologyRepository = class { - layers = /* @__PURE__ */ new Map(); - async getLayer(id) { - return this.layers.get(id) ?? null; - } - async getLayersByScope(scope) { - return Array.from(this.layers.values()).filter((l) => l.scope === scope); - } - async compose(layerIds) { - const layers = layerIds.map((id) => this.layers.get(id)).filter((l) => l != null); - return composeLayers(layers); - } - validateEntry(entityType, data, ontology) { - const result = validateAgainstOntology(entityType, data, ontology); - return { valid: result.valid, errors: result.errors.map((e) => e.message) }; - } - // Test helpers - addLayer(layer) { - this.layers.set(layer.id, layer); - } - clear() { - this.layers.clear(); - } -}; - -// ../freya/packages/ontology/dist/seed/loader.js -function parseOntologyYaml(id, raw) { - const entityTypes = []; - const relationships = []; - for (const [entityName, entityDef] of Object.entries(raw.entities || {})) { - const properties = []; - if (entityDef.properties) { - for (const prop of entityDef.properties) { - properties.push({ - name: prop, - type: "string", - required: false, - description: "" - }); - } - } - for (const [key, value] of Object.entries(entityDef)) { - if (Array.isArray(value) && key !== "properties" && key !== "belongs_to" && key !== "has_many" && key !== "connects" && value.every((v) => typeof v === "string")) { - properties.push({ - name: key, - type: "enum", - enumValues: value, - required: false, - description: `${key} for ${entityName}` - }); - } - } - entityTypes.push({ - id: `${id}:${entityName}`, - layerId: id, - name: entityName, - properties, - description: entityDef.description || entityName - }); - const belongsTo = entityDef.belongs_to ? Array.isArray(entityDef.belongs_to) ? entityDef.belongs_to : [entityDef.belongs_to] : []; - for (const target of belongsTo) { - relationships.push({ - id: `${id}:${entityName}:belongs_to:${target}`, - layerId: id, - name: "belongs_to", - fromType: entityName, - toType: target, - cardinality: "many_to_many", - description: `${entityName} belongs to ${target}` - }); - } - for (const target of entityDef.has_many || []) { - relationships.push({ - id: `${id}:${entityName}:has_many:${target}`, - layerId: id, - name: "has_many", - fromType: entityName, - toType: target, - cardinality: "one_to_many", - description: `${entityName} has many ${target}` - }); - } - for (const target of entityDef.connects || []) { - relationships.push({ - id: `${id}:${entityName}:connects:${target}`, - layerId: id, - name: "connects", - fromType: entityName, - toType: target, - cardinality: "many_to_many", - description: `${entityName} connects to ${target}` - }); - } - } - return { - id, - name: raw.name, - scope: raw.scope, - version: 1, - entityTypes, - relationships, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }; -} - -// ../freya/packages/mcp-client/dist/mcp-client-tool-executor.js -var NAME_MAX = 64; -var PROXY_LIST_MAX = 40; -function sanitizeName(raw) { - return raw.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, NAME_MAX); -} -var s = (v) => typeof v === "string" ? v.toLowerCase() : ""; -var McpClientToolExecutor = class { - servers; - scopePrefix; - mode; - clientFactory; - // One connected client per server, created lazily and reused across turns - // on a warm instance. `connecting` de-dupes concurrent connects. - clients = /* @__PURE__ */ new Map(); - connecting = /* @__PURE__ */ new Map(); - // Cached tools/list per server (per warm instance). - toolCache = /* @__PURE__ */ new Map(); - // namespaced tool name -> route, rebuilt on each discover. - routes = /* @__PURE__ */ new Map(); - constructor(config2) { - this.servers = new Map(config2.servers.map((server) => [server.id, server])); - this.scopePrefix = config2.scopePrefix ?? "mcp"; - this.mode = config2.mode ?? "direct"; - this.clientFactory = config2.clientFactory ?? createSdkClient; - } - /** Resolve a `mcp:` scope to its server, or null if not ours. */ - serverForScope(scope) { - const prefix = `${this.scopePrefix}:`; - if (!scope.startsWith(prefix)) - return null; - return this.servers.get(scope.slice(prefix.length)) ?? null; - } - async getClient(server) { - const existing = this.clients.get(server.id); - if (existing) - return existing; - const inFlight = this.connecting.get(server.id); - if (inFlight) - return inFlight; - const p = (async () => { - const client = this.clientFactory(server); - await client.connect(); - this.clients.set(server.id, client); - this.connecting.delete(server.id); - return client; - })().catch((e) => { - this.connecting.delete(server.id); - throw e; - }); - this.connecting.set(server.id, p); - return p; - } - /** Connect (if needed) and return the server's tools, cached per instance. */ - async fetchRawTools(server) { - const cached2 = this.toolCache.get(server.id); - if (cached2) - return cached2; - const client = await this.getClient(server); - const listed = await client.listTools(); - const tools = listed.tools ?? []; - this.toolCache.set(server.id, tools); - return tools; - } - async discoverTools(scope) { - const server = this.serverForScope(scope); - if (!server) - return []; - return this.mode === "proxy" ? this.discoverProxy(server, scope) : this.discoverDirect(server, scope); - } - /** Proxy mode: two small tools, no network at discovery time. */ - discoverProxy(server, scope) { - const listName = sanitizeName(`${server.id}__list_tools`); - const callName = sanitizeName(`${server.id}__call_tool`); - this.routes.set(listName, { serverId: server.id, proxy: "list" }); - this.routes.set(callName, { serverId: server.id, proxy: "call" }); - return [ - { - name: listName, - description: `List or search the tools available from the "${server.id}" MCP server. Returns each tool's name, description, and input schema. Call this to discover what "${server.id}" can do before using ${callName}.`, - inputSchema: { - type: "object", - properties: { - query: { - type: "string", - description: "Optional filter over tool name/description." - } - }, - additionalProperties: false - }, - source: scope, - requiresApproval: false, - permissionScope: `${scope}:list` - }, - { - name: callName, - description: `Invoke a tool on the "${server.id}" MCP server. Use ${listName} first to find the exact tool name and its required arguments.`, - inputSchema: { - type: "object", - properties: { - tool: { type: "string", description: `Tool name from ${listName}.` }, - arguments: { - type: "object", - description: "Arguments object matching that tool's input schema." - } - }, - required: ["tool"], - additionalProperties: false - }, - source: scope, - requiresApproval: false, - permissionScope: `${scope}:call` - } - ]; - } - /** Direct mode: fan every server tool out as its own definition. */ - async discoverDirect(server, scope) { - let tools; - try { - tools = await this.fetchRawTools(server); - } catch (e) { - console.log(`mcp-client: discover failed for ${server.id}:`, e instanceof Error ? e.message : String(e)); - return []; - } - const defs = []; - const used = /* @__PURE__ */ new Set(); - for (const tool of tools) { - let name = sanitizeName(`${server.id}__${tool.name}`); - if (used.has(name)) { - const base = name.slice(0, NAME_MAX - 3); - let i = 1; - while (used.has(`${base}_${i}`)) - i++; - name = `${base}_${i}`; - } - used.add(name); - this.routes.set(name, { serverId: server.id, toolName: tool.name }); - defs.push({ - name, - description: tool.description ?? `${tool.name} (via ${server.id})`, - inputSchema: tool.inputSchema ?? { type: "object", properties: {} }, - source: scope, - requiresApproval: false, - permissionScope: `${scope}:call` - }); - } - return defs; - } - async execute(call) { - const start = Date.now(); - const done = (output, status, error2) => ({ - callId: call.id, - toolName: call.toolName, - output, - status, - ...error2 ? { error: error2 } : {}, - durationMs: Date.now() - start, - timestamp: /* @__PURE__ */ new Date() - }); - const route = this.routes.get(call.toolName); - if (!route) - return done(null, "error", `unknown MCP tool: ${call.toolName}`); - const server = this.servers.get(route.serverId); - if (!server) - return done(null, "error", `unknown MCP server: ${route.serverId}`); - const input = call.input ?? {}; - try { - if (route.proxy === "list") { - const query = typeof input.query === "string" ? input.query : ""; - const tools = (await this.fetchRawTools(server)).filter((t) => !query || s(t.name).includes(s(query)) || s(t.description).includes(s(query))).slice(0, PROXY_LIST_MAX).map((t) => ({ - tool: t.name, - description: t.description ?? "", - inputSchema: t.inputSchema ?? { type: "object" } - })); - return done({ server: server.id, count: tools.length, tools }, "success"); - } - const toolName = route.proxy === "call" ? typeof input.tool === "string" ? input.tool : "" : route.toolName ?? ""; - if (!toolName) { - return done(null, "error", `no tool name provided for ${call.toolName}`); - } - const args = route.proxy === "call" ? input.arguments ?? {} : input; - const client = await this.getClient(server); - const result = await client.callTool({ name: toolName, arguments: args }); - const text = (result.content ?? []).filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n").trim(); - const output = text || result.content || null; - return done(output, result.isError ? "error" : "success"); - } catch (e) { - return done(null, "error", e instanceof Error ? e.message : String(e)); - } - } - /** Close all open MCP connections (best-effort). */ - async close() { - for (const client of this.clients.values()) { - try { - await client.close?.(); - } catch { - } - } - this.clients.clear(); - } -}; -function createSdkClient(server) { - let ready = null; - const init = async () => { - const { Client: Client2, StreamableHTTPClientTransport: StreamableHTTPClientTransport2 } = await Promise.resolve().then(() => (init_dist3(), dist_exports)); - const client = new Client2({ name: "freya-mcp-client", version: "0.1.0" }); - const transport = new StreamableHTTPClientTransport2(new URL(server.url), server.headers ? { requestInit: { headers: server.headers } } : void 0); - await client.connect(transport); - return { - listTools: () => client.listTools(), - callTool: (a) => client.callTool(a), - close: () => client.close() - }; - }; - return { - async connect() { - ready = init(); - await ready; - }, - async listTools() { - if (!ready) - ready = init(); - return (await ready).listTools(); - }, - async callTool(a) { - if (!ready) - ready = init(); - return (await ready).callTool(a); - }, - async close() { - if (ready) - await (await ready).close(); - } - }; -} - -// website/tools/freya-vendor/entry.mjs -var AGENT_ID = "frigg-web"; -var TRANSPORT = "netlify-web"; -var FRIGG_ONTOLOGY = { - name: "frigg", - scope: "domain", - entities: { - Platform: { - description: "A third-party software product Frigg integrates with (e.g. HubSpot, Salesforce, Attio).", - properties: ["name", "vendor"] - }, - ApiModule: { - description: "A prebuilt Frigg connector for a platform API, installed with `frigg install ` and drawn from the api-module-library.", - properties: ["name", "provider", "authType"], - category: [ - "ai", - "analytics", - "commerce", - "communication", - "crm", - "devtools", - "finance", - "hr", - "marketing", - "other", - "productivity", - "storage", - "support" - ], - complexity: ["Low", "Medium", "High"], - status: ["Active", "Beta", "Planned"], - belongs_to: "Platform" - }, - Integration: { - description: "A running integration a developer builds by extending IntegrationBase, wiring API modules to events (USER_ACTION, CRON, QUEUE, WEBHOOK).", - properties: ["name", "useCase"], - connects: ["ApiModule", "Primitive"] - }, - Primitive: { - description: "A Frigg building block exposed to developers and their agents: an Endpoint, a Queue, a Provider-native backend, or a Fenestra in-app UI experience.", - properties: ["name"], - kind: ["Endpoint", "Queue", "ProviderNative", "Fenestra"] - }, - Capability: { - description: "A typed declaration of what a module or integration can do, pointing at a spec and its implementation (the mcp-tool / agent-tooling surface).", - properties: ["name", "spec"], - belongs_to: "ApiModule" - }, - Adr: { - description: 'A Frigg architecture decision record shaping the roadmap, tracked on the "next" branch and surfaced at /roadmap/.', - properties: ["num", "title", "theme"], - status: ["Accepted", "Proposed", "Superseded", "Draft"] - }, - Visitor: { - description: "A person chatting with the assistant on the site.", - properties: ["name", "stack", "interest"] - } - } -}; -var activeData = { adrs: [], apis: [], categories: [], builtCount: 0 }; -var s2 = (v) => typeof v === "string" ? v.toLowerCase() : ""; -var matches = (hay, q) => !q || s2(hay).includes(s2(q)); -var RoadmapTools = class { - async discoverTools(scope) { - if (scope !== "roadmap") return []; - return [ - { - name: "catalog_stats", - description: 'Frigg roadmap catalog summary: number of ADRs, number of API modules, how many are already built, and the list of API categories. Call this first for any "how many / what categories" question.', - inputSchema: { type: "object", properties: {}, additionalProperties: false }, - source: "roadmap", - requiresApproval: false, - permissionScope: "roadmap:read" - }, - { - name: "search_adrs", - description: "Search Frigg architecture decision records (ADRs). Filter by free-text query (matches title/summary/theme) and/or status (e.g. Accepted, Proposed). Returns matching ADRs with number, title, status, theme, one-line summary, and URL.", - inputSchema: { - type: "object", - properties: { - query: { type: "string", description: "Free-text filter over title/summary/theme" }, - status: { type: "string", description: 'Exact status filter, e.g. "Accepted"' } - }, - additionalProperties: false - }, - source: "roadmap", - requiresApproval: false, - permissionScope: "roadmap:read" - }, - { - name: "search_apis", - description: "Search the Frigg API module catalog (224 integrations). Filter by free-text query (matches name/provider/description/tags), category, or built=true to only return modules that already exist in api-module-library. Returns a capped list plus the total match count so you can point people to /roadmap/ for the full set.", - inputSchema: { - type: "object", - properties: { - query: { type: "string" }, - category: { type: "string", description: "One of the catalog categories" }, - built: { type: "boolean", description: "If true, only modules already built" } - }, - additionalProperties: false - }, - source: "roadmap", - requiresApproval: false, - permissionScope: "roadmap:read" - } - ]; - } - async execute(call) { - const start = Date.now(); - const done = (output, status = "success", error2) => ({ - callId: call.id, - toolName: call.toolName, - output, - status, - error: error2, - durationMs: Date.now() - start, - timestamp: /* @__PURE__ */ new Date() - }); - try { - const input = call.input || {}; - if (call.toolName === "catalog_stats") { - return done({ - adrCount: activeData.adrs.length, - apiCount: activeData.apis.length, - builtCount: activeData.builtCount, - categories: activeData.categories - }); - } - if (call.toolName === "search_adrs") { - const hits = activeData.adrs.filter( - (a) => (matches(a.title, input.query) || matches(a.summary, input.query) || matches(a.theme, input.query)) && (!input.status || s2(a.status) === s2(input.status)) - ); - return done({ - total: hits.length, - adrs: hits.slice(0, 12).map((a) => ({ - num: a.num, - title: a.title, - status: a.status, - theme: a.theme, - summary: a.summary, - url: a.url - })) - }); - } - if (call.toolName === "search_apis") { - const hits = activeData.apis.filter( - (a) => (matches(a.name, input.query) || matches(a.provider, input.query) || matches(a.description, input.query) || Array.isArray(a.tags) && a.tags.some((t) => matches(t, input.query))) && (!input.category || s2(a.category) === s2(input.category)) && (input.built === void 0 || Boolean(a.built) === Boolean(input.built)) - ); - return done({ - total: hits.length, - showing: Math.min(hits.length, 15), - apis: hits.slice(0, 15).map((a) => ({ - slug: a.slug, - name: a.name, - provider: a.provider, - category: a.category, - status: a.status, - complexity: a.complexity, - built: !!a.built, - library: a.library - })) - }); - } - return done(null, "error", `unknown tool: ${call.toolName}`); - } catch (e) { - return done(null, "error", e && e.message ? e.message : String(e)); - } - } -}; -function mcpServersFromEnv() { - const servers = []; - if (process.env.CONTEXT7_API_KEY) { - servers.push({ - id: "frigg-docs", - url: process.env.CONTEXT7_MCP_URL || "https://mcp.context7.com/mcp", - headers: { CONTEXT7_API_KEY: process.env.CONTEXT7_API_KEY } - }); - } - const ghToken = process.env.GITHUB_MCP_TOKEN; - if (ghToken) { - servers.push({ - id: "frigg-repo", - url: process.env.GITHUB_MCP_URL || "https://api.githubcopilot.com/mcp/", - headers: { Authorization: `Bearer ${ghToken}` } - }); - } - return servers; -} -var CompositeToolExecutor = class { - constructor(executors) { - this.executors = executors; - this.owner = /* @__PURE__ */ new Map(); - } - async discoverTools(scope) { - for (const ex of this.executors) { - const defs = await ex.discoverTools(scope); - if (defs && defs.length) { - for (const d of defs) this.owner.set(d.name, ex); - return defs; - } - } - return []; - } - async execute(call) { - const ex = this.owner.get(call.toolName); - if (ex) return ex.execute(call); - return { - callId: call.id, - toolName: call.toolName, - output: null, - status: "error", - error: `no executor for tool: ${call.toolName}`, - durationMs: 0, - timestamp: /* @__PURE__ */ new Date() - }; - } -}; -var runtime = null; -var sessionsRepo = null; -var registered = false; -var mcpScopes = []; -function getRuntime() { - if (runtime) return runtime; - sessionsRepo = new InMemorySessionRepository(); - const apiKey = process.env.ANTHROPIC_API_KEY || ""; - const baseUrl = process.env.ANTHROPIC_BASE_URL || void 0; - const executors = [new RoadmapTools()]; - const mcpServers = mcpServersFromEnv(); - if (mcpServers.length) { - executors.push(new McpClientToolExecutor({ servers: mcpServers, mode: "proxy" })); - mcpScopes = mcpServers.map((sv) => `mcp:${sv.id}`); - } - const toolExecutor = new CompositeToolExecutor(executors); - runtime = createAgentRuntime({ - llm: new AnthropicLLM({ - apiKey, - baseUrl, - defaultModel: process.env.ASSISTANT_MODEL || "claude-opus-4-8", - maxTokens: 900 - }), - toolExecutor, - memory: new InMemoryMemoryRepository(), - ontologyRepo: (() => { - const repo = new InMemoryOntologyRepository(); - repo.addLayer(parseOntologyYaml("frigg", FRIGG_ONTOLOGY)); - return repo; - })(), - sessions: sessionsRepo, - embedding: new FakeEmbedding() - }); - return runtime; -} -async function ensureAgent(rt, systemPrompt, model) { - if (registered) return; - await rt.registry.registerAgent( - { - id: AGENT_ID, - name: "Freya", - type: "shared", - systemPrompt, - ontologyScopes: ["frigg"], - memoryNamespaces: ["default"], - toolScopes: ["roadmap", ...mcpScopes], - routines: [], - delegationTargets: [], - modelId: model || process.env.ASSISTANT_MODEL || "claude-opus-4-8", - maxTurns: 6 - }, - "friggframework-org" - ); - registered = true; -} -async function runTurn({ systemPrompt, model, messages, data }) { - if (data) { - const apis = data.apis || {}; - activeData = { - adrs: data.adrs && data.adrs.adrs || data.adrs || [], - apis: apis.apis || (Array.isArray(apis) ? apis : []), - categories: apis.categories || [], - builtCount: apis.builtCount || 0 - }; - } - const rt = getRuntime(); - await ensureAgent(rt, systemPrompt, model); - const history = messages.slice(0, -1); - const last = messages[messages.length - 1]; - const sessionId = crypto.randomUUID(); - let session = createSession(sessionId, AGENT_ID, "web-visitor", TRANSPORT); - for (const m of history) { - const msg = m.role === "assistant" ? createAssistantMessage(crypto.randomUUID(), m.content) : createUserMessage(crypto.randomUUID(), m.content, TRANSPORT); - session = addMessage(session, msg); - } - await sessionsRepo.save(session); - const result = await rt.handleMessage({ - agentId: AGENT_ID, - sessionId, - message: createUserMessage(crypto.randomUUID(), last.content, TRANSPORT) - }); - return result && result.message && result.message.content || ""; -} -export { - runTurn -}; + `)}v.write("payload.value = newResult;"),v.write("return payload;");let S=v.compile();return(_,$)=>S(m,_,$)},i,a=Rn,s=!uc.jitless,u=s&&fp.value,l=t.catchall,d;e._zod.parse=(m,v)=>{d??(d=n.value);let g=m.value;return a(g)?s&&u&&v?.async===!1&&v.jitless!==!0?(i||(i=o(t.shape)),m=i(m,v),l?I_([],g,m,v,d,e):m):r(m,v):(m.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),m)}});zc=C("$ZodUnion",(e,t)=>{we.init(e,t),Ie(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ie(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ie(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Ie(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>Bi(i.source)).join("|")})$`)}});let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let a=!1,s=[];for(let c of t.options){let u=c._zod.run({value:o.value,issues:[]},i);if(u instanceof Promise)s.push(u),a=!0;else{if(u.issues.length===0)return u;s.push(u)}}return a?Promise.all(s).then(c=>Nv(c,o,e,i)):Nv(s,o,e,i)}});T_=C("$ZodXor",(e,t)=>{zc.init(e,t),t.inclusive=!1;let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let a=!1,s=[];for(let c of t.options){let u=c._zod.run({value:o.value,issues:[]},i);u instanceof Promise?(s.push(u),a=!0):s.push(u)}return a?Promise.all(s).then(c=>jv(c,o,e,i)):jv(s,o,e,i)}}),C_=C("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,zc.init(e,t);let r=e._zod.parse;Ie(e._zod,"propValues",()=>{let o={};for(let i of t.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[s,c]of Object.entries(a)){o[s]||(o[s]=new Set);for(let u of c)o[s].add(u)}}return o});let n=_o(()=>{let o=t.options,i=new Map;for(let a of o){let s=a._zod.propValues?.[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let c of s){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,a)}}return i});e._zod.parse=(o,i)=>{let a=o.value;if(!Rn(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;let s=n.value.get(a?.[t.discriminator]);return s?s._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),o)}}),A_=C("$ZodIntersection",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([c,u])=>Uv(r,c,u)):Uv(r,i,a)}});am=C("$ZodTuple",(e,t)=>{we.init(e,t);let r=t.items;e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let a=[],s=[...r].reverse().findIndex(l=>l._zod.optin!=="optional"),c=s===-1?0:r.length-s;if(!t.rest){let l=i.length>r.length,d=i.length=i.length&&u>=c)continue;let d=l._zod.run({value:i[u],issues:[]},o);d instanceof Promise?a.push(d.then(m=>vc(m,n,u))):vc(d,n,u)}if(t.rest){let l=i.slice(r.length);for(let d of l){u++;let m=t.rest._zod.run({value:d,issues:[]},o);m instanceof Promise?a.push(m.then(v=>vc(v,n,u))):vc(m,n,u)}}return a.length?Promise.all(a).then(()=>n):n}});O_=C("$ZodRecord",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Vr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],a=t.keyType._zod.values;if(a){r.value={};let s=new Set;for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){s.add(typeof u=="number"?u.toString():u);let l=t.valueType._zod.run({value:o[u],issues:[]},n);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&r.issues.push(...Ot(u,d.issues)),r.value[u]=d.value})):(l.issues.length&&r.issues.push(...Ot(u,l.issues)),r.value[u]=l.value)}let c;for(let u in o)s.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&fc.test(s)&&c.issues.length){let d=t.keyType._zod.run({value:Number(s),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){t.mode==="loose"?r.value[s]=o[s]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Rt(d,n,lt())),input:s,path:[s],inst:e});continue}let l=t.valueType._zod.run({value:o[s],issues:[]},n);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&r.issues.push(...Ot(s,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...Ot(s,l.issues)),r.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}}),N_=C("$ZodMap",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),r;let i=[];r.value=new Map;for(let[a,s]of o){let c=t.keyType._zod.run({value:a,issues:[]},n),u=t.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||u instanceof Promise?i.push(Promise.all([c,u]).then(([l,d])=>{Mv(l,d,r,a,o,e,n)})):Mv(c,u,r,a,o,e,n)}return i.length?Promise.all(i).then(()=>r):r}});j_=C("$ZodSet",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Set))return r.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),r;let i=[];r.value=new Set;for(let a of o){let s=t.valueType._zod.run({value:a,issues:[]},n);s instanceof Promise?i.push(s.then(c=>Dv(c,r))):Dv(s,r)}return i.length?Promise.all(i).then(()=>r):r}});U_=C("$ZodEnum",(e,t)=>{we.init(e,t);let r=Wi(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>Gi.has(typeof o)).map(o=>typeof o=="string"?qt(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let a=o.value;return n.has(a)||o.issues.push({code:"invalid_value",values:r,input:a,inst:e}),o}}),M_=C("$ZodLiteral",(e,t)=>{if(we.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?qt(n):n?qt(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}}),D_=C("$ZodFile",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return o instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:o,inst:e}),r}}),q_=C("$ZodTransform",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new En(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new ir;return r.value=o,r}});sm=C("$ZodOptional",(e,t)=>{we.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ie(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ie(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bi(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>qv(i,r.value)):qv(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),L_=C("$ZodExactOptional",(e,t)=>{sm.init(e,t),Ie(e._zod,"values",()=>t.innerType._zod.values),Ie(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),V_=C("$ZodNullable",(e,t)=>{we.init(e,t),Ie(e._zod,"optin",()=>t.innerType._zod.optin),Ie(e._zod,"optout",()=>t.innerType._zod.optout),Ie(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bi(r.source)}|null)$`):void 0}),Ie(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),K_=C("$ZodDefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",Ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Lv(i,t)):Lv(o,t)}});J_=C("$ZodPrefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",Ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),F_=C("$ZodNonOptional",(e,t)=>{we.init(e,t),Ie(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Vv(i,e)):Vv(o,e)}});H_=C("$ZodSuccess",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new En("ZodSuccess");let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.issues.length===0,r)):(r.value=o.issues.length===0,r)}}),Z_=C("$ZodCatch",(e,t)=>{we.init(e,t),Ie(e._zod,"optin",()=>t.innerType._zod.optin),Ie(e._zod,"optout",()=>t.innerType._zod.optout),Ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(a=>Rt(a,n,lt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Rt(i,n,lt()))},input:r.value}),r.issues=[]),r)}}),W_=C("$ZodNaN",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),B_=C("$ZodPipe",(e,t)=>{we.init(e,t),Ie(e._zod,"values",()=>t.in._zod.values),Ie(e._zod,"optin",()=>t.in._zod.optin),Ie(e._zod,"optout",()=>t.out._zod.optout),Ie(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);return i instanceof Promise?i.then(a=>_c(a,t.in,n)):_c(i,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>_c(i,t.out,n)):_c(o,t.out,n)}});kc=C("$ZodCodec",(e,t)=>{we.init(e,t),Ie(e._zod,"values",()=>t.in._zod.values),Ie(e._zod,"optin",()=>t.in._zod.optin),Ie(e._zod,"optout",()=>t.out._zod.optout),Ie(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let i=t.in._zod.run(r,n);return i instanceof Promise?i.then(a=>Sc(a,t,n)):Sc(i,t,n)}else{let i=t.out._zod.run(r,n);return i instanceof Promise?i.then(a=>Sc(a,t,n)):Sc(i,t,n)}}});G_=C("$ZodReadonly",(e,t)=>{we.init(e,t),Ie(e._zod,"propValues",()=>t.innerType._zod.propValues),Ie(e._zod,"values",()=>t.innerType._zod.values),Ie(e._zod,"optin",()=>t.innerType?._zod?.optin),Ie(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Kv):Kv(o)}});X_=C("$ZodTemplateLiteral",(e,t)=>{we.init(e,t);let r=[];for(let n of t.parts)if(typeof n=="object"&&n!==null){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);let o=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!o)throw new Error(`Invalid template literal part: ${n._zod.traits}`);let i=o.startsWith("^")?1:0,a=o.endsWith("$")?o.length-1:o.length;r.push(o.slice(i,a))}else if(n===null||hp.has(typeof n))r.push(qt(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,o)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),Y_=C("$ZodFunction",(e,t)=>(we.init(e,t),e._def=t,e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...n){let o=e._def.input?$p(e._def.input,n):n,i=Reflect.apply(r,this,o);return e._def.output?$p(e._def.output,i):i}},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...n){let o=e._def.input?await wp(e._def.input,n):n,i=await Reflect.apply(r,this,o);return e._def.output?await wp(e._def.output,i):i}},e._zod.parse=(r,n)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{let n=e.constructor;return Array.isArray(r[0])?new n({type:"function",input:new am({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new n({type:"function",input:r[0],output:e._def.output})},e.output=r=>{let n=e.constructor;return new n({type:"function",input:e._def.input,output:r})},e)),Q_=C("$ZodPromise",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(o=>t.innerType._zod.run({value:o,issues:[]},n))}),eS=C("$ZodLazy",(e,t)=>{we.init(e,t),Ie(e._zod,"innerType",()=>t.getter()),Ie(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ie(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ie(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ie(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),tS=C("$ZodCustom",(e,t)=>{Je.init(e,t),we.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>Jv(i,r,n,e));Jv(o,r,n,e)}})});var rS=q(()=>{de()});var nS=q(()=>{de()});var oS=q(()=>{de()});var iS=q(()=>{de()});var aS=q(()=>{de()});var sS=q(()=>{de()});var cS=q(()=>{de()});var uS=q(()=>{de()});function um(){return{localeError:fR()}}var fR,lm=q(()=>{de();fR=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=n[o.expected]??o.expected,a=Se(o.input),s=n[a]??a;return`Invalid input: expected ${i}, received ${s}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${ye(o.values[0])}`:`Invalid option: expected one of ${ge(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",a=t(o.origin);return a?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",a=t(o.origin);return a?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${a.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${ge(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}}});var lS=q(()=>{de()});var dS=q(()=>{de()});var pS=q(()=>{de()});var mS=q(()=>{de()});var fS=q(()=>{de()});var hS=q(()=>{de()});var gS=q(()=>{de()});var yS=q(()=>{de()});var vS=q(()=>{de()});var _S=q(()=>{de()});var SS=q(()=>{de()});var bS=q(()=>{de()});var $S=q(()=>{de()});var wS=q(()=>{de()});var dm=q(()=>{de()});var zS=q(()=>{dm()});var kS=q(()=>{de()});var ES=q(()=>{de()});var RS=q(()=>{de()});var xS=q(()=>{de()});var IS=q(()=>{de()});var PS=q(()=>{de()});var TS=q(()=>{de()});var CS=q(()=>{de()});var AS=q(()=>{de()});var OS=q(()=>{de()});var NS=q(()=>{de()});var jS=q(()=>{de()});var US=q(()=>{de()});var MS=q(()=>{de()});var DS=q(()=>{de()});var qS=q(()=>{de()});var pm=q(()=>{de()});var LS=q(()=>{pm()});var VS=q(()=>{de()});var KS=q(()=>{de()});var JS=q(()=>{de()});var FS=q(()=>{de()});var HS=q(()=>{de()});var ZS=q(()=>{de()});var mm=q(()=>{rS();nS();oS();iS();aS();sS();cS();uS();lm();lS();dS();pS();mS();fS();hS();gS();yS();vS();_S();SS();bS();$S();wS();zS();dm();kS();ES();RS();xS();IS();PS();TS();CS();AS();OS();NS();jS();US();MS();DS();qS();LS();pm();VS();KS();JS();FS();HS();ZS()});function GS(){return new fm}var BS,fm,xt,sa=q(()=>{fm=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};(BS=globalThis).__zod_globalRegistry??(BS.__zod_globalRegistry=GS());xt=globalThis.__zod_globalRegistry});function XS(e,t){return new e({type:"string",...X(t)})}function YS(e,t){return new e({type:"string",coerce:!0,...X(t)})}function hm(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...X(t)})}function Ec(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...X(t)})}function gm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...X(t)})}function ym(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(t)})}function vm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(t)})}function _m(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(t)})}function Rc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...X(t)})}function Sm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...X(t)})}function bm(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(t)})}function $m(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...X(t)})}function wm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(t)})}function zm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...X(t)})}function km(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...X(t)})}function Em(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(t)})}function Rm(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(t)})}function xm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(t)})}function QS(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...X(t)})}function Im(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(t)})}function Pm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(t)})}function Tm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...X(t)})}function Cm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...X(t)})}function Am(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...X(t)})}function Om(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...X(t)})}function eb(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(t)})}function tb(e,t){return new e({type:"string",format:"date",check:"string_format",...X(t)})}function rb(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...X(t)})}function nb(e,t){return new e({type:"string",format:"duration",check:"string_format",...X(t)})}function ob(e,t){return new e({type:"number",checks:[],...X(t)})}function ib(e,t){return new e({type:"number",coerce:!0,checks:[],...X(t)})}function ab(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...X(t)})}function sb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...X(t)})}function cb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...X(t)})}function ub(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...X(t)})}function lb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...X(t)})}function db(e,t){return new e({type:"boolean",...X(t)})}function pb(e,t){return new e({type:"boolean",coerce:!0,...X(t)})}function mb(e,t){return new e({type:"bigint",...X(t)})}function fb(e,t){return new e({type:"bigint",coerce:!0,...X(t)})}function hb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...X(t)})}function gb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...X(t)})}function yb(e,t){return new e({type:"symbol",...X(t)})}function vb(e,t){return new e({type:"undefined",...X(t)})}function _b(e,t){return new e({type:"null",...X(t)})}function Sb(e){return new e({type:"any"})}function bb(e){return new e({type:"unknown"})}function $b(e,t){return new e({type:"never",...X(t)})}function wb(e,t){return new e({type:"void",...X(t)})}function zb(e,t){return new e({type:"date",...X(t)})}function kb(e,t){return new e({type:"date",coerce:!0,...X(t)})}function Eb(e,t){return new e({type:"nan",...X(t)})}function Jr(e,t){return new Qp({check:"less_than",...X(t),value:e,inclusive:!1})}function Wt(e,t){return new Qp({check:"less_than",...X(t),value:e,inclusive:!0})}function Fr(e,t){return new em({check:"greater_than",...X(t),value:e,inclusive:!1})}function Nt(e,t){return new em({check:"greater_than",...X(t),value:e,inclusive:!0})}function Rb(e){return Fr(0,e)}function xb(e){return Jr(0,e)}function Ib(e){return Wt(0,e)}function Pb(e){return Nt(0,e)}function $o(e,t){return new fv({check:"multiple_of",...X(t),value:e})}function wo(e,t){return new yv({check:"max_size",...X(t),maximum:e})}function Hr(e,t){return new vv({check:"min_size",...X(t),minimum:e})}function ca(e,t){return new _v({check:"size_equals",...X(t),size:e})}function ua(e,t){return new Sv({check:"max_length",...X(t),maximum:e})}function In(e,t){return new bv({check:"min_length",...X(t),minimum:e})}function la(e,t){return new $v({check:"length_equals",...X(t),length:e})}function xc(e,t){return new wv({check:"string_format",format:"regex",...X(t),pattern:e})}function Ic(e){return new zv({check:"string_format",format:"lowercase",...X(e)})}function Pc(e){return new kv({check:"string_format",format:"uppercase",...X(e)})}function Tc(e,t){return new Ev({check:"string_format",format:"includes",...X(t),includes:e})}function Cc(e,t){return new Rv({check:"string_format",format:"starts_with",...X(t),prefix:e})}function Ac(e,t){return new xv({check:"string_format",format:"ends_with",...X(t),suffix:e})}function Tb(e,t,r){return new Iv({check:"property",property:e,schema:t,...X(r)})}function Oc(e,t){return new Pv({check:"mime_type",mime:e,...X(t)})}function br(e){return new Tv({check:"overwrite",tx:e})}function Nc(e){return br(t=>t.normalize(e))}function jc(){return br(e=>e.trim())}function Uc(){return br(e=>e.toLowerCase())}function Mc(){return br(e=>e.toUpperCase())}function Dc(){return br(e=>mp(e))}function Cb(e,t,r){return new e({type:"array",element:t,...X(r)})}function Ab(e,t){return new e({type:"file",...X(t)})}function Ob(e,t,r){let n=X(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Nb(e,t,r){return new e({type:"custom",check:"custom",fn:t,...X(r)})}function jb(e){let t=vR(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(So(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(So(o))}},e(r.value,r)));return t}function vR(e,t){let r=new Je({check:"custom",...X(t)});return r._zod.check=e,r}function Ub(e){let t=new Je({check:"describe"});return t._zod.onattach=[r=>{let n=xt.get(r)??{};xt.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function Mb(e){let t=new Je({check:"meta"});return t._zod.onattach=[r=>{let n=xt.get(r)??{};xt.add(r,{...n,...e})}],t._zod.check=()=>{},t}function Db(e,t){let r=X(t),n=r.truthy??["true","1","yes","on","y","enabled"],o=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(v=>typeof v=="string"?v.toLowerCase():v),o=o.map(v=>typeof v=="string"?v.toLowerCase():v));let i=new Set(n),a=new Set(o),s=e.Codec??kc,c=e.Boolean??wc,u=e.String??bo,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),m=new s({type:"pipe",in:l,out:d,transform:((v,g)=>{let h=v;return r.case!=="sensitive"&&(h=h.toLowerCase()),i.has(h)?!0:a.has(h)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((v,g)=>v===!0?n[0]||"true":o[0]||"false"),error:r.error});return m}function da(e,t,r,n={}){let o=X(n),i={...X(n),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:s=>r.test(s),...o};return r instanceof RegExp&&(i.pattern=r),new e(i)}var qb=q(()=>{gc();sa();cm();de()});function zo(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??xt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Le(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,l);else{let m=a.schema,v=t.processors[o.type];if(!v)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);v(e,t,m,l)}let d=e._zod.parent;d&&(a.ref||(a.ref=d),Le(d,t,l),t.seen.get(d).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),t.io==="input"&&$t(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function ko(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let a of e.seen.entries()){let s=e.metadataRegistry.get(a[0])?.id;if(s){let c=n.get(s);if(c&&c!==a[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,a[0])}}let o=a=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(a[0])?.id,m=e.external.uri??(g=>g);if(d)return{ref:m(d)};let v=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=v,{defId:v,ref:`${m("__shared")}#/${s}/${v}`}}if(a[1]===r)return{ref:"#"};let u=`#/${s}/`,l=a[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+l}},i=a=>{if(a[1].schema.$ref)return;let s=a[1],{ref:c,defId:u}=o(a);s.def={...s.schema},u&&(s.defId=u);let l=s.schema;for(let d in l)delete l[d];l.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let u=e.external.registry.get(a[0])?.id;if(t!==a[0]&&u){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}if(s.count>1&&e.reused==="ref"){i(a);continue}}}function Eo(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let s=e.seen.get(a);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.ref=null,l){n(l);let m=e.seen.get(l),v=m.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(v)):Object.assign(c,v),Object.assign(c,u),a._zod.parent===l)for(let h in c)h==="$ref"||h==="allOf"||h in u||delete c[h];if(v.$ref&&m.def)for(let h in c)h==="$ref"||h==="allOf"||h in m.def&&JSON.stringify(c[h])===JSON.stringify(m.def[h])&&delete c[h]}let d=a._zod.parent;if(d&&d!==l){n(d);let m=e.seen.get(d);if(m?.schema.$ref&&(c.$ref=m.schema.$ref,m.def))for(let v in c)v==="$ref"||v==="allOf"||v in m.def&&JSON.stringify(c[v])===JSON.stringify(m.def[v])&&delete c[v]}e.override({zodSchema:a,jsonSchema:c,path:s.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.external?.defs??{};for(let a of e.seen.entries()){let s=a[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:pa(t,"input",e.processors),output:pa(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function $t(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return $t(n.element,r);if(n.type==="set")return $t(n.valueType,r);if(n.type==="lazy")return $t(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return $t(n.innerType,r);if(n.type==="intersection")return $t(n.left,r)||$t(n.right,r);if(n.type==="record"||n.type==="map")return $t(n.keyType,r)||$t(n.valueType,r);if(n.type==="pipe")return $t(n.in,r)||$t(n.out,r);if(n.type==="object"){for(let o in n.shape)if($t(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if($t(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if($t(o,r))return!0;return!!(n.rest&&$t(n.rest,r))}return!1}var Lb,pa,ma=q(()=>{sa();Lb=(e,t={})=>r=>{let n=zo({...r,processors:t});return Le(e,n),ko(n,e),Eo(n,e)},pa=(e,t,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},a=zo({...o??{},target:i,io:t,processors:r});return Le(e,a),ko(a,e),Eo(a,e)}});function fa(e,t){if("_idmap"in e){let n=e,o=zo({...t,processors:Nm}),i={};for(let c of n._idmap.entries()){let[u,l]=c;Le(l,o)}let a={},s={registry:n,uri:t?.uri,defs:i};o.external=s;for(let c of n._idmap.entries()){let[u,l]=c;ko(o,l),a[u]=Eo(o,l)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:i}}return{schemas:a}}let r=zo({...t,processors:Nm});return Le(e,r),ko(r,e),Eo(r,e)}var _R,jm,Um,Mm,Dm,qm,Lm,Vm,Km,Jm,Fm,Hm,Zm,Wm,Bm,Gm,Xm,Ym,Qm,ef,tf,rf,nf,of,af,sf,qc,cf,uf,lf,df,pf,mf,ff,hf,gf,yf,vf,Lc,_f,Nm,ha=q(()=>{ma();de();_R={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},jm=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:a,format:s,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof a=="number"&&(o.maxLength=a),s&&(o.format=_R[s]??s,o.format===""&&delete o.format,s==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Um=(e,t,r,n)=>{let o=r,{minimum:i,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof s=="string"&&s.includes("int")?o.type="integer":o.type="number",typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l),typeof i=="number"&&(o.minimum=i,typeof l=="number"&&t.target!=="draft-04"&&(l>=i?delete o.minimum:delete o.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u),typeof a=="number"&&(o.maximum=a,typeof u=="number"&&t.target!=="draft-04"&&(u<=a?delete o.maximum:delete o.exclusiveMaximum)),typeof c=="number"&&(o.multipleOf=c)},Mm=(e,t,r,n)=>{r.type="boolean"},Dm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},qm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Lm=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Vm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Km=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Jm=(e,t,r,n)=>{r.not={}},Fm=(e,t,r,n)=>{},Hm=(e,t,r,n)=>{},Zm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Wm=(e,t,r,n)=>{let o=e._zod.def,i=Wi(o.entries);i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Bm=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let a of o.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Gm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Xm=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Ym=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=e._zod.bag;a!==void 0&&(i.minLength=a),s!==void 0&&(i.maxLength=s),c?c.length===1?(i.contentMediaType=c[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(o,i)},Qm=(e,t,r,n)=>{r.type="boolean"},ef=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},tf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},rf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},nf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},of=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},af=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;typeof a=="number"&&(o.minItems=a),typeof s=="number"&&(o.maxItems=s),o.type="array",o.items=Le(i.element,t,{...n,path:[...n.path,"items"]})},sf=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let a=i.shape;for(let u in a)o.properties[u]=Le(a[u],t,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(u=>{let l=i.shape[u]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Le(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},qc=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,a=o.options.map((s,c)=>Le(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=a:r.anyOf=a},cf=(e,t,r,n)=>{let o=e._zod.def,i=Le(o.left,t,{...n,path:[...n.path,"allOf",0]}),a=Le(o.right,t,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=c},uf=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,v)=>Le(m,t,{...n,path:[...n.path,a,v]})),u=i.rest?Le(i.rest,t,{...n,path:[...n.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=c,u&&(o.items=u)):t.target==="openapi-3.0"?(o.items={anyOf:c},u&&o.items.anyOf.push(u),o.minItems=c.length,u||(o.maxItems=c.length)):(o.items=c,u&&(o.additionalItems=u));let{minimum:l,maximum:d}=e._zod.bag;typeof l=="number"&&(o.minItems=l),typeof d=="number"&&(o.maxItems=d)},lf=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let a=i.keyType,c=a._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let l=Le(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=Le(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=Le(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let u=a._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},df=(e,t,r,n)=>{let o=e._zod.def,i=Le(o.innerType,t,n),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},pf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},mf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},ff=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},hf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},gf=(e,t,r,n)=>{let o=e._zod.def,i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Le(i,t,n);let a=t.seen.get(e);a.ref=i},yf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},vf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Lc=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},_f=(e,t,r,n)=>{let o=e._zod.innerType;Le(o,t,n);let i=t.seen.get(e);i.ref=o},Nm={string:jm,number:Um,boolean:Mm,bigint:Dm,symbol:qm,null:Lm,undefined:Vm,void:Km,never:Jm,any:Fm,unknown:Hm,date:Zm,enum:Wm,literal:Bm,nan:Gm,template_literal:Xm,file:Ym,success:Qm,custom:ef,function:tf,transform:rf,map:nf,set:of,array:af,object:sf,union:qc,intersection:cf,tuple:uf,record:lf,nullable:df,nonoptional:pf,default:mf,prefault:ff,catch:hf,pipe:gf,readonly:yf,promise:vf,optional:Lc,lazy:_f}});var Vb=q(()=>{ha();ma()});var Kb=q(()=>{});var It=q(()=>{yo();zp();bp();cm();gc();rm();de();hc();mm();sa();tm();qb();ma();ha();Vb();Kb()});var Vc={};nr(Vc,{endsWith:()=>Ac,gt:()=>Fr,gte:()=>Nt,includes:()=>Tc,length:()=>la,lowercase:()=>Ic,lt:()=>Jr,lte:()=>Wt,maxLength:()=>ua,maxSize:()=>wo,mime:()=>Oc,minLength:()=>In,minSize:()=>Hr,multipleOf:()=>$o,negative:()=>xb,nonnegative:()=>Pb,nonpositive:()=>Ib,normalize:()=>Nc,overwrite:()=>br,positive:()=>Rb,property:()=>Tb,regex:()=>xc,size:()=>ca,slugify:()=>Dc,startsWith:()=>Cc,toLowerCase:()=>Uc,toUpperCase:()=>Mc,trim:()=>jc,uppercase:()=>Pc});var Kc=q(()=>{It()});var Lt={};nr(Lt,{ZodISODate:()=>$f,ZodISODateTime:()=>Sf,ZodISODuration:()=>Ef,ZodISOTime:()=>zf,date:()=>wf,datetime:()=>bf,duration:()=>Rf,time:()=>kf});function bf(e){return eb(Sf,e)}function wf(e){return tb($f,e)}function kf(e){return rb(zf,e)}function Rf(e){return nb(Ef,e)}var Sf,$f,zf,Ef,ga=q(()=>{It();va();Sf=C("ZodISODateTime",(e,t)=>{r_.init(e,t),Ke.init(e,t)});$f=C("ZodISODate",(e,t)=>{n_.init(e,t),Ke.init(e,t)});zf=C("ZodISOTime",(e,t)=>{o_.init(e,t),Ke.init(e,t)});Ef=C("ZodISODuration",(e,t)=>{i_.init(e,t),Ke.init(e,t)})});var Jb,SM,jt,xf=q(()=>{It();It();de();Jb=(e,t)=>{pc.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Sp(e,r)},flatten:{value:r=>_p(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,vo,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,vo,2)}},isEmpty:{get(){return e.issues.length===0}}})},SM=C("ZodError",Jb),jt=C("ZodError",Jb,{Parent:Error})});var Fb,Hb,Jc,Zb,Wb,Bb,Gb,Xb,Yb,Qb,e$,t$,If=q(()=>{It();xf();Fb=ea(jt),Hb=ta(jt),Jc=ra(jt),Zb=na(jt),Wb=tv(jt),Bb=rv(jt),Gb=nv(jt),Xb=ov(jt),Yb=iv(jt),Qb=av(jt),e$=sv(jt),t$=cv(jt)});var ya={};nr(ya,{ZodAny:()=>a$,ZodArray:()=>l$,ZodBase64:()=>Ff,ZodBase64URL:()=>Hf,ZodBigInt:()=>ka,ZodBigIntFormat:()=>Bf,ZodBoolean:()=>za,ZodCIDRv4:()=>Kf,ZodCIDRv6:()=>Jf,ZodCUID:()=>jf,ZodCUID2:()=>Uf,ZodCatch:()=>P$,ZodCodec:()=>rh,ZodCustom:()=>Qc,ZodCustomStringFormat:()=>$a,ZodDate:()=>Bc,ZodDefault:()=>z$,ZodDiscriminatedUnion:()=>p$,ZodE164:()=>Zf,ZodEmail:()=>Cf,ZodEmoji:()=>Of,ZodEnum:()=>_a,ZodExactOptional:()=>b$,ZodFile:()=>_$,ZodFunction:()=>M$,ZodGUID:()=>Fc,ZodIPv4:()=>Lf,ZodIPv6:()=>Vf,ZodIntersection:()=>m$,ZodJWT:()=>Wf,ZodKSUID:()=>qf,ZodLazy:()=>j$,ZodLiteral:()=>v$,ZodMAC:()=>r$,ZodMap:()=>g$,ZodNaN:()=>C$,ZodNanoID:()=>Nf,ZodNever:()=>c$,ZodNonOptional:()=>eh,ZodNull:()=>i$,ZodNullable:()=>w$,ZodNumber:()=>wa,ZodNumberFormat:()=>Ro,ZodObject:()=>Gc,ZodOptional:()=>Qf,ZodPipe:()=>th,ZodPrefault:()=>E$,ZodPromise:()=>U$,ZodReadonly:()=>A$,ZodRecord:()=>Yc,ZodSet:()=>y$,ZodString:()=>Sa,ZodStringFormat:()=>Ke,ZodSuccess:()=>I$,ZodSymbol:()=>n$,ZodTemplateLiteral:()=>N$,ZodTransform:()=>S$,ZodTuple:()=>f$,ZodType:()=>xe,ZodULID:()=>Mf,ZodURL:()=>Wc,ZodUUID:()=>$r,ZodUndefined:()=>o$,ZodUnion:()=>Xc,ZodUnknown:()=>s$,ZodVoid:()=>u$,ZodXID:()=>Df,ZodXor:()=>d$,_ZodString:()=>Tf,_default:()=>k$,_function:()=>Sx,any:()=>Gf,array:()=>N,base64:()=>qR,base64url:()=>LR,bigint:()=>YR,boolean:()=>ee,catch:()=>T$,check:()=>bx,cidrv4:()=>MR,cidrv6:()=>DR,codec:()=>yx,cuid:()=>PR,cuid2:()=>TR,custom:()=>$x,date:()=>ox,describe:()=>wx,discriminatedUnion:()=>Tn,e164:()=>VR,email:()=>Af,emoji:()=>xR,enum:()=>ve,exactOptional:()=>$$,file:()=>mx,float32:()=>WR,float64:()=>BR,function:()=>Sx,guid:()=>$R,hash:()=>ZR,hex:()=>HR,hostname:()=>FR,httpUrl:()=>RR,instanceof:()=>kx,int:()=>Pf,int32:()=>GR,int64:()=>QR,intersection:()=>sr,ipv4:()=>NR,ipv6:()=>UR,json:()=>Rx,jwt:()=>KR,keyof:()=>ix,ksuid:()=>OR,lazy:()=>Cn,literal:()=>U,looseObject:()=>pe,looseRecord:()=>ux,mac:()=>jR,map:()=>lx,meta:()=>zx,nan:()=>gx,nanoid:()=>IR,nativeEnum:()=>px,never:()=>Xf,nonoptional:()=>x$,null:()=>wr,nullable:()=>Hc,nullish:()=>fx,number:()=>F,object:()=>x,optional:()=>le,partialRecord:()=>cx,pipe:()=>Zc,prefault:()=>R$,preprocess:()=>Zr,promise:()=>_x,readonly:()=>O$,record:()=>Y,refine:()=>D$,set:()=>dx,strictObject:()=>ax,string:()=>p,stringFormat:()=>JR,stringbool:()=>Ex,success:()=>hx,superRefine:()=>q$,symbol:()=>tx,templateLiteral:()=>vx,transform:()=>Yf,tuple:()=>h$,uint32:()=>XR,uint64:()=>ex,ulid:()=>CR,undefined:()=>rx,union:()=>re,unknown:()=>ue,url:()=>ba,uuid:()=>wR,uuidv4:()=>zR,uuidv6:()=>kR,uuidv7:()=>ER,void:()=>nx,xid:()=>AR,xor:()=>sx});function p(e){return XS(Sa,e)}function Af(e){return hm(Cf,e)}function $R(e){return Ec(Fc,e)}function wR(e){return gm($r,e)}function zR(e){return ym($r,e)}function kR(e){return vm($r,e)}function ER(e){return _m($r,e)}function ba(e){return Rc(Wc,e)}function RR(e){return Rc(Wc,{protocol:/^https?$/,hostname:ar.domain,...G.normalizeParams(e)})}function xR(e){return Sm(Of,e)}function IR(e){return bm(Nf,e)}function PR(e){return $m(jf,e)}function TR(e){return wm(Uf,e)}function CR(e){return zm(Mf,e)}function AR(e){return km(Df,e)}function OR(e){return Em(qf,e)}function NR(e){return Rm(Lf,e)}function jR(e){return QS(r$,e)}function UR(e){return xm(Vf,e)}function MR(e){return Im(Kf,e)}function DR(e){return Pm(Jf,e)}function qR(e){return Tm(Ff,e)}function LR(e){return Cm(Hf,e)}function VR(e){return Am(Zf,e)}function KR(e){return Om(Wf,e)}function JR(e,t,r={}){return da($a,e,t,r)}function FR(e){return da($a,"hostname",ar.hostname,e)}function HR(e){return da($a,"hex",ar.hex,e)}function ZR(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,o=ar[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return da($a,n,o,t)}function F(e){return ob(wa,e)}function Pf(e){return ab(Ro,e)}function WR(e){return sb(Ro,e)}function BR(e){return cb(Ro,e)}function GR(e){return ub(Ro,e)}function XR(e){return lb(Ro,e)}function ee(e){return db(za,e)}function YR(e){return mb(ka,e)}function QR(e){return hb(Bf,e)}function ex(e){return gb(Bf,e)}function tx(e){return yb(n$,e)}function rx(e){return vb(o$,e)}function wr(e){return _b(i$,e)}function Gf(){return Sb(a$)}function ue(){return bb(s$)}function Xf(e){return $b(c$,e)}function nx(e){return wb(u$,e)}function ox(e){return zb(Bc,e)}function N(e,t){return Cb(l$,e,t)}function ix(e){let t=e._zod.def.shape;return ve(Object.keys(t))}function x(e,t){let r={type:"object",shape:e??{},...G.normalizeParams(t)};return new Gc(r)}function ax(e,t){return new Gc({type:"object",shape:e,catchall:Xf(),...G.normalizeParams(t)})}function pe(e,t){return new Gc({type:"object",shape:e,catchall:ue(),...G.normalizeParams(t)})}function re(e,t){return new Xc({type:"union",options:e,...G.normalizeParams(t)})}function sx(e,t){return new d$({type:"union",options:e,inclusive:!1,...G.normalizeParams(t)})}function Tn(e,t,r){return new p$({type:"union",options:t,discriminator:e,...G.normalizeParams(r)})}function sr(e,t){return new m$({type:"intersection",left:e,right:t})}function h$(e,t,r){let n=t instanceof we,o=n?r:t,i=n?t:null;return new f$({type:"tuple",items:e,rest:i,...G.normalizeParams(o)})}function Y(e,t,r){return new Yc({type:"record",keyType:e,valueType:t,...G.normalizeParams(r)})}function cx(e,t,r){let n=At(e);return n._zod.values=void 0,new Yc({type:"record",keyType:n,valueType:t,...G.normalizeParams(r)})}function ux(e,t,r){return new Yc({type:"record",keyType:e,valueType:t,mode:"loose",...G.normalizeParams(r)})}function lx(e,t,r){return new g$({type:"map",keyType:e,valueType:t,...G.normalizeParams(r)})}function dx(e,t){return new y$({type:"set",valueType:e,...G.normalizeParams(t)})}function ve(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new _a({type:"enum",entries:r,...G.normalizeParams(t)})}function px(e,t){return new _a({type:"enum",entries:e,...G.normalizeParams(t)})}function U(e,t){return new v$({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}function mx(e){return Ab(_$,e)}function Yf(e){return new S$({type:"transform",transform:e})}function le(e){return new Qf({type:"optional",innerType:e})}function $$(e){return new b$({type:"optional",innerType:e})}function Hc(e){return new w$({type:"nullable",innerType:e})}function fx(e){return le(Hc(e))}function k$(e,t){return new z$({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():G.shallowClone(t)}})}function R$(e,t){return new E$({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():G.shallowClone(t)}})}function x$(e,t){return new eh({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}function hx(e){return new I$({type:"success",innerType:e})}function T$(e,t){return new P$({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function gx(e){return Eb(C$,e)}function Zc(e,t){return new th({type:"pipe",in:e,out:t})}function yx(e,t,r){return new rh({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function O$(e){return new A$({type:"readonly",innerType:e})}function vx(e,t){return new N$({type:"template_literal",parts:e,...G.normalizeParams(t)})}function Cn(e){return new j$({type:"lazy",getter:e})}function _x(e){return new U$({type:"promise",innerType:e})}function Sx(e){return new M$({type:"function",input:Array.isArray(e?.input)?h$(e?.input):e?.input??N(ue()),output:e?.output??ue()})}function bx(e){let t=new Je({check:"custom"});return t._zod.check=e,t}function $x(e,t){return Ob(Qc,e??(()=>!0),t)}function D$(e,t={}){return Nb(Qc,e,t)}function q$(e){return jb(e)}function kx(e,t={}){let r=new Qc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...G.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function Rx(e){let t=Cn(()=>re([p(e),F(),ee(),wr(),N(t),Y(p(),t)]));return t}function Zr(e,t){return Zc(Yf(e),t)}var xe,Tf,Sa,Ke,Cf,Fc,$r,Wc,Of,Nf,jf,Uf,Mf,Df,qf,Lf,r$,Vf,Kf,Jf,Ff,Hf,Zf,Wf,$a,wa,Ro,za,ka,Bf,n$,o$,i$,a$,s$,c$,u$,Bc,l$,Gc,Xc,d$,p$,m$,f$,Yc,g$,y$,_a,v$,_$,S$,Qf,b$,w$,z$,E$,eh,I$,P$,C$,th,rh,A$,N$,j$,U$,M$,Qc,wx,zx,Ex,va=q(()=>{It();It();ha();ma();Kc();ga();If();xe=C("ZodType",(e,t)=>(we.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:pa(e,"input"),output:pa(e,"output")}}),e.toJSONSchema=Lb(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(G.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(r,n)=>At(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Fb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Jc(e,r,n),e.parseAsync=async(r,n)=>Hb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Zb(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Wb(e,r,n),e.decode=(r,n)=>Bb(e,r,n),e.encodeAsync=async(r,n)=>Gb(e,r,n),e.decodeAsync=async(r,n)=>Xb(e,r,n),e.safeEncode=(r,n)=>Yb(e,r,n),e.safeDecode=(r,n)=>Qb(e,r,n),e.safeEncodeAsync=async(r,n)=>e$(e,r,n),e.safeDecodeAsync=async(r,n)=>t$(e,r,n),e.refine=(r,n)=>e.check(D$(r,n)),e.superRefine=r=>e.check(q$(r)),e.overwrite=r=>e.check(br(r)),e.optional=()=>le(e),e.exactOptional=()=>$$(e),e.nullable=()=>Hc(e),e.nullish=()=>le(Hc(e)),e.nonoptional=r=>x$(e,r),e.array=()=>N(e),e.or=r=>re([e,r]),e.and=r=>sr(e,r),e.transform=r=>Zc(e,Yf(r)),e.default=r=>k$(e,r),e.prefault=r=>R$(e,r),e.catch=r=>T$(e,r),e.pipe=r=>Zc(e,r),e.readonly=()=>O$(e),e.describe=r=>{let n=e.clone();return xt.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return xt.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return xt.get(e);let n=e.clone();return xt.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Tf=C("_ZodString",(e,t)=>{bo.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>jm(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(xc(...n)),e.includes=(...n)=>e.check(Tc(...n)),e.startsWith=(...n)=>e.check(Cc(...n)),e.endsWith=(...n)=>e.check(Ac(...n)),e.min=(...n)=>e.check(In(...n)),e.max=(...n)=>e.check(ua(...n)),e.length=(...n)=>e.check(la(...n)),e.nonempty=(...n)=>e.check(In(1,...n)),e.lowercase=n=>e.check(Ic(n)),e.uppercase=n=>e.check(Pc(n)),e.trim=()=>e.check(jc()),e.normalize=(...n)=>e.check(Nc(...n)),e.toLowerCase=()=>e.check(Uc()),e.toUpperCase=()=>e.check(Mc()),e.slugify=()=>e.check(Dc())}),Sa=C("ZodString",(e,t)=>{bo.init(e,t),Tf.init(e,t),e.email=r=>e.check(hm(Cf,r)),e.url=r=>e.check(Rc(Wc,r)),e.jwt=r=>e.check(Om(Wf,r)),e.emoji=r=>e.check(Sm(Of,r)),e.guid=r=>e.check(Ec(Fc,r)),e.uuid=r=>e.check(gm($r,r)),e.uuidv4=r=>e.check(ym($r,r)),e.uuidv6=r=>e.check(vm($r,r)),e.uuidv7=r=>e.check(_m($r,r)),e.nanoid=r=>e.check(bm(Nf,r)),e.guid=r=>e.check(Ec(Fc,r)),e.cuid=r=>e.check($m(jf,r)),e.cuid2=r=>e.check(wm(Uf,r)),e.ulid=r=>e.check(zm(Mf,r)),e.base64=r=>e.check(Tm(Ff,r)),e.base64url=r=>e.check(Cm(Hf,r)),e.xid=r=>e.check(km(Df,r)),e.ksuid=r=>e.check(Em(qf,r)),e.ipv4=r=>e.check(Rm(Lf,r)),e.ipv6=r=>e.check(xm(Vf,r)),e.cidrv4=r=>e.check(Im(Kf,r)),e.cidrv6=r=>e.check(Pm(Jf,r)),e.e164=r=>e.check(Am(Zf,r)),e.datetime=r=>e.check(bf(r)),e.date=r=>e.check(wf(r)),e.time=r=>e.check(kf(r)),e.duration=r=>e.check(Rf(r))});Ke=C("ZodStringFormat",(e,t)=>{Ve.init(e,t),Tf.init(e,t)}),Cf=C("ZodEmail",(e,t)=>{Zv.init(e,t),Ke.init(e,t)});Fc=C("ZodGUID",(e,t)=>{Fv.init(e,t),Ke.init(e,t)});$r=C("ZodUUID",(e,t)=>{Hv.init(e,t),Ke.init(e,t)});Wc=C("ZodURL",(e,t)=>{Wv.init(e,t),Ke.init(e,t)});Of=C("ZodEmoji",(e,t)=>{Bv.init(e,t),Ke.init(e,t)});Nf=C("ZodNanoID",(e,t)=>{Gv.init(e,t),Ke.init(e,t)});jf=C("ZodCUID",(e,t)=>{Xv.init(e,t),Ke.init(e,t)});Uf=C("ZodCUID2",(e,t)=>{Yv.init(e,t),Ke.init(e,t)});Mf=C("ZodULID",(e,t)=>{Qv.init(e,t),Ke.init(e,t)});Df=C("ZodXID",(e,t)=>{e_.init(e,t),Ke.init(e,t)});qf=C("ZodKSUID",(e,t)=>{t_.init(e,t),Ke.init(e,t)});Lf=C("ZodIPv4",(e,t)=>{a_.init(e,t),Ke.init(e,t)});r$=C("ZodMAC",(e,t)=>{c_.init(e,t),Ke.init(e,t)});Vf=C("ZodIPv6",(e,t)=>{s_.init(e,t),Ke.init(e,t)});Kf=C("ZodCIDRv4",(e,t)=>{u_.init(e,t),Ke.init(e,t)});Jf=C("ZodCIDRv6",(e,t)=>{l_.init(e,t),Ke.init(e,t)});Ff=C("ZodBase64",(e,t)=>{p_.init(e,t),Ke.init(e,t)});Hf=C("ZodBase64URL",(e,t)=>{m_.init(e,t),Ke.init(e,t)});Zf=C("ZodE164",(e,t)=>{f_.init(e,t),Ke.init(e,t)});Wf=C("ZodJWT",(e,t)=>{h_.init(e,t),Ke.init(e,t)});$a=C("ZodCustomStringFormat",(e,t)=>{g_.init(e,t),Ke.init(e,t)});wa=C("ZodNumber",(e,t)=>{om.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Um(e,n,o,i),e.gt=(n,o)=>e.check(Fr(n,o)),e.gte=(n,o)=>e.check(Nt(n,o)),e.min=(n,o)=>e.check(Nt(n,o)),e.lt=(n,o)=>e.check(Jr(n,o)),e.lte=(n,o)=>e.check(Wt(n,o)),e.max=(n,o)=>e.check(Wt(n,o)),e.int=n=>e.check(Pf(n)),e.safe=n=>e.check(Pf(n)),e.positive=n=>e.check(Fr(0,n)),e.nonnegative=n=>e.check(Nt(0,n)),e.negative=n=>e.check(Jr(0,n)),e.nonpositive=n=>e.check(Wt(0,n)),e.multipleOf=(n,o)=>e.check($o(n,o)),e.step=(n,o)=>e.check($o(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});Ro=C("ZodNumberFormat",(e,t)=>{y_.init(e,t),wa.init(e,t)});za=C("ZodBoolean",(e,t)=>{wc.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mm(e,r,n,o)});ka=C("ZodBigInt",(e,t)=>{im.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Dm(e,n,o,i),e.gte=(n,o)=>e.check(Nt(n,o)),e.min=(n,o)=>e.check(Nt(n,o)),e.gt=(n,o)=>e.check(Fr(n,o)),e.gte=(n,o)=>e.check(Nt(n,o)),e.min=(n,o)=>e.check(Nt(n,o)),e.lt=(n,o)=>e.check(Jr(n,o)),e.lte=(n,o)=>e.check(Wt(n,o)),e.max=(n,o)=>e.check(Wt(n,o)),e.positive=n=>e.check(Fr(BigInt(0),n)),e.negative=n=>e.check(Jr(BigInt(0),n)),e.nonpositive=n=>e.check(Wt(BigInt(0),n)),e.nonnegative=n=>e.check(Nt(BigInt(0),n)),e.multipleOf=(n,o)=>e.check($o(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});Bf=C("ZodBigIntFormat",(e,t)=>{v_.init(e,t),ka.init(e,t)});n$=C("ZodSymbol",(e,t)=>{__.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qm(e,r,n,o)});o$=C("ZodUndefined",(e,t)=>{S_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vm(e,r,n,o)});i$=C("ZodNull",(e,t)=>{b_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lm(e,r,n,o)});a$=C("ZodAny",(e,t)=>{$_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Fm(e,r,n,o)});s$=C("ZodUnknown",(e,t)=>{w_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hm(e,r,n,o)});c$=C("ZodNever",(e,t)=>{z_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jm(e,r,n,o)});u$=C("ZodVoid",(e,t)=>{k_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Km(e,r,n,o)});Bc=C("ZodDate",(e,t)=>{E_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Zm(e,n,o,i),e.min=(n,o)=>e.check(Nt(n,o)),e.max=(n,o)=>e.check(Wt(n,o));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});l$=C("ZodArray",(e,t)=>{R_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>af(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(In(r,n)),e.nonempty=r=>e.check(In(1,r)),e.max=(r,n)=>e.check(ua(r,n)),e.length=(r,n)=>e.check(la(r,n)),e.unwrap=()=>e.element});Gc=C("ZodObject",(e,t)=>{P_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sf(e,r,n,o),G.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ve(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ue()}),e.loose=()=>e.clone({...e._zod.def,catchall:ue()}),e.strict=()=>e.clone({...e._zod.def,catchall:Xf()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>G.extend(e,r),e.safeExtend=r=>G.safeExtend(e,r),e.merge=r=>G.merge(e,r),e.pick=r=>G.pick(e,r),e.omit=r=>G.omit(e,r),e.partial=(...r)=>G.partial(Qf,e,r[0]),e.required=(...r)=>G.required(eh,e,r[0])});Xc=C("ZodUnion",(e,t)=>{zc.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qc(e,r,n,o),e.options=t.options});d$=C("ZodXor",(e,t)=>{Xc.init(e,t),T_.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qc(e,r,n,o),e.options=t.options});p$=C("ZodDiscriminatedUnion",(e,t)=>{Xc.init(e,t),C_.init(e,t)});m$=C("ZodIntersection",(e,t)=>{A_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cf(e,r,n,o)});f$=C("ZodTuple",(e,t)=>{am.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>uf(e,r,n,o),e.rest=r=>e.clone({...e._zod.def,rest:r})});Yc=C("ZodRecord",(e,t)=>{O_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lf(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});g$=C("ZodMap",(e,t)=>{N_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nf(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Hr(...r)),e.nonempty=r=>e.check(Hr(1,r)),e.max=(...r)=>e.check(wo(...r)),e.size=(...r)=>e.check(ca(...r))});y$=C("ZodSet",(e,t)=>{j_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>of(e,r,n,o),e.min=(...r)=>e.check(Hr(...r)),e.nonempty=r=>e.check(Hr(1,r)),e.max=(...r)=>e.check(wo(...r)),e.size=(...r)=>e.check(ca(...r))});_a=C("ZodEnum",(e,t)=>{U_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Wm(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new _a({...t,checks:[],...G.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new _a({...t,checks:[],...G.normalizeParams(o),entries:i})}});v$=C("ZodLiteral",(e,t)=>{M_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bm(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});_$=C("ZodFile",(e,t)=>{D_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ym(e,r,n,o),e.min=(r,n)=>e.check(Hr(r,n)),e.max=(r,n)=>e.check(wo(r,n)),e.mime=(r,n)=>e.check(Oc(Array.isArray(r)?r:[r],n))});S$=C("ZodTransform",(e,t)=>{q_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rf(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new En(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(G.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(G.issue(a))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});Qf=C("ZodOptional",(e,t)=>{sm.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});b$=C("ZodExactOptional",(e,t)=>{L_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});w$=C("ZodNullable",(e,t)=>{V_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>df(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});z$=C("ZodDefault",(e,t)=>{K_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});E$=C("ZodPrefault",(e,t)=>{J_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ff(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});eh=C("ZodNonOptional",(e,t)=>{F_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});I$=C("ZodSuccess",(e,t)=>{H_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qm(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});P$=C("ZodCatch",(e,t)=>{Z_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});C$=C("ZodNaN",(e,t)=>{W_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gm(e,r,n,o)});th=C("ZodPipe",(e,t)=>{B_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gf(e,r,n,o),e.in=t.in,e.out=t.out});rh=C("ZodCodec",(e,t)=>{th.init(e,t),kc.init(e,t)});A$=C("ZodReadonly",(e,t)=>{G_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});N$=C("ZodTemplateLiteral",(e,t)=>{X_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xm(e,r,n,o)});j$=C("ZodLazy",(e,t)=>{eS.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_f(e,r,n,o),e.unwrap=()=>e._zod.def.getter()});U$=C("ZodPromise",(e,t)=>{Q_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});M$=C("ZodFunction",(e,t)=>{Y_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tf(e,r,n,o)});Qc=C("ZodCustom",(e,t)=>{tS.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ef(e,r,n,o)});wx=Ub,zx=Mb;Ex=(...e)=>Db({Codec:rh,Boolean:za,String:Sa},...e)});var V$,L$,K$=q(()=>{It();It();V$={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"};L$||(L$={})});var xM,J$=q(()=>{sa();Kc();ga();va();xM={...ya,...Vc,iso:Lt}});var eu={};nr(eu,{bigint:()=>Cx,boolean:()=>Tx,date:()=>Ax,number:()=>Px,string:()=>Ix});function Ix(e){return YS(Sa,e)}function Px(e){return ib(wa,e)}function Tx(e){return pb(za,e)}function Cx(e){return fb(ka,e)}function Ax(e){return kb(Bc,e)}var F$=q(()=>{It();va()});var nh=q(()=>{It();va();Kc();xf();If();K$();It();lm();It();ha();J$();mm();ga();ga();F$();lt(um())});var oh=q(()=>{nh();nh()});var ih=q(()=>{oh();oh()});var Br,tu,Ea,Ra,cr,On,ur,Gr,xo,Nn,ru,nu,ou,Xr,iu,au,su,cu,uu,Wr,Ge,sh,xa,Ia,lu,du,Pa,pt,Yr,Xe,St,bt,Ta,Ye,Qr,Ca,Aa,Io,Po,Bt,pu,Oa,mu,Na,fu,en,zr,To,Nx,jx,hu,gu,yu,vu,ja,Ua,_u,Ma,Su,jn,Da,bu,$u,qa,wu,tn,rn,La,Va,ch,Ka,nn,kr,Ja,zu,ku,Eu,Ru,xu,Co,Iu,Pu,Tu,Cu,Au,Ou,Nu,ju,Fa,Uu,Mu,Du,qu,Lu,Vu,Ku,Ju,Fu,Hu,Zu,Wu,Bu,Gu,Ao,Oo,No,Xu,Yu,Qu,jo,el,tl,rl,nl,ol,Ha,il,al,Uo,uh,sl,cl,ul,Za,Wa,ll,dl,pl,ml,fl,hl,gl,yl,vl,An,_l,Sl,bl,$l,wl,Ba,Mo,Do,Ga,Xa,Ya,zl,Qa,es,kl,El,ts,qo,Rl,xl,Il,Pl,Tl,Cl,Al,Ol,Nl,jl,Ul,Ml,Dl,ql,Ll,lh,Vl,on,dh,Kl,ph,mh,fh,hh,gh,yh,vh,_h,Sh,bh,$h,wh,zh,kh,Eh,dt,rs,Un,Jl,ns,Lo,os,Mn,ah,Fl,Hl,is,Rh,xh,Z$=q(()=>{ih();Br="2025-11-25",tu="2025-03-26",Ea=[Br,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ra="io.modelcontextprotocol/related-task",cr="io.modelcontextprotocol/protocolVersion",On="io.modelcontextprotocol/clientInfo",ur="io.modelcontextprotocol/serverInfo",Gr="io.modelcontextprotocol/clientCapabilities",xo="io.modelcontextprotocol/subscriptionId",Nn="io.modelcontextprotocol/logLevel",ru="traceparent",nu="tracestate",ou="baggage",Xr="2.0",iu=-32700,au=-32600,su=-32601,cu=-32602,uu=-32603,Wr=Cn(()=>re([p(),F(),ee(),wr(),Y(p(),Wr),N(Wr)])),Ge=Y(p(),Wr),sh=N(Wr),xa=re([p(),F().int()]),Ia=p(),lu=x({ttl:F().optional()}),du=x({taskId:p()}),Pa=pe({progressToken:xa.optional(),[Ra]:du.optional()}),pt=x({_meta:Pa.optional()}),Yr=pt.extend({task:lu.optional()}),Xe=x({method:p(),params:pt.loose().optional()}),St=x({_meta:Pa.optional()}),bt=x({method:p(),params:St.loose().optional()}),Ta=pe({get[ur](){return To.optional().catch(void 0)}}),Ye=pe({_meta:Ta.optional()}),Qr=re([p(),F().int()]),Ca=x({jsonrpc:U(Xr),id:Qr,...Xe.shape}).strict(),Aa=x({jsonrpc:U(Xr),...bt.shape}).strict(),Io=x({jsonrpc:U(Xr),id:Qr,result:Ye}).strict(),Po=x({jsonrpc:U(Xr),id:Qr.optional(),error:x({code:F().int(),message:p(),data:ue().optional()})}).strict(),Bt=re([Ca,Aa,Io,Po]),pu=re([Io,Po]),Oa=Ye.strict(),mu=St.extend({requestId:Qr.optional(),reason:p().optional()}),Na=bt.extend({method:U("notifications/cancelled"),params:mu}),fu=x({src:p(),mimeType:p().optional(),sizes:N(p()).optional(),theme:ve(["light","dark"]).optional()}),en=x({icons:N(fu).optional()}),zr=x({name:p(),title:p().optional()}),To=zr.extend({...zr.shape,...en.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),Nx=sr(x({applyDefaults:ee().optional()}),Ge),jx=Zr(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,sr(x({form:Nx.optional(),url:Ge.optional()}),Ge.optional())),hu=pe({list:Ge.optional(),cancel:Ge.optional(),requests:pe({sampling:pe({createMessage:Ge.optional()}).optional(),elicitation:pe({create:Ge.optional()}).optional()}).optional()}),gu=pe({list:Ge.optional(),cancel:Ge.optional(),requests:pe({tools:pe({call:Ge.optional()}).optional()}).optional()}),yu=x({experimental:Y(p(),Ge).optional(),sampling:x({context:Ge.optional(),tools:Ge.optional()}).optional(),elicitation:jx.optional(),roots:x({listChanged:ee().optional()}).optional(),tasks:hu.optional(),extensions:Y(p(),Ge).optional()}),vu=pt.extend({protocolVersion:p(),capabilities:yu,clientInfo:To}),ja=Xe.extend({method:U("initialize"),params:vu}),Ua=x({experimental:Y(p(),Ge).optional(),logging:Ge.optional(),completions:Ge.optional(),prompts:x({listChanged:ee().optional()}).optional(),resources:x({subscribe:ee().optional(),listChanged:ee().optional()}).optional(),tools:x({listChanged:ee().optional()}).optional(),tasks:gu.optional(),extensions:Y(p(),Ge).optional()}),_u=Ye.extend({protocolVersion:p(),capabilities:Ua,serverInfo:To,instructions:p().optional()}),Ma=bt.extend({method:U("notifications/initialized"),params:St.optional()}),Su=Xe.extend({method:U("server/discover"),params:pt.optional()}),jn=Ye.extend({supportedVersions:N(p()),capabilities:Ua,instructions:p().optional()}),Da=Xe.extend({method:U("ping"),params:pt.optional()}),bu=x({progress:F(),total:le(F()),message:le(p())}),$u=x({...St.shape,...bu.shape,progressToken:xa}),qa=bt.extend({method:U("notifications/progress"),params:$u}),wu=pt.extend({cursor:Ia.optional()}),tn=Xe.extend({params:wu.optional()}),rn=Ye.extend({nextCursor:Ia.optional()}),La=x({uri:p(),mimeType:le(p()),_meta:Y(p(),ue()).optional()}),Va=La.extend({text:p()}),ch=p().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ka=La.extend({blob:ch}),nn=ve(["user","assistant"]),kr=x({audience:N(nn).optional(),priority:F().min(0).max(1).optional(),lastModified:Lt.datetime({offset:!0}).optional()}),Ja=x({...zr.shape,...en.shape,uri:p(),description:le(p()),mimeType:le(p()),size:le(F()),annotations:kr.optional(),_meta:le(pe({}))}),zu=x({...zr.shape,...en.shape,uriTemplate:p(),description:le(p()),mimeType:le(p()),annotations:kr.optional(),_meta:le(pe({}))}),ku=tn.extend({method:U("resources/list")}),Eu=rn.extend({resources:N(Ja)}),Ru=tn.extend({method:U("resources/templates/list")}),xu=rn.extend({resourceTemplates:N(zu)}),Co=pt.extend({uri:p()}),Iu=Co,Pu=Xe.extend({method:U("resources/read"),params:Iu}),Tu=Ye.extend({contents:N(re([Va,Ka]))}),Cu=bt.extend({method:U("notifications/resources/list_changed"),params:St.optional()}),Au=Co,Ou=Xe.extend({method:U("resources/subscribe"),params:Au}),Nu=Co,ju=Xe.extend({method:U("resources/unsubscribe"),params:Nu}),Fa=x({toolsListChanged:ee().optional(),promptsListChanged:ee().optional(),resourcesListChanged:ee().optional(),resourceSubscriptions:N(p()).optional()}),Uu=pt.extend({notifications:Fa}),Mu=Xe.extend({method:U("subscriptions/listen"),params:Uu}),Du=St.extend({notifications:Fa}),qu=bt.extend({method:U("notifications/subscriptions/acknowledged"),params:Du}),Lu=Ta.extend({[xo]:Qr}),Vu=Ye.extend({_meta:Lu}),Ku=St.extend({uri:p()}),Ju=bt.extend({method:U("notifications/resources/updated"),params:Ku}),Fu=x({name:p(),description:le(p()),required:le(ee())}),Hu=x({...zr.shape,...en.shape,description:le(p()),arguments:le(N(Fu)),_meta:le(pe({}))}),Zu=tn.extend({method:U("prompts/list")}),Wu=rn.extend({prompts:N(Hu)}),Bu=pt.extend({name:p(),arguments:Y(p(),p()).optional()}),Gu=Xe.extend({method:U("prompts/get"),params:Bu}),Ao=x({type:U("text"),text:p(),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),Oo=x({type:U("image"),data:ch,mimeType:p(),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),No=x({type:U("audio"),data:ch,mimeType:p(),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),Xu=x({type:U("tool_use"),name:p(),id:p(),input:Y(p(),ue()),_meta:Y(p(),ue()).optional()}),Yu=x({type:U("resource"),resource:re([Va,Ka]),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),Qu=Ja.extend({type:U("resource_link")}),jo=re([Ao,Oo,No,Qu,Yu]),el=x({role:nn,content:jo}),tl=Ye.extend({description:p().optional(),messages:N(el)}),rl=bt.extend({method:U("notifications/prompts/list_changed"),params:St.optional()}),nl=x({title:p().optional(),readOnlyHint:ee().optional(),destructiveHint:ee().optional(),idempotentHint:ee().optional(),openWorldHint:ee().optional()}),ol=x({taskSupport:ve(["required","optional","forbidden"]).optional()}),Ha=x({...zr.shape,...en.shape,description:p().optional(),inputSchema:x({type:U("object"),properties:Y(p(),Wr).optional(),required:N(p()).optional()}).catchall(ue()),outputSchema:pe({$schema:p().optional()}).optional(),annotations:nl.optional(),execution:ol.optional(),_meta:Y(p(),ue()).optional()}),il=tn.extend({method:U("tools/list")}),al=rn.extend({tools:N(Ha)}),Uo=Ye.extend({content:N(jo).default([]),structuredContent:ue().optional(),isError:ee().optional()}),uh=Uo.or(Ye.extend({toolResult:ue()})),sl=Yr.extend({name:p(),arguments:Y(p(),ue()).optional()}),cl=Xe.extend({method:U("tools/call"),params:sl}),ul=bt.extend({method:U("notifications/tools/list_changed"),params:St.optional()}),Za=x({autoRefresh:ee().default(!0),debounceMs:F().int().nonnegative().default(300)}),Wa=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),ll=pt.extend({level:Wa}),dl=Xe.extend({method:U("logging/setLevel"),params:ll}),pl=St.extend({level:Wa,logger:p().optional(),data:ue()}),ml=bt.extend({method:U("notifications/message"),params:pl}),fl=x({name:p().optional()}),hl=x({hints:N(fl).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),gl=x({mode:ve(["auto","required","none"]).optional()}),yl=x({type:U("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:N(jo),structuredContent:ue().optional(),isError:ee().optional(),_meta:Y(p(),ue()).optional()}),vl=Tn("type",[Ao,Oo,No]),An=Tn("type",[Ao,Oo,No,Xu,yl]),_l=x({role:nn,content:re([An,N(An)]),_meta:Y(p(),ue()).optional()}),Sl=Yr.extend({messages:N(_l),modelPreferences:hl.optional(),systemPrompt:p().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(p()).optional(),metadata:Ge.optional(),tools:N(Ha).optional(),toolChoice:gl.optional()}),bl=Xe.extend({method:U("sampling/createMessage"),params:Sl}),$l=Ye.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens"]).or(p())),role:nn,content:vl}),wl=Ye.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:nn,content:re([An,N(An)])}),Ba=x({type:U("boolean"),title:p().optional(),description:p().optional(),default:ee().optional()}),Mo=x({type:U("string"),title:p().optional(),description:p().optional(),minLength:F().optional(),maxLength:F().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:p().optional()}),Do=x({type:ve(["number","integer"]),title:p().optional(),description:p().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),Ga=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),default:p().optional()}),Xa=x({type:U("string"),title:p().optional(),description:p().optional(),oneOf:N(x({const:p(),title:p()})),default:p().optional()}),Ya=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),enumNames:N(p()).optional(),default:p().optional()}),zl=re([Ga,Xa]),Qa=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:U("string"),enum:N(p())}),default:N(p()).optional()}),es=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:N(x({const:p(),title:p()}))}),default:N(p()).optional()}),kl=re([Qa,es]),El=re([Ya,zl,kl]),ts=re([El,Ba,Mo,Do]),qo=Yr.extend({mode:U("form").optional(),message:p(),requestedSchema:x({type:U("object"),properties:Y(p(),ts),required:N(p()).optional()}).catchall(ue())}),Rl=Yr.extend({mode:U("url"),message:p(),elicitationId:p(),url:p().url()}),xl=re([qo,Rl]),Il=Xe.extend({method:U("elicitation/create"),params:xl}),Pl=St.extend({elicitationId:p()}),Tl=bt.extend({method:U("notifications/elicitation/complete"),params:Pl}),Cl=Ye.extend({action:ve(["accept","decline","cancel"]),content:Zr(e=>e===null?void 0:e,Y(p(),re([p(),F(),ee(),N(p())])).optional())}),Al=x({type:U("ref/resource"),uri:p()}),Ol=x({type:U("ref/prompt"),name:p()}),Nl=pt.extend({ref:re([Ol,Al]),argument:x({name:p(),value:p()}),context:x({arguments:Y(p(),p()).optional()}).optional()}),jl=Xe.extend({method:U("completion/complete"),params:Nl}),Ul=Ye.extend({completion:pe({values:N(p()).max(100),total:le(F().int()),hasMore:le(ee())})}),Ml=x({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),ue()).optional()}),Dl=Xe.extend({method:U("roots/list"),params:pt.optional()}),ql=Ye.extend({roots:N(Ml)}),Ll=bt.extend({method:U("notifications/roots/list_changed"),params:St.optional()}),lh=pe({ttl:F().optional(),pollInterval:F().optional()}),Vl=ve(["working","input_required","completed","failed","cancelled"]),on=x({taskId:p(),status:Vl,ttl:re([F(),wr()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:le(F()),statusMessage:le(p())}),dh=Ye.extend({task:on}),Kl=St.merge(on),ph=bt.extend({method:U("notifications/tasks/status"),params:Kl}),mh=Xe.extend({method:U("tasks/get"),params:pt.extend({taskId:p()})}),fh=Ye.merge(on),hh=Xe.extend({method:U("tasks/result"),params:pt.extend({taskId:p()})}),gh=Ye.loose(),yh=tn.extend({method:U("tasks/list")}),vh=rn.extend({tasks:N(on)}),_h=Xe.extend({method:U("tasks/cancel"),params:pt.extend({taskId:p()})}),Sh=Ye.merge(on),bh=re([Da,ja,Su,jl,dl,Gu,Zu,ku,Ru,Pu,Ou,ju,Mu,cl,il]),$h=re([Na,qa,Ma,Ll]),wh=re([Oa,$l,wl,Cl,ql]),zh=re([Da,bl,Il,Dl]),kh=re([Na,qa,ml,Ju,Cu,ul,rl,qu,Tl]),Eh=re([Oa,_u,jn,Ul,tl,Wu,Eu,xu,Tu,Uo,al,Vu]),dt=ba().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:V$.custom,message:"URL must be parseable",fatal:!0}),up}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),rs=pe({resource:p().url(),authorization_servers:N(dt).optional(),jwks_uri:p().url().optional(),scopes_supported:N(p()).optional(),bearer_methods_supported:N(p()).optional(),resource_signing_alg_values_supported:N(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:ee().optional(),authorization_details_types_supported:N(p()).optional(),dpop_signing_alg_values_supported:N(p()).optional(),dpop_bound_access_tokens_required:ee().optional()}),Un=pe({issuer:p(),authorization_endpoint:dt,token_endpoint:dt,registration_endpoint:dt.optional(),scopes_supported:N(p()).optional(),response_types_supported:N(p()),response_modes_supported:N(p()).optional(),grant_types_supported:N(p()).optional(),token_endpoint_auth_methods_supported:N(p()).optional(),token_endpoint_auth_signing_alg_values_supported:N(p()).optional(),service_documentation:dt.optional(),revocation_endpoint:dt.optional(),revocation_endpoint_auth_methods_supported:N(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:N(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:N(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:N(p()).optional(),code_challenge_methods_supported:N(p()).optional(),client_id_metadata_document_supported:ee().optional(),authorization_response_iss_parameter_supported:ee().optional().catch(void 0)}),Jl=pe({issuer:p(),authorization_endpoint:dt,token_endpoint:dt,userinfo_endpoint:dt.optional(),jwks_uri:dt,registration_endpoint:dt.optional(),scopes_supported:N(p()).optional(),response_types_supported:N(p()),response_modes_supported:N(p()).optional(),grant_types_supported:N(p()).optional(),acr_values_supported:N(p()).optional(),subject_types_supported:N(p()),id_token_signing_alg_values_supported:N(p()),id_token_encryption_alg_values_supported:N(p()).optional(),id_token_encryption_enc_values_supported:N(p()).optional(),userinfo_signing_alg_values_supported:N(p()).optional(),userinfo_encryption_alg_values_supported:N(p()).optional(),userinfo_encryption_enc_values_supported:N(p()).optional(),request_object_signing_alg_values_supported:N(p()).optional(),request_object_encryption_alg_values_supported:N(p()).optional(),request_object_encryption_enc_values_supported:N(p()).optional(),token_endpoint_auth_methods_supported:N(p()).optional(),token_endpoint_auth_signing_alg_values_supported:N(p()).optional(),display_values_supported:N(p()).optional(),claim_types_supported:N(p()).optional(),claims_supported:N(p()).optional(),service_documentation:p().optional(),claims_locales_supported:N(p()).optional(),ui_locales_supported:N(p()).optional(),claims_parameter_supported:ee().optional(),request_parameter_supported:ee().optional(),request_uri_parameter_supported:ee().optional(),require_request_uri_registration:ee().optional(),op_policy_uri:dt.optional(),op_tos_uri:dt.optional(),client_id_metadata_document_supported:ee().optional(),authorization_response_iss_parameter_supported:ee().optional().catch(void 0)}),ns=x({...Jl.shape,...Un.pick({code_challenge_methods_supported:!0}).shape}),Lo=x({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:eu.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),os=x({issued_token_type:U("urn:ietf:params:oauth:token-type:id-jag"),access_token:p(),token_type:p().optional(),expires_in:F().optional(),scope:p().optional()}).strip(),Mn=x({error:p(),error_description:p().optional(),error_uri:p().optional()}),ah=dt.optional().or(U("").transform(()=>{})),Fl=x({redirect_uris:N(dt),token_endpoint_auth_method:p().optional(),grant_types:N(p()).optional(),response_types:N(p()).optional(),application_type:p().optional(),client_name:p().optional(),client_uri:dt.optional(),logo_uri:ah,scope:p().optional(),contacts:N(p()).optional(),tos_uri:ah,policy_uri:p().optional(),jwks_uri:dt.optional(),jwks:Gf().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),Hl=x({client_id:p(),client_secret:p().optional(),client_id_issued_at:F().optional(),client_secret_expires_at:F().optional()}).strip(),is=Fl.merge(Hl),Rh=x({error:p(),error_description:p().optional()}).strip(),xh=x({token:p(),token_type_hint:p().optional()}).strip()});var W$=q(()=>{Z$()});function Ln(e,t){let r=new Set,n=t;for(;typeof n=="function";){let o=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof o=="string"&&r.add(o),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,Oh,{value:r,enumerable:!1,configurable:!0})}function Ut(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Oh)){let r=t[Oh];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}function qh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Lh({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length=sw}function Kh(e){return e.filter(t=>!Ir(t))}function ps(e){return e.filter(t=>Ir(t))}function cw(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}function Ux(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||uw.some(t=>t in e)?e:{...e,content:[]}}function Mx(){let e=Cn(()=>re([p(),F(),ee(),wr(),Y(p(),e),N(e)])),t=Y(p(),e),r=re([p(),F().int()]),n=p(),o=x({ttl:F().optional()}),i=x({taskId:p()}),a=pe({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),s=x({_meta:a.optional()}),c=s.extend({task:o.optional()}),u=x({method:p(),params:s.loose().optional()}),l=x({_meta:a.optional()}),d=x({method:p(),params:l.loose().optional()}),m=pe({_meta:a.optional()}),v=re([p(),F().int()]),g=m.strict(),h=l.extend({requestId:v.optional(),reason:p().optional()}),f=d.extend({method:U("notifications/cancelled"),params:h}),y=x({src:p(),mimeType:p().optional(),sizes:N(p()).optional(),theme:ve(["light","dark"]).optional()}),S=x({icons:N(y).optional()}),_=x({name:p(),title:p().optional()}),$=_.extend({..._.shape,...S.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),k=sr(x({applyDefaults:ee().optional()}),t),w=Zr(_t=>_t&&typeof _t=="object"&&!Array.isArray(_t)&&Object.keys(_t).length===0?{form:{}}:_t,sr(x({form:k.optional(),url:t.optional()}),t.optional())),b=pe({list:t.optional(),cancel:t.optional(),requests:pe({sampling:pe({createMessage:t.optional()}).optional(),elicitation:pe({create:t.optional()}).optional()}).optional()}),E=pe({list:t.optional(),cancel:t.optional(),requests:pe({tools:pe({call:t.optional()}).optional()}).optional()}),j=x({experimental:Y(p(),t).optional(),sampling:x({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:x({listChanged:ee().optional()}).optional(),tasks:b.optional(),extensions:Y(p(),t).optional()}),V=s.extend({protocolVersion:p(),capabilities:j,clientInfo:$}),A=u.extend({method:U("initialize"),params:V}),L=x({experimental:Y(p(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:x({listChanged:ee().optional()}).optional(),resources:x({subscribe:ee().optional(),listChanged:ee().optional()}).optional(),tools:x({listChanged:ee().optional()}).optional(),tasks:E.optional(),extensions:Y(p(),t).optional()}),Z=m.extend({protocolVersion:p(),capabilities:L,serverInfo:$,instructions:p().optional()}),J=d.extend({method:U("notifications/initialized"),params:l.optional()}),te=u.extend({method:U("ping"),params:s.optional()}),_e=x({progress:F(),total:le(F()),message:le(p())}),ke=x({...l.shape,..._e.shape,progressToken:r}),Ne=d.extend({method:U("notifications/progress"),params:ke}),be=s.extend({cursor:n.optional()}),P=u.extend({params:be.optional()}),M=m.extend({nextCursor:n.optional()}),K=x({uri:p(),mimeType:le(p()),_meta:Y(p(),ue()).optional()}),z=K.extend({text:p()}),I=p().refine(_t=>{try{return atob(_t),!0}catch{return!1}},{message:"Invalid Base64 string"}),O=K.extend({blob:I}),W=ve(["user","assistant"]),ce=x({audience:N(W).optional(),priority:F().min(0).max(1).optional(),lastModified:Lt.datetime({offset:!0}).optional()}),$e=x({..._.shape,...S.shape,uri:p(),description:le(p()),mimeType:le(p()),size:le(F()),annotations:ce.optional(),_meta:le(pe({}))}),B=x({..._.shape,...S.shape,uriTemplate:p(),description:le(p()),mimeType:le(p()),annotations:ce.optional(),_meta:le(pe({}))}),Re=P.extend({method:U("resources/list")}),Fe=M.extend({resources:N($e)}),R=P.extend({method:U("resources/templates/list")}),T=M.extend({resourceTemplates:N(B)}),D=s.extend({uri:p()}),oe=D,ne=u.extend({method:U("resources/read"),params:oe}),ie=m.extend({contents:N(re([z,O]))}),me=d.extend({method:U("notifications/resources/list_changed"),params:l.optional()}),Pe=D,Ee=u.extend({method:U("resources/subscribe"),params:Pe}),Ze=D,je=u.extend({method:U("resources/unsubscribe"),params:Ze}),De=l.extend({uri:p()}),nt=d.extend({method:U("notifications/resources/updated"),params:De}),Jt=x({name:p(),description:le(p()),required:le(ee())}),yt=x({..._.shape,...S.shape,description:le(p()),arguments:le(N(Jt)),_meta:le(pe({}))}),ut=P.extend({method:U("prompts/list")}),Ft=M.extend({prompts:N(yt)}),rr=s.extend({name:p(),arguments:Y(p(),p()).optional()}),hn=u.extend({method:U("prompts/get"),params:rr}),gn=x({type:U("text"),text:p(),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),yn=x({type:U("image"),data:I,mimeType:p(),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),vn=x({type:U("audio"),data:I,mimeType:p(),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),mi=x({type:U("tool_use"),name:p(),id:p(),input:Y(p(),ue()),_meta:Y(p(),ue()).optional()}),Or=x({type:U("resource"),resource:re([z,O]),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),fi=$e.extend({type:U("resource_link")}),Dt=re([gn,yn,vn,fi,Or]),no=x({role:W,content:Dt}),oo=m.extend({description:p().optional(),messages:N(no)}),_n=d.extend({method:U("notifications/prompts/list_changed"),params:l.optional()}),hi=x({title:p().optional(),readOnlyHint:ee().optional(),destructiveHint:ee().optional(),idempotentHint:ee().optional(),openWorldHint:ee().optional()}),io=x({taskSupport:ve(["required","optional","forbidden"]).optional()}),Sn=x({..._.shape,...S.shape,description:p().optional(),inputSchema:x({type:U("object"),properties:Y(p(),e).optional(),required:N(p()).optional()}).catchall(ue()),outputSchema:x({type:U("object"),properties:Y(p(),e).optional(),required:N(p()).optional()}).catchall(ue()).optional(),annotations:hi.optional(),execution:io.optional(),_meta:Y(p(),ue()).optional()}),ao=P.extend({method:U("tools/list")}),so=M.extend({tools:N(Sn)}),co=m.extend({content:N(Dt),structuredContent:Y(p(),ue()).optional(),isError:ee().optional()}),vt=c.extend({name:p(),arguments:Y(p(),ue()).optional()}),gi=u.extend({method:U("tools/call"),params:vt}),Us=d.extend({method:U("notifications/tools/list_changed"),params:l.optional()}),uo=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),yi=s.extend({level:uo}),vi=u.extend({method:U("logging/setLevel"),params:yi}),_i=l.extend({level:uo,logger:p().optional(),data:ue()}),Si=d.extend({method:U("notifications/message"),params:_i}),bi=x({name:p().optional()}),$i=x({hints:N(bi).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),wi=x({mode:ve(["auto","required","none"]).optional()}),Ms=x({type:U("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:N(Dt),structuredContent:x({}).loose().optional(),isError:ee().optional(),_meta:Y(p(),ue()).optional()}),zi=Tn("type",[gn,yn,vn]),Nr=Tn("type",[gn,yn,vn,mi,Ms]),ki=x({role:W,content:re([Nr,N(Nr)]),_meta:Y(p(),ue()).optional()}),Ei=c.extend({messages:N(ki),modelPreferences:$i.optional(),systemPrompt:p().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(p()).optional(),metadata:t.optional(),tools:N(Sn).optional(),toolChoice:wi.optional()}),Ri=u.extend({method:U("sampling/createMessage"),params:Ei}),xi=m.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens"]).or(p())),role:W,content:zi}),Ii=m.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:W,content:re([Nr,N(Nr)])}),Pi=x({type:U("boolean"),title:p().optional(),description:p().optional(),default:ee().optional()}),Ti=x({type:U("string"),title:p().optional(),description:p().optional(),minLength:F().optional(),maxLength:F().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:p().optional()}),Ci=x({type:ve(["number","integer"]),title:p().optional(),description:p().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),Ai=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),default:p().optional()}),Oi=x({type:U("string"),title:p().optional(),description:p().optional(),oneOf:N(x({const:p(),title:p()})),default:p().optional()}),Ni=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),enumNames:N(p()).optional(),default:p().optional()}),ji=re([Ai,Oi]),bn=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:U("string"),enum:N(p())}),default:N(p()).optional()}),$n=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:N(x({const:p(),title:p()}))}),default:N(p()).optional()}),Ds=re([bn,$n]),qs=re([Ni,ji,Ds]),Tt=re([qs,Pi,Ti,Ci]),Ct=c.extend({mode:U("form").optional(),message:p(),requestedSchema:x({type:U("object"),properties:Y(p(),Tt),required:N(p()).optional()}).catchall(ue())}),Ui=c.extend({mode:U("url"),message:p(),elicitationId:p(),url:p().url()}),Ht=re([Ct,Ui]),Ls=u.extend({method:U("elicitation/create"),params:Ht}),Vs=l.extend({elicitationId:p()}),Ks=d.extend({method:U("notifications/elicitation/complete"),params:Vs}),Js=m.extend({action:ve(["accept","decline","cancel"]),content:Zr(_t=>_t===null?void 0:_t,Y(p(),re([p(),F(),ee(),N(p())])).optional())}),Fs=x({type:U("ref/resource"),uri:p()}),Hs=x({type:U("ref/prompt"),name:p()}),Zs=s.extend({ref:re([Hs,Fs]),argument:x({name:p(),value:p()}),context:x({arguments:Y(p(),p()).optional()}).optional()}),Mi=u.extend({method:U("completion/complete"),params:Zs}),Ws=m.extend({completion:pe({values:N(p()).max(100),total:le(F().int()),hasMore:le(ee())})}),Bs=x({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),ue()).optional()}),lo=u.extend({method:U("roots/list"),params:s.optional()}),Di=m.extend({roots:N(Bs)}),Gs=d.extend({method:U("notifications/roots/list_changed"),params:l.optional()}),Xs=pe({ttl:F().optional(),pollInterval:F().optional()}),Ys=ve(["working","input_required","completed","failed","cancelled"]),jr=x({taskId:p(),status:Ys,ttl:re([F(),wr()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:le(F()),statusMessage:le(p())}),kt=m.extend({task:jr}),Qs=l.merge(jr),wn=d.extend({method:U("notifications/tasks/status"),params:Qs}),po=u.extend({method:U("tasks/get"),params:s.extend({taskId:p()})}),mo=m.merge(jr),fo=u.extend({method:U("tasks/result"),params:s.extend({taskId:p()})}),np=m.loose(),Et=P.extend({method:U("tasks/list")}),et=M.extend({tasks:N(jr)}),zn=u.extend({method:U("tasks/cancel"),params:s.extend({taskId:p()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:o,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:u,NotificationsParamsSchema:l,NotificationSchema:d,ResultSchema:m,RequestIdSchema:v,EmptyResultSchema:g,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:f,IconSchema:y,IconsSchema:S,BaseMetadataSchema:_,ImplementationSchema:$,ClientTasksCapabilitySchema:b,ServerTasksCapabilitySchema:E,ClientCapabilitiesSchema:j,InitializeRequestParamsSchema:V,InitializeRequestSchema:A,ServerCapabilitiesSchema:L,InitializeResultSchema:Z,InitializedNotificationSchema:J,PingRequestSchema:te,ProgressSchema:_e,ProgressNotificationParamsSchema:ke,ProgressNotificationSchema:Ne,PaginatedRequestParamsSchema:be,PaginatedRequestSchema:P,PaginatedResultSchema:M,ResourceContentsSchema:K,TextResourceContentsSchema:z,BlobResourceContentsSchema:O,RoleSchema:W,AnnotationsSchema:ce,ResourceSchema:$e,ResourceTemplateSchema:B,ListResourcesRequestSchema:Re,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:R,ListResourceTemplatesResultSchema:T,ResourceRequestParamsSchema:D,ReadResourceRequestParamsSchema:oe,ReadResourceRequestSchema:ne,ReadResourceResultSchema:ie,ResourceListChangedNotificationSchema:me,SubscribeRequestParamsSchema:Pe,SubscribeRequestSchema:Ee,UnsubscribeRequestParamsSchema:Ze,UnsubscribeRequestSchema:je,ResourceUpdatedNotificationParamsSchema:De,ResourceUpdatedNotificationSchema:nt,PromptArgumentSchema:Jt,PromptSchema:yt,ListPromptsRequestSchema:ut,ListPromptsResultSchema:Ft,GetPromptRequestParamsSchema:rr,GetPromptRequestSchema:hn,TextContentSchema:gn,ImageContentSchema:yn,AudioContentSchema:vn,ToolUseContentSchema:mi,EmbeddedResourceSchema:Or,ResourceLinkSchema:fi,ContentBlockSchema:Dt,PromptMessageSchema:no,GetPromptResultSchema:oo,PromptListChangedNotificationSchema:_n,ToolAnnotationsSchema:hi,ToolExecutionSchema:io,ToolSchema:Sn,ListToolsRequestSchema:ao,ListToolsResultSchema:so,CallToolResultSchema:co,CallToolRequestParamsSchema:vt,CallToolRequestSchema:gi,ToolListChangedNotificationSchema:Us,LoggingLevelSchema:uo,SetLevelRequestParamsSchema:yi,SetLevelRequestSchema:vi,LoggingMessageNotificationParamsSchema:_i,LoggingMessageNotificationSchema:Si,ModelHintSchema:bi,ModelPreferencesSchema:$i,ToolChoiceSchema:wi,ToolResultContentSchema:Ms,SamplingContentSchema:zi,SamplingMessageContentBlockSchema:Nr,SamplingMessageSchema:ki,CreateMessageRequestParamsSchema:Ei,CreateMessageRequestSchema:Ri,CreateMessageResultSchema:xi,CreateMessageResultWithToolsSchema:Ii,BooleanSchemaSchema:Pi,StringSchemaSchema:Ti,NumberSchemaSchema:Ci,UntitledSingleSelectEnumSchemaSchema:Ai,TitledSingleSelectEnumSchemaSchema:Oi,LegacyTitledEnumSchemaSchema:Ni,SingleSelectEnumSchemaSchema:ji,UntitledMultiSelectEnumSchemaSchema:bn,TitledMultiSelectEnumSchemaSchema:$n,MultiSelectEnumSchemaSchema:Ds,EnumSchemaSchema:qs,PrimitiveSchemaDefinitionSchema:Tt,ElicitRequestFormParamsSchema:Ct,ElicitRequestURLParamsSchema:Ui,ElicitRequestParamsSchema:Ht,ElicitRequestSchema:Ls,ElicitationCompleteNotificationParamsSchema:Vs,ElicitationCompleteNotificationSchema:Ks,ElicitResultSchema:Js,ResourceTemplateReferenceSchema:Fs,PromptReferenceSchema:Hs,CompleteRequestParamsSchema:Zs,CompleteRequestSchema:Mi,CompleteResultSchema:Ws,RootSchema:Bs,ListRootsRequestSchema:lo,ListRootsResultSchema:Di,RootsListChangedNotificationSchema:Gs,TaskCreationParamsSchema:Xs,TaskStatusSchema:Ys,TaskSchema:jr,CreateTaskResultSchema:kt,TaskStatusNotificationParamsSchema:Qs,TaskStatusNotificationSchema:wn,GetTaskRequestSchema:po,GetTaskResultSchema:mo,GetTaskPayloadRequestSchema:fo,GetTaskPayloadResultSchema:np,ListTasksRequestSchema:Et,ListTasksResultSchema:et,CancelTaskRequestSchema:zn,CancelTaskResultSchema:m.merge(jr),ClientRequestSchema:re([te,A,Mi,vi,hn,ut,Re,R,ne,Ee,je,gi,ao,po,fo,Et,zn]),ClientNotificationSchema:re([f,Ne,J,Gs,wn]),ClientResultSchema:re([g,xi,Ii,Js,Di,mo,et,kt]),ServerRequestSchema:re([te,Ri,Ls,lo,po,fo,Et,zn]),ServerNotificationSchema:re([f,Ne,Si,nt,me,Us,_n,wn,Ks]),ServerResultSchema:re([g,Z,Ws,oo,Ft,Fe,T,ie,co,so,mo,et,kt]),CallToolResultWireSchema:ue().superRefine((_t,Lk)=>{if(!(typeof _t!="object"||_t===null||Array.isArray(_t)||_t.content!==void 0)){for(let Ey of uw)if(Ey in _t){Lk.addIssue({code:"custom",message:`content is required when the body carries '${Ey}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Ux).pipe(co)}}function Jh(){return Dx??=Mx()}function lw(e){return e.type!=="object"}function Vx(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(e.$id!==void 0)return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=(n,o)=>{if(Array.isArray(n))return n.map(a=>r(a,!1));if(n===null||typeof n!="object"||!o&&n.$id!==void 0)return n;let i={};for(let[a,s]of Object.entries(n))o?i[a]=r(s,!1):(a==="$ref"||a==="$dynamicRef")&&typeof s=="string"?i[a]=s==="#"?"#/properties/result":s.startsWith("#/")?`#/properties/result${s.slice(1)}`:s:qx.has(a)?i[a]=s:Lx.has(a)?i[a]=r(s,!0):i[a]=r(s,!1);return i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:r(e,!1)},required:["result"]}}function Ql(){if(Zl)return Zl;let e=Jh();return Zl={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Zl}function Jx(){Ql()}function mw(e){return Object.prototype.hasOwnProperty.call(dw,e)}function fw(e){return Object.prototype.hasOwnProperty.call(pw,e)}function Fx(e){return Object.prototype.hasOwnProperty.call(Kx,e)}function Hx(e){return Fx(e)?Ql().resultSchemas[e]:void 0}function Zx(e){return mw(e)?Ql().requestSchemas[e]:void 0}function Wx(e){return fw(e)?Ql().notificationSchemas[e]:void 0}function Nh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Wl(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}function G$(e){return Nh(e)&&Nh(e.outputSchema)&&lw(e.outputSchema)}function Bx(){let e=Cn(()=>re([p(),F(),ee(),wr(),Y(p(),e),N(e)])),t=Y(p(),e),r=re([p(),F().int()]),n=p(),o=re([p(),F().int()]),i=ve(["user","assistant"]),a=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),s=p().refine(et=>{try{return atob(et),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=x({ttl:F().optional()}),u=x({taskId:p()}),l=pe({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),d=x({_meta:l.optional()}),m=d.extend({task:c.optional()}),v=x({_meta:l.optional()}),g=x({method:p(),params:v.loose().optional()}),h=x({src:p(),mimeType:p().optional(),sizes:N(p()).optional(),theme:ve(["light","dark"]).optional()}),f=x({icons:N(h).optional()}),y=x({name:p(),title:p().optional()}),S=y.extend({...y.shape,...f.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),_=sr(x({applyDefaults:ee().optional()}),t),$=Zr(et=>et&&typeof et=="object"&&!Array.isArray(et)&&Object.keys(et).length===0?{form:{}}:et,sr(x({form:_.optional(),url:t.optional()}),t.optional())),k=pe({list:t.optional(),cancel:t.optional(),requests:pe({sampling:pe({createMessage:t.optional()}).optional(),elicitation:pe({create:t.optional()}).optional()}).optional()}),w=pe({list:t.optional(),cancel:t.optional(),requests:pe({tools:pe({call:t.optional()}).optional()}).optional()}),b=x({experimental:Y(p(),t).optional(),sampling:x({context:t.optional(),tools:t.optional()}).optional(),elicitation:$.optional(),roots:x({listChanged:ee().optional()}).optional(),tasks:k.optional(),extensions:Y(p(),t).optional()}),E=x({experimental:Y(p(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:x({listChanged:ee().optional()}).optional(),resources:x({subscribe:ee().optional(),listChanged:ee().optional()}).optional(),tools:x({listChanged:ee().optional()}).optional(),tasks:w.optional(),extensions:Y(p(),t).optional()}),j=x({progress:F(),total:le(F()),message:le(p())}),V=x({...v.shape,...j.shape,progressToken:r}),A=g.extend({method:U("notifications/progress"),params:V}),L=v.extend({level:a,logger:p().optional(),data:ue()}),Z=g.extend({method:U("notifications/message"),params:L}),J=x({uri:p(),mimeType:le(p()),_meta:Y(p(),ue()).optional()}),te=J.extend({text:p()}),_e=J.extend({blob:s}),ke=x({audience:N(i).optional(),priority:F().min(0).max(1).optional(),lastModified:Lt.datetime({offset:!0}).optional()}),Ne=x({...y.shape,...f.shape,uri:p(),description:le(p()),mimeType:le(p()),size:le(F()),annotations:ke.optional(),_meta:le(pe({}))}),be=x({...y.shape,...f.shape,uriTemplate:p(),description:le(p()),mimeType:le(p()),annotations:ke.optional(),_meta:le(pe({}))}),P=g.extend({method:U("notifications/resources/list_changed"),params:v.optional()}),M=v.extend({uri:p()}),K=g.extend({method:U("notifications/resources/updated"),params:M}),z=x({name:p(),description:le(p()),required:le(ee())}),I=x({...y.shape,...f.shape,description:le(p()),arguments:le(N(z)),_meta:le(pe({}))}),O=g.extend({method:U("notifications/prompts/list_changed"),params:v.optional()}),W=x({type:U("text"),text:p(),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),ce=x({type:U("image"),data:s,mimeType:p(),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),$e=x({type:U("audio"),data:s,mimeType:p(),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),B=x({type:U("tool_use"),name:p(),id:p(),input:Y(p(),ue()),_meta:Y(p(),ue()).optional()}),Re=x({type:U("resource"),resource:re([te,_e]),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),Fe=Ne.extend({type:U("resource_link")}),R=re([W,ce,$e,Fe,Re]),T=x({role:i,content:R}),D=x({title:p().optional(),readOnlyHint:ee().optional(),destructiveHint:ee().optional(),idempotentHint:ee().optional(),openWorldHint:ee().optional()}),oe=g.extend({method:U("notifications/tools/list_changed"),params:v.optional()}),ne=x({name:p().optional()}),ie=x({hints:N(ne).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),me=x({mode:ve(["auto","required","none"]).optional()}),Pe=x({type:U("boolean"),title:p().optional(),description:p().optional(),default:ee().optional()}),Ee=x({type:U("string"),title:p().optional(),description:p().optional(),minLength:F().optional(),maxLength:F().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:p().optional()}),Ze=x({type:ve(["number","integer"]),title:p().optional(),description:p().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),je=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),default:p().optional()}),De=x({type:U("string"),title:p().optional(),description:p().optional(),oneOf:N(x({const:p(),title:p()})),default:p().optional()}),nt=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),enumNames:N(p()).optional(),default:p().optional()}),Jt=re([je,De]),yt=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:U("string"),enum:N(p())}),default:N(p()).optional()}),ut=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:N(x({const:p(),title:p()}))}),default:N(p()).optional()}),Ft=re([yt,ut]),rr=re([nt,Jt,Ft]),hn=re([rr,Pe,Ee,Ze]),gn=m.extend({mode:U("form").optional(),message:p(),requestedSchema:x({type:U("object"),properties:Y(p(),hn),required:N(p()).optional()}).catchall(ue())}),yn=x({type:U("ref/resource"),uri:p()}),vn=x({type:U("ref/prompt"),name:p()}),mi=x({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),ue()).optional()}),Or=b.shape,fi=x({experimental:Or.experimental,sampling:Or.sampling,elicitation:Or.elicitation,roots:Or.roots,extensions:Or.extensions}),Dt=E.shape,no=x({experimental:Dt.experimental,logging:Dt.logging,completions:Dt.completions,prompts:Dt.prompts,resources:Dt.resources,tools:Dt.tools,extensions:Dt.extensions}),oo=pe({progressToken:r.optional(),[cr]:p(),[On]:S.optional(),[Gr]:fi,[Nn]:a.optional()}),_n=x({...y.shape,...f.shape,description:p().optional(),inputSchema:pe({$schema:p().optional(),type:U("object")}),outputSchema:pe({$schema:p().optional()}).optional(),annotations:D.optional(),_meta:Y(p(),ue()).optional()}),hi=x({type:U("tool_result"),toolUseId:p(),content:N(R),structuredContent:ue().optional(),isError:ee().optional(),_meta:Y(p(),ue()).optional()}),io=re([W,ce,$e,B,hi]),Sn=x({role:i,content:re([io,N(io)]),_meta:Y(p(),ue()).optional()}),ao=p(),so=pe({[ur]:S.optional().catch(void 0)}),co=so.optional();function vt(et){return pe({_meta:co,resultType:ao.default("complete"),...et})}let gi=vt({}),Us=vt({nextCursor:n.optional()}),uo=vt({content:N(R),structuredContent:ue().optional(),isError:ee().optional()}),yi=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),tools:N(_n),nextCursor:n.optional()}),vi=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),prompts:N(I),nextCursor:n.optional()}),_i=vt({description:p().optional(),messages:N(T)}),Si=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resources:N(Ne),nextCursor:n.optional()}),bi=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resourceTemplates:N(be),nextCursor:n.optional()}),$i=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),contents:N(re([te,_e]))}),wi=vt({completion:x({values:N(p()).max(100),total:F().int().optional(),hasMore:ee().optional()}).loose()}),Ms=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"])}),zi=vt({ttlMs:F().int().min(0).catch(0),cacheScope:ve(["public","private"]).catch("private"),supportedVersions:N(p()),capabilities:no,instructions:p().optional()}),Nr=x({messages:N(Sn),modelPreferences:ie.optional(),systemPrompt:p().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(p()).optional(),metadata:t.optional(),tools:N(_n).optional(),toolChoice:me.optional()}),ki=x({method:U("sampling/createMessage"),params:Nr}),Ei=x({method:U("roots/list"),params:x({_meta:Y(p(),ue()).optional()}).optional()}),Ri=x({...Sn.shape,model:p(),stopReason:p().optional()}),xi=x({roots:N(mi)}),Ii=x({action:ve(["accept","decline","cancel"]),content:Y(p(),re([p(),F(),ee(),N(p())])).optional()}),Pi=x({mode:U("url"),message:p(),url:p().url()}),Ti=re([gn,Pi]),Ci=x({method:U("elicitation/create"),params:Ti}),Ai=re([ki,Ei,Ci]),Oi=re([Ri,xi,Ii]),Ni=Y(p(),Ai),ji=Y(p(),Oi),bn=vt({inputRequests:Ni.optional(),requestState:p().optional()}),$n={inputResponses:ji.optional(),requestState:p().optional()},Ds=x({_meta:oo,...$n}),qs=pe({progressToken:r.optional()});function Tt(et,zn){return x({method:U(et),params:x({_meta:oo,...zn})})}function Ct(et,zn){return x({method:U(et),params:x({_meta:qs.optional(),...zn}).optional()})}let Ui={name:p(),arguments:Y(p(),ue()).optional(),...$n},Ht={cursor:n.optional()},Ls=Tt("tools/call",Ui),Vs=Tt("tools/list",Ht),Ks=Tt("prompts/list",Ht),Js=Tt("prompts/get",{name:p(),arguments:Y(p(),p()).optional(),...$n}),Fs=Tt("resources/list",Ht),Hs=Tt("resources/templates/list",Ht),Zs=Tt("resources/read",{uri:p(),...$n}),Mi={ref:re([vn,yn]),argument:x({name:p(),value:p()}),context:x({arguments:Y(p(),p()).optional()}).optional()},Ws=Tt("completion/complete",Mi),Bs=Tt("server/discover",{}),lo=x({toolsListChanged:ee().optional(),promptsListChanged:ee().optional(),resourcesListChanged:ee().optional(),resourceSubscriptions:N(p()).optional()}),Di={notifications:lo},Gs=Tt("subscriptions/listen",Di),Xs=so.extend({"io.modelcontextprotocol/subscriptionId":o}),Ys=pe({_meta:Xs,resultType:ao.default("complete")}),jr={"tools/call":Ct("tools/call",Ui),"tools/list":Ct("tools/list",Ht),"prompts/get":Ct("prompts/get",{name:p(),arguments:Y(p(),p()).optional()}),"prompts/list":Ct("prompts/list",Ht),"resources/list":Ct("resources/list",Ht),"resources/templates/list":Ct("resources/templates/list",Ht),"resources/read":Ct("resources/read",{uri:p()}),"completion/complete":Ct("completion/complete",Mi),"server/discover":Ct("server/discover",{}),"subscriptions/listen":Ct("subscriptions/listen",Di)};function kt(et){return pe({_meta:co,...et})}let Qs={"tools/call":kt({content:N(R),structuredContent:ue().optional(),isError:ee().optional()}),"tools/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),tools:N(_n),nextCursor:n.optional()}),"prompts/get":kt({description:p().optional(),messages:N(T)}),"prompts/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),prompts:N(I),nextCursor:n.optional()}),"resources/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resources:N(Ne),nextCursor:n.optional()}),"resources/templates/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resourceTemplates:N(be),nextCursor:n.optional()}),"resources/read":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),contents:N(re([te,_e]))}),"completion/complete":kt({completion:x({values:N(p()).max(100),total:F().int().optional(),hasMore:ee().optional()}).loose()}),"server/discover":kt({ttlMs:F().int().min(0).catch(0),cacheScope:ve(["public","private"]).catch("private"),supportedVersions:N(p()),capabilities:no,instructions:p().optional()}),"subscriptions/listen":kt({})},wn=pe({"io.modelcontextprotocol/subscriptionId":o.optional()}),po=x({method:U("notifications/subscriptions/acknowledged"),params:x({_meta:wn.optional(),notifications:lo})}),mo=x({_meta:wn.optional(),requestId:o,reason:p().optional()}),fo=x({method:U("notifications/cancelled"),params:mo}),np={"notifications/cancelled":fo,"notifications/progress":A,"notifications/message":Z,"notifications/resources/updated":K,"notifications/resources/list_changed":P,"notifications/tools/list_changed":oe,"notifications/prompts/list_changed":O,"notifications/subscriptions/acknowledged":po},Et=et=>x({jsonrpc:U("2.0"),id:re([p(),F().int()]),result:et}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:o,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:c,RelatedTaskMetadataSchema:u,RequestMetaSchema:l,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:m,NotificationsParamsSchema:v,NotificationSchema:g,IconSchema:h,IconsSchema:f,BaseMetadataSchema:y,ImplementationSchema:S,ClientTasksCapabilitySchema:k,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:b,ServerCapabilitiesSchema:E,ProgressSchema:j,ProgressNotificationParamsSchema:V,ProgressNotificationSchema:A,LoggingMessageNotificationParamsSchema:L,LoggingMessageNotificationSchema:Z,ResourceContentsSchema:J,TextResourceContentsSchema:te,BlobResourceContentsSchema:_e,AnnotationsSchema:ke,ResourceSchema:Ne,ResourceTemplateSchema:be,ResourceListChangedNotificationSchema:P,ResourceUpdatedNotificationParamsSchema:M,ResourceUpdatedNotificationSchema:K,PromptArgumentSchema:z,PromptSchema:I,PromptListChangedNotificationSchema:O,TextContentSchema:W,ImageContentSchema:ce,AudioContentSchema:$e,ToolUseContentSchema:B,EmbeddedResourceSchema:Re,ResourceLinkSchema:Fe,ContentBlockSchema:R,PromptMessageSchema:T,ToolAnnotationsSchema:D,ToolListChangedNotificationSchema:oe,ModelHintSchema:ne,ModelPreferencesSchema:ie,ToolChoiceSchema:me,BooleanSchemaSchema:Pe,StringSchemaSchema:Ee,NumberSchemaSchema:Ze,UntitledSingleSelectEnumSchemaSchema:je,TitledSingleSelectEnumSchemaSchema:De,LegacyTitledEnumSchemaSchema:nt,SingleSelectEnumSchemaSchema:Jt,UntitledMultiSelectEnumSchemaSchema:yt,TitledMultiSelectEnumSchemaSchema:ut,MultiSelectEnumSchemaSchema:Ft,EnumSchemaSchema:rr,PrimitiveSchemaDefinitionSchema:hn,ElicitRequestFormParamsSchema:gn,ResourceTemplateReferenceSchema:yn,PromptReferenceSchema:vn,RootSchema:mi,ClientCapabilities2026Schema:fi,ServerCapabilities2026Schema:no,RequestMetaEnvelopeSchema:oo,ToolSchema:_n,ToolResultContentSchema:hi,SamplingMessageContentBlockSchema:io,SamplingMessageSchema:Sn,ResultTypeSchema:ao,ResultMetaSchema:so,ResultSchema:gi,PaginatedResultSchema:Us,CallToolResultSchema:uo,ListToolsResultSchema:yi,ListPromptsResultSchema:vi,GetPromptResultSchema:_i,ListResourcesResultSchema:Si,ListResourceTemplatesResultSchema:bi,ReadResourceResultSchema:$i,CompleteResultSchema:wi,CacheableResultSchema:Ms,DiscoverResultSchema:zi,CreateMessageRequestParamsSchema:Nr,CreateMessageRequestSchema:ki,ListRootsRequestSchema:Ei,CreateMessageResultSchema:Ri,ListRootsResultSchema:xi,ElicitResultSchema:Ii,ElicitRequestURLParamsSchema:Pi,ElicitRequestParamsSchema:Ti,ElicitRequestSchema:Ci,InputRequestSchema:Ai,InputResponseSchema:Oi,InputRequestsSchema:Ni,InputResponsesSchema:ji,InputRequiredResultSchema:bn,InputResponseRequestParamsSchema:Ds,CallToolRequestSchema:Ls,ListToolsRequestSchema:Vs,ListPromptsRequestSchema:Ks,GetPromptRequestSchema:Js,ListResourcesRequestSchema:Fs,ListResourceTemplatesRequestSchema:Hs,ReadResourceRequestSchema:Zs,CompleteRequestSchema:Ws,DiscoverRequestSchema:Bs,SubscriptionFilterSchema:lo,SubscriptionsListenRequestSchema:Gs,SubscriptionsListenResultMetaSchema:Xs,SubscriptionsListenResultSchema:Ys,dispatchRequestSchemas:jr,dispatchResultSchemas:Qs,NotificationMetaSchema:wn,SubscriptionsAcknowledgedNotificationSchema:po,CancelledNotificationParamsSchema:mo,CancelledNotificationSchema:fo,notificationSchemas2026:np,JSONRPCResultResponseSchema:Et(gi),CallToolResultResponseSchema:Et(re([uo,bn])),ListToolsResultResponseSchema:Et(yi),ListPromptsResultResponseSchema:Et(vi),GetPromptResultResponseSchema:Et(re([_i,bn])),ListResourcesResultResponseSchema:Et(Si),ListResourceTemplatesResultResponseSchema:Et(bi),ReadResourceResultResponseSchema:Et(re([$i,bn])),CompleteResultResponseSchema:Et(wi),DiscoverResultResponseSchema:Et(zi)}}function an(){return Gx??=Bx()}function Yx(e){return Xx.includes(e)}function Qx(e){return e[Hh]}function hw(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function gw(e){return e==="public"||e==="private"}function nI(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||rI.includes(e))return t;throw new Me(fe.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function oI(e,t){let r=Qx(t);if(t.resultType!=="complete"||!Yx(e))return r===void 0?t:uI(t);let n=t,o=hw(n.ttlMs)?n.ttlMs:sI(r),i=gw(n.cacheScope)?n.cacheScope:cI(r),a={...n,ttlMs:o,cacheScope:i};return delete a[Hh],a}function iI(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function aI(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[ur]:t}}:!iI(r)||r[ur]!==void 0?e:{...e,_meta:{...r,[ur]:t}}}function sI(e){return e!==void 0&&hw(e.ttlMs)?e.ttlMs:eI}function cI(e){return e!==void 0&&gw(e.cacheScope)?e.cacheScope:tI}function uI(e){let t={...e};return delete t[Hh],t}function Gh(){if(Bl)return Bl;let e=an();return Bl={request:{"elicitation/create":x({method:U("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":x({method:U("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":x({method:U("roots/list"),params:pe({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Bl}function dI(){Gh()}function vw(e){return lI.includes(e)}function Ih(e){return vw(e)?Gh().request[e]:void 0}function pI(e){return vw(e)?Gh().response[e]:void 0}function Sw(e){return Object.prototype.hasOwnProperty.call(Xh,e)}function bw(e){return Object.prototype.hasOwnProperty.call(_w,e)}function mI(e){return Object.prototype.hasOwnProperty.call(Xh,e)}function fI(e){return Sw(e)?an().dispatchRequestSchemas[e]:void 0}function hI(e){return mI(e)?an().dispatchResultSchemas[e]:void 0}function gI(e){return bw(e)?an().notificationSchemas2026[e]:void 0}function cs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function as(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}function _I(e,t){let r=t,n=!1,o=()=>(n||(r={...r},n=!0),r),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(s=>cs(s)&&"execution"in s)&&(o().tools=i.map(s=>{if(!cs(s)||!("execution"in s))return s;let c={...s};return delete c.execution,c}));let a=t.capabilities;if(cs(a)&&"tasks"in a){let s={...a};delete s.tasks,o().capabilities=s}return r}function $w(){if(Gl)return Gl;let e=an();return Gl={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Gl}function SI(){$w()}function Er(e){return e!==void 0&&Ir(e)?Yh:Fh}function X$(e){return e.revision!==void 0?Er(e.revision).era:e.era==="modern"?Yh.era:Fh.era}function Ph(e){return ww.some(t=>t.hasRequestMethod(e))}function Th(e){return ww.some(t=>t.hasNotificationMethod(e))}function zw(e){return Bt.parse(e)}function xw(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Iw(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function tg(e){let t=[],r=new Map,n=(i,a,s)=>{if(i===null||typeof i!="object")return;let c=i;if(Y$ in c){if(!s||a.length===0)return`${Xl(a)}: 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)`;let l=c[Y$];if(typeof l!="string"||l.length===0)return`${Xl(a)}: x-mcp-header MUST be a non-empty string`;if(!wI.test(l))return`${Xl(a)}: x-mcp-header '${l}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let d=typeof c.type=="string"?c.type:void 0;if(d===void 0||!zI.has(d))return`${Xl(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${d??""}`;let m=l.toLowerCase(),v=r.get(m);if(v!==void 0)return`x-mcp-header '${l}' is not case-insensitively unique (also declared as '${v}')`;r.set(m,l),t.push({path:a,headerName:l,type:d})}let u=c.properties;if(u!==null&&typeof u=="object")for(let[l,d]of Object.entries(u)){let m=n(d,[...a,l],s);if(m!==void 0)return m}for(let l of kI){let d=c[l];if(d===void 0)continue;let m=Array.isArray(d)?d:d!==null&&typeof d=="object"&&EI.has(l)?Object.values(d):[d];for(let v of m){let g=n(v,[...a,`<${l}>`],!1);if(g!==void 0)return g}}},o=n(e,[],!0);return o===void 0?{valid:!0,declarations:t}:{valid:!1,reason:o}}function Xl(e){return e.length===0?"":e.join(".")}function RI(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function xI(e){if(e.length===0||e.startsWith(Pw)&&e.endsWith(Tw)||e!==e.trim())return!0;for(let t=0;t=32&&r<=126))return!0}return!1}function II(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCodePoint(n);return btoa(r)}function rg(e){return xI(e)?`${Pw}${II(e)}${Tw}`:e}function PI(e,t){let r=e;for(let n of t){if(r===null||typeof r!="object")return;r=r[n]}return r}function Cw(e,t){let r={};for(let n of e){let o=PI(t,n.path);if(o==null)continue;let i=RI(o);i!==void 0&&(r[`${$I}${n.headerName}`]=rg(i))}return r}function nd(e,t){return Jc(e,t)}function ss(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function jh(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}function TI(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Uh});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Q$||(Q$=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=fa(e,{target:Uh,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:Aw(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}function Aw(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||Aw(n)))}return!1}function CI(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Ch(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>CI(n)).join(", ")}:{success:!0,data:r.value}}function AI(e){let t=fa(e,{target:Uh,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}function NI(e){let t=OI.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(o=>r.map(i=>Lt.datetime({local:n,offset:o,precision:i}))))}function jI(e,t){let r;switch(e){case"email":r=[Af()];break;case"uri":r=[ba()];break;case"date":r=[Lt.date()];break;case"date-time":r=NI(t);break}return new Set(r.map(n=>AI(n)).filter(n=>n!==void 0))}function UI(e,t,r){return r!=="zod"?!0:jI(e,t).has(t)}function ls(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function MI(e){try{return TI(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new Me(fe.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}function ng(e){return DI.has(e)||e.startsWith("x-")}function VI(e,t,r,n){if(!ls(e))return e;let o=typeof e.type=="string"&&Object.hasOwn(ew,e.type)?ew[e.type]:void 0;if(o===void 0)return e;let i={};for(let[a,s]of Object.entries(e))o.has(a)||ng(a)?i[a]=s:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?LI.has(e.format)?(typeof s!="string"||!UI(e.format,s,r))&&n.push(`${t}.${a}`):i[a]=s:n.push(`${t}.${a}`);return i}function KI(e,t){let r={},n=[];for(let[o,i]of Object.entries(e))o==="properties"&&ls(i)?r[o]=Object.fromEntries(Object.entries(i).map(([a,s])=>[a,VI(s,`properties.${a}`,t,n)])):qI.has(o)?r[o]=i:ng(o)||n.push(o);if(n.length>0)throw new Me(fe.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}function JI(e,t){if(!ls(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!nd(ts,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}function Mh(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,o)=>Mh(n,t[o],`${r}[${o}]`)):!ls(e)||!ls(t)?[]:Object.entries(e).flatMap(([n,o])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?Mh(o,t[n],i):ng(n)?[]:[i]})}function FI(e){if(!jh(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=KI(MI(e.requestedSchema),t),n=nd(qo.shape.requestedSchema,r);if(!n.success)throw new Me(fe.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${JI(r,n.error.message)}`);let o=Mh(r,n.data);if(o.length>0)throw new Me(fe.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new Me(fe.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}function HI(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}function Ow(e){return{"~standard":{version:1,vendor:"modelcontextprotocol",validate:(t,r)=>td(t)?{value:t}:e["~standard"].validate(t,r)}}}function Nw(e){return{autoFulfill:e?.autoFulfill??ZI,maxRounds:e?.maxRounds??WI}}function GI(e,t,r){let n=t!==void 0&&Object.keys(t).length>0;return!n&&r===void 0?e:{...e,...n&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function XI(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function YI(e,t){return new Promise((r,n)=>{if(t?.aborted){n(t.reason instanceof ae?t.reason:new ae(se.RequestTimeout,String(t.reason)));return}let o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(o),n(t?.reason instanceof ae?t.reason:new ae(se.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function QI(e){let t=new AbortController,r=()=>t.abort(e?.reason);return e?.addEventListener("abort",r,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:n=>t.abort(n),dispose:()=>e?.removeEventListener("abort",r)}}async function eP(e){let{config:t,method:r,originalParams:n,requestOptions:o,hooks:i,signal:a}=e,s=e.flowStartedAt??Date.now(),c=e.firstPayload,u=0;for(;;){if(u+=1,u>t.maxRounds)throw new ae(se.InputRequiredRoundsExceeded,XI(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:c.inputRequests,...c.requestState!==void 0&&{requestState:c.requestState}}});o.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let l=Object.entries(c.inputRequests??{}),d;if(l.length>0){let g=QI(a);try{let h=await Promise.all(l.map(async([f,y])=>{try{return[f,await i.dispatchInputRequest(f,y,g.signal)]}catch(S){throw g.abort(S),S}}));d=Object.fromEntries(h)}finally{g.dispose()}}else await YI(BI,a);let m={...o.timeout!==void 0&&{timeout:o.timeout}};if(o.maxTotalTimeout!==void 0){let g=Date.now()-s,h=o.maxTotalTimeout-g;if(h<=0)throw new ae(se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:o.maxTotalTimeout,totalElapsed:g});m.maxTotalTimeout=h}let v=await i.retry(GI(n,d,c.requestState),m);if(td(v)){c={inputRequests:v.inputRequests??{},...v.requestState!==void 0&&{requestState:v.requestState}};continue}return v}}function Mw(e,t){let r=e.slice(0,-6);jw[r]=t,Uw[r]=n=>t.safeParse(n).success}function nP(e){switch(e){case"initialize":case"notifications/initialized":return Er(void 0);case"server/discover":return Er(ed);default:return}}function tw(e,t){let r=e.params;if(!us(r))return{message:e,lifted:{}};let n=r._meta,o=us(n)?oP.filter(c=>c in n):[],i=t==="request"?iP.filter(c=>c in r):[];if(o.length===0&&i.length===0)return{message:e,lifted:{}};let a={},s={...r};if(o.length>0&&us(n)){let c={},u={...n};for(let l of o)c[l]=n[l],delete u[l];a.envelope=c,Object.keys(u).length>0?s._meta=u:delete s._meta}for(let c of i)c==="inputResponses"&&(a.inputResponses=s[c]),c==="requestState"&&(a.requestState=s[c]),delete s[c];return{message:{...e,params:s},lifted:a}}function rw(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let o=e.validateResult(t,n);return o.ok?{value:o.value}:{issues:[{message:o.reason==="invalid"?o.message:`not-in-era: ${t}`}]}}}}}function ig(e){return()=>e}function us(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sg(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let a=r[o];r[o]=us(a)&&us(i)?{...a,...i}:i}return r}function Yl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cP(e){let t={},r=[];if(!Yl(e))return{accepted:t,droppedKeys:r};for(let[n,o]of Object.entries(e)){if(!Yl(o)||"method"in o||"result"in o){r.push(n);continue}t[n]=o}return{accepted:t,droppedKeys:r}}function nw(e){throw new ae(se.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function uP(e,t,r,n,o){return{sessionId:o,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:ig(void 0),signal:n,send:(()=>nw("send")),notify:()=>nw("notify")}}}async function lP(e,t,r,n,o){if(!Yl(n)||typeof n.method!="string")throw new ae(se.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let i=n.method;if(!t.hasInputRequestMethod(i))throw new ae(se.InvalidResult,`Invalid input request '${r}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:i});let a=e.getRequestHandler(i);if(a===void 0)throw new ae(se.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:i});let s=Yl(n.params)?n.params:void 0;return await a({jsonrpc:"2.0",id:r,method:i,...s!==void 0&&{params:s}},e.buildContext(uP(r,i,s,o,e.sessionId)))}function dP(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function qw(e,t,r,n){let{codec:o,request:i,options:a,flowStartedAt:s}=n,c={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(l,d,m)=>lP(e,o,l,d,m),retry:(l,d)=>n.retry(l,dP(a,d))};return eP({config:t,method:i.method,originalParams:i.params,firstPayload:c,flowStartedAt:s,signal:a?.signal,requestOptions:{...a?.timeout!==void 0&&{timeout:a.timeout},...a?.maxTotalTimeout!==void 0&&{maxTotalTimeout:a.maxTotalTimeout},...a?.onprogress!==void 0&&{onprogress:a.onprogress}},hooks:u})}function pP(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}function cg(e){if(e)try{return fP.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function Lw(e){return e==="application/json"?!0:cg(e)==="application/json"}function Vw(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}function lg(e){return Bt.parse(JSON.parse(e))}function Jw(e){return JSON.stringify(e)+` +`}function ds(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function od(e=fetch,t){return t?async(r,n)=>e(r,{...t,...n,headers:n?.headers?{...ds(t.headers),...ds(n.headers)}:t.headers}):e}function Zw(){Jh(),an(),Jx(),dI(),SI()}function Ww(e,t){let r=t.getValidator(e);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>e,output:()=>e},validate:n=>{let o=r(n);return o.valid?{value:o.data}:{issues:[{message:o.errorMessage}]}}}}}var Oh,Rr,xr,se,ae,lr,sw,Vh,uw,Dx,qx,Lx,dw,pw,Kx,Zl,nD,oD,B$,Fh,Gx,Xx,Hh,fe,Me,Zh,Wh,ms,Bh,eI,tI,rI,lI,Bl,Xh,_w,iD,aD,yI,vI,Yh,Gl,ed,ww,bI,sn,Qh,qn,Vn,kw,Ew,td,Rw,rd,eg,$I,Y$,wI,zI,kI,EI,Pw,Tw,Vo,sD,cD,Q$,Uh,OI,DI,qI,ew,LI,uD,ZI,WI,BI,tP,rP,jw,Uw,Dw,og,fs,oP,iP,aP,sP,ag,mP,fP,ug,Kw,ow,Ah,iw,hP,Fw,Hw,Bw=q(()=>{cp();W$();ih();Oh=Symbol.for("mcp.sdk.errorBrands");Rr=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e})({}),xr=class aw extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Ut(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",Ln(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new aw(t.error,t.error_description??t.error,t.error_uri)}},se=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),ae=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",Ln(this,new.target)}},lr=class extends ae{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r){super(e,t,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};sw="2026-07-28",Vh=[sw];uw=["task","inputRequests","requestState"];qx=new Set(["const","enum","default","examples"]),Lx=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas"]);dw={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},pw={"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},Kx={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};nD=Object.keys(dw),oD=Object.keys(pw);B$={ok:!1,reason:"not-in-era"};Fh={era:"2025-11-25",hasRequestMethod:mw,hasNotificationMethod:fw,validateRequest:(e,t)=>Wl(Zx(e),t),validateResult:(e,t)=>Wl(Hx(e),t),validateNotification:(e,t)=>Wl(Wx(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>B$,validateInputResponse:()=>B$,samplingResultVariant:((e,t)=>{let r=Jh();return Wl(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let r=cw(e),n=r.structuredContent;if(n===void 0)return r;let o=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&lw(t);return!o&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Nh(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>G$(n))?t:{...t,tools:r.map(n=>G$(n)?{...n,outputSchema:Vx(n.outputSchema)}:n)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};Xx=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];Hh=Symbol("modelcontextprotocol.resultCacheHintFallback");fe=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),Me=class yw extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Ut(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",Ln(this,new.target)}static fromError(t,r,n){if(t===fe.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Wh(o.elicitations,r)}if(t===fe.UnsupportedProtocolVersion&&n){let o=n;if(Array.isArray(o.supported)&&typeof o.requested=="string")return new ms({supported:o.supported,requested:o.requested},r)}if(t===fe.InvalidParams||t===fe.ResourceNotFound){let o=n;if(typeof o?.uri=="string"&&(t===fe.ResourceNotFound||Object.keys(o).length===1))return new Zh(o.uri,r)}if(t===fe.MissingRequiredClientCapability&&n){let o=n;if(o.requiredCapabilities!==null&&typeof o.requiredCapabilities=="object"&&!Array.isArray(o.requiredCapabilities))return new Bh({requiredCapabilities:o.requiredCapabilities},r)}return new yw(t,r,n)}},Zh=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(fe.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Wh=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(fe.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},ms=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(fe.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Bh=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(fe.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},eI=0,tI="private",rI=["tools/call","prompts/get","resources/read"];lI=["elicitation/create","sampling/createMessage","roots/list"];Xh={"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},_w={"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};iD=Object.keys(Xh),aD=Object.keys(_w);yI={ok:!1,reason:"not-in-era"},vI=[cr,Gr];Yh={era:"2026-07-28",hasRequestMethod:Sw,hasNotificationMethod:bw,hasInputRequestMethod:e=>Ih(e)!==void 0,validateRequest:(e,t)=>as(fI(e),t),validateResult:(e,t)=>as(hI(e),t),validateNotification:(e,t)=>as(gI(e),t),validateInputRequest:(e,t)=>as(Ih(e),t),validateInputResponse:(e,t)=>as(pI(e),t),samplingResultVariant:()=>yI,outboundEnvelope(e){return{[cr]:e.protocolVersion,[On]:e.clientInfo,[Gr]:e.clientCapabilities,...e.logLevel!==void 0&&{[Nn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of vI)n in e||t.push({key:n,problem:"missing"});let r=an().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let o=n.path.map(String),i=o.length>0?o.join("."):"_meta";o.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:e=>cw(e),inputRequestSchema:Ih,decodeResult(e,t){if(!cs(t))return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,s=cs(a)?a:{},c=t.requestState;return Object.keys(s).length===0&&typeof c!="string"?{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:s,...typeof c=="string"&&{requestState:c}}}if(r!=="complete")return{kind:"invalid",error:new ae(se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=$w(),o=Object.hasOwn(n,e)?n[e]:void 0;if(o!==void 0){let a=o.safeParse(t);if(!a.success)return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return aI(oI(e,nI(e,_I(e,t))),r)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=an().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}};ed="2026-07-28";ww=[Fh,Yh],bI=Zy({AnnotationsSchema:()=>kr,AudioContentSchema:()=>No,BaseMetadataSchema:()=>zr,BaseRequestParamsSchema:()=>pt,BlobResourceContentsSchema:()=>Ka,BooleanSchemaSchema:()=>Ba,CallToolRequestParamsSchema:()=>sl,CallToolRequestSchema:()=>cl,CallToolResultSchema:()=>Uo,CancelTaskRequestSchema:()=>_h,CancelTaskResultSchema:()=>Sh,CancelledNotificationParamsSchema:()=>mu,CancelledNotificationSchema:()=>Na,ClientCapabilitiesSchema:()=>yu,ClientNotificationSchema:()=>$h,ClientRequestSchema:()=>bh,ClientResultSchema:()=>wh,ClientTasksCapabilitySchema:()=>hu,CompatibilityCallToolResultSchema:()=>uh,CompleteRequestParamsSchema:()=>Nl,CompleteRequestSchema:()=>jl,CompleteResultSchema:()=>Ul,ContentBlockSchema:()=>jo,CreateMessageRequestParamsSchema:()=>Sl,CreateMessageRequestSchema:()=>bl,CreateMessageResultSchema:()=>$l,CreateMessageResultWithToolsSchema:()=>wl,CreateTaskResultSchema:()=>dh,CursorSchema:()=>Ia,DiscoverRequestSchema:()=>Su,DiscoverResultSchema:()=>jn,ElicitRequestFormParamsSchema:()=>qo,ElicitRequestParamsSchema:()=>xl,ElicitRequestSchema:()=>Il,ElicitRequestURLParamsSchema:()=>Rl,ElicitResultSchema:()=>Cl,ElicitationCompleteNotificationParamsSchema:()=>Pl,ElicitationCompleteNotificationSchema:()=>Tl,EmbeddedResourceSchema:()=>Yu,EmptyResultSchema:()=>Oa,EnumSchemaSchema:()=>El,GetPromptRequestParamsSchema:()=>Bu,GetPromptRequestSchema:()=>Gu,GetPromptResultSchema:()=>tl,GetTaskPayloadRequestSchema:()=>hh,GetTaskPayloadResultSchema:()=>gh,GetTaskRequestSchema:()=>mh,GetTaskResultSchema:()=>fh,IconSchema:()=>fu,IconsSchema:()=>en,ImageContentSchema:()=>Oo,ImplementationSchema:()=>To,InitializeRequestParamsSchema:()=>vu,InitializeRequestSchema:()=>ja,InitializeResultSchema:()=>_u,InitializedNotificationSchema:()=>Ma,JSONArraySchema:()=>sh,JSONObjectSchema:()=>Ge,JSONRPCErrorResponseSchema:()=>Po,JSONRPCMessageSchema:()=>Bt,JSONRPCNotificationSchema:()=>Aa,JSONRPCRequestSchema:()=>Ca,JSONRPCResponseSchema:()=>pu,JSONRPCResultResponseSchema:()=>Io,JSONValueSchema:()=>Wr,LegacyTitledEnumSchemaSchema:()=>Ya,ListChangedOptionsBaseSchema:()=>Za,ListPromptsRequestSchema:()=>Zu,ListPromptsResultSchema:()=>Wu,ListResourceTemplatesRequestSchema:()=>Ru,ListResourceTemplatesResultSchema:()=>xu,ListResourcesRequestSchema:()=>ku,ListResourcesResultSchema:()=>Eu,ListRootsRequestSchema:()=>Dl,ListRootsResultSchema:()=>ql,ListTasksRequestSchema:()=>yh,ListTasksResultSchema:()=>vh,ListToolsRequestSchema:()=>il,ListToolsResultSchema:()=>al,LoggingLevelSchema:()=>Wa,LoggingMessageNotificationParamsSchema:()=>pl,LoggingMessageNotificationSchema:()=>ml,ModelHintSchema:()=>fl,ModelPreferencesSchema:()=>hl,MultiSelectEnumSchemaSchema:()=>kl,NotificationSchema:()=>bt,NotificationsParamsSchema:()=>St,NumberSchemaSchema:()=>Do,PaginatedRequestParamsSchema:()=>wu,PaginatedRequestSchema:()=>tn,PaginatedResultSchema:()=>rn,PingRequestSchema:()=>Da,PrimitiveSchemaDefinitionSchema:()=>ts,ProgressNotificationParamsSchema:()=>$u,ProgressNotificationSchema:()=>qa,ProgressSchema:()=>bu,ProgressTokenSchema:()=>xa,PromptArgumentSchema:()=>Fu,PromptListChangedNotificationSchema:()=>rl,PromptMessageSchema:()=>el,PromptReferenceSchema:()=>Ol,PromptSchema:()=>Hu,ReadResourceRequestParamsSchema:()=>Iu,ReadResourceRequestSchema:()=>Pu,ReadResourceResultSchema:()=>Tu,RelatedTaskMetadataSchema:()=>du,RequestIdSchema:()=>Qr,RequestMetaSchema:()=>Pa,RequestSchema:()=>Xe,ResourceContentsSchema:()=>La,ResourceLinkSchema:()=>Qu,ResourceListChangedNotificationSchema:()=>Cu,ResourceRequestParamsSchema:()=>Co,ResourceSchema:()=>Ja,ResourceTemplateReferenceSchema:()=>Al,ResourceTemplateSchema:()=>zu,ResourceUpdatedNotificationParamsSchema:()=>Ku,ResourceUpdatedNotificationSchema:()=>Ju,ResultMetaObjectSchema:()=>Ta,ResultSchema:()=>Ye,RoleSchema:()=>nn,RootSchema:()=>Ml,RootsListChangedNotificationSchema:()=>Ll,SamplingContentSchema:()=>vl,SamplingMessageContentBlockSchema:()=>An,SamplingMessageSchema:()=>_l,ServerCapabilitiesSchema:()=>Ua,ServerNotificationSchema:()=>kh,ServerRequestSchema:()=>zh,ServerResultSchema:()=>Eh,ServerTasksCapabilitySchema:()=>gu,SetLevelRequestParamsSchema:()=>ll,SetLevelRequestSchema:()=>dl,SingleSelectEnumSchemaSchema:()=>zl,StringSchemaSchema:()=>Mo,SubscribeRequestParamsSchema:()=>Au,SubscribeRequestSchema:()=>Ou,SubscriptionFilterSchema:()=>Fa,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Du,SubscriptionsAcknowledgedNotificationSchema:()=>qu,SubscriptionsListenRequestParamsSchema:()=>Uu,SubscriptionsListenRequestSchema:()=>Mu,SubscriptionsListenResultMetaSchema:()=>Lu,SubscriptionsListenResultSchema:()=>Vu,TaskAugmentedRequestParamsSchema:()=>Yr,TaskCreationParamsSchema:()=>lh,TaskMetadataSchema:()=>lu,TaskSchema:()=>on,TaskStatusNotificationParamsSchema:()=>Kl,TaskStatusNotificationSchema:()=>ph,TaskStatusSchema:()=>Vl,TextContentSchema:()=>Ao,TextResourceContentsSchema:()=>Va,TitledMultiSelectEnumSchemaSchema:()=>es,TitledSingleSelectEnumSchemaSchema:()=>Xa,ToolAnnotationsSchema:()=>nl,ToolChoiceSchema:()=>gl,ToolExecutionSchema:()=>ol,ToolListChangedNotificationSchema:()=>ul,ToolResultContentSchema:()=>yl,ToolSchema:()=>Ha,ToolUseContentSchema:()=>Xu,UnsubscribeRequestParamsSchema:()=>Nu,UnsubscribeRequestSchema:()=>ju,UntitledMultiSelectEnumSchemaSchema:()=>Qa,UntitledSingleSelectEnumSchemaSchema:()=>Ga});sn=e=>Ca.safeParse(e).success,Qh=e=>Aa.safeParse(e).success,qn=e=>Io.safeParse(e).success,Vn=e=>Po.safeParse(e).success,kw=e=>pu.safeParse(e).success,Ew=e=>typeof e!="object"||e===null||e.content===void 0?!1:Uo.safeParse(e).success,td=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required",Rw=e=>Yr.safeParse(e).success,rd=e=>ja.safeParse(e).success,eg=e=>Ma.safeParse(e).success;$I="Mcp-Param-",Y$="x-mcp-header",wI=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zI=new Set(["string","integer","boolean","number"]);kI=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],EI=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);Pw="=?base64?",Tw="?=";Vo=-32020,sD=[{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:[fe.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:[Vo,fe.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:[fe.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[fe.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[fe.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:[Vo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[fe.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Vo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],cD={[fe.ParseError]:400,[fe.InvalidRequest]:400,[fe.MethodNotFound]:404,[fe.UnsupportedProtocolVersion]:400,[fe.MissingRequiredClientCapability]:400,[Vo]:400};Q$=!1,Uh="draft-2020-12";OI=/\\\.\\d\{(\d+)\}/;DI=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);qI=new Set(["$schema",...Object.keys(qo.shape.requestedSchema.shape)]),ew={string:ss([Mo,Ga,Xa,Ya]),number:ss([Do]),integer:ss([Do]),boolean:ss([Ba]),array:ss([Qa,es])},LI=new Set(Mo.shape.format.unwrap().options);uD=Object.assign(HI,{elicit(e){try{return{method:"elicitation/create",params:FI(e)}}catch(t){throw t instanceof Me?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});ZI=!0,WI=10,BI=250;tP=["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"],rP={IdJagTokenExchangeResponseSchema:os,OAuthClientInformationFullSchema:is,OAuthClientInformationSchema:Hl,OAuthClientMetadataSchema:Fl,OAuthClientRegistrationErrorSchema:Rh,OAuthErrorResponseSchema:Mn,OAuthMetadataSchema:Un,OAuthProtectedResourceMetadataSchema:rs,OAuthTokenRevocationRequestSchema:xh,OAuthTokensSchema:Lo,OpenIdProviderDiscoveryMetadataSchema:ns,OpenIdProviderMetadataSchema:Jl},jw={},Uw={};for(let e of tP)Mw(e,bI[e]);for(let[e,t]of Object.entries(rP))Mw(e,t);Dw=Object.freeze(jw),og=Object.freeze(Uw);fs=6e4,oP=[cr,On,Gr,Nn],iP=["inputResponses","requestState"];aP=ig(void 0),ag=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{sP=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ea,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new ae(se.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new ae(se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),qn(o)||Vn(o)?this._onresponse(o):sn(o)?this._onrequest(o,i):Qh(o)?this._onnotification(o,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new ae(se.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=tw(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=X$(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(Th(r.method)&&!n.hasNotificationMethod(r.method))return;let o=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;o===void 0&&i===void 0||Promise.resolve().then(()=>o===void 0?i(r):o(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=tw(e,"request"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=(h,f,y)=>{let S={jsonrpc:"2.0",id:r.id,error:{code:h,message:f,...y!==void 0&&{data:y}}};i?.send(S).catch(_=>this._onerror(new Error(`Failed to send an error response: ${_}`)))};if(t?.classification!==void 0){let h=X$(t.classification);if(h!==o.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${h} but this instance serves ${o.era}`));let f=t.classification.revision??h;a(fe.UnsupportedProtocolVersion,`Unsupported protocol version: ${f}`,{supported:this._supportedProtocolVersions,requested:f});return}}if(Ph(r.method)&&!o.hasRequestMethod(r.method)){a(fe.MethodNotFound,"Method not found");return}let s=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(s===void 0){a(fe.MethodNotFound,"Method not found");return}let c=o.checkInboundEnvelope(n);if(c!==void 0){a(fe.InvalidParams,c);return}let u=(h,f)=>this._notificationViaCodec(this._resolveOutboundCodec(h.method),h,{...f,relatedRequestId:r.id}),l=(h,f,y)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(h.method),h,f,{...y,relatedRequestId:r.id}),d=new AbortController;this._requestHandlerAbortControllers.set(r.id,d);let m=n.inputResponses===void 0?void 0:cP(n.inputResponses),v={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...m!==void 0&&{inputResponses:m.accepted},...m!==void 0&&m.droppedKeys.length>0&&{droppedInputResponseKeys:m.droppedKeys},requestState:n.requestState===void 0?aP:ig(n.requestState),signal:d.signal,send:((h,f,y)=>{let S=this._resolveOutboundCodec(h.method);if(this._assertOutboundRequestInEra(S,h.method),jh(f))return l(h,f,y);let _=rw(S,h.method);if(_===void 0)throw new TypeError(`'${h.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return l(h,_,f)}),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},g=this.buildContext(v,t);Promise.resolve().then(()=>s(r,g)).then(async h=>{if(d.signal.aborted)return;let f;try{f=o.encodeResult(r.method,h,this._outboundServerInfo())}catch(S){this._onerror(new Error(`Failed to encode result for ${r.method}: ${S}`)),a(fe.InternalError,"Internal error");return}let y={result:f,jsonrpc:"2.0",id:r.id};await i?.send(y)},async h=>{if(d.signal.aborted)return;let f=Number.isSafeInteger(h.code)?h.code:fe.InternalError,y={jsonrpc:"2.0",id:r.id,error:{code:o.encodeErrorCode(f),message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};await i?.send(y)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===d&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(s){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(s);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),qn(e)?r(e):r(Me.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(n,e.method),jh(t))return this._requestWithSchemaViaCodec(n,e,t,r);let o=rw(n,e.method);if(o===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,o,t)}_negotiatedWireCodec(){return Er(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=nP(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Ph(t)&&!e.hasRequestMethod(t))throw new ae(se.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:s}=n??{},c=Date.now(),u,l;return new Promise((d,m)=>{let v=w=>{m(w)};if(!this._transport){v(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){v(w);return}if(n?.signal?.aborted){let w=n.signal.reason;throw w instanceof ae?w:new ae(se.RequestTimeout,String(w))}let g=e.era===ed&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;l=h;let f={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let y=this._envelopeOutbound(f),S=!1,_=w=>{S||(this._progressHandlers.delete(h),g===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(w)}}),{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`))):g.abort(),m(w instanceof ae?w:new ae(se.RequestTimeout,String(w))))};this._responseHandlers.set(h,w=>{if(n?.signal?.aborted)return;if(S=!0,w instanceof Error)return m(w);let b;try{b=e.decodeResult(t.method,w.result)}catch(j){return m(j instanceof Error?j:new Error(String(j)))}if(b.kind==="invalid")return m(b.error);if(b.kind==="input_required"){if(n?.allowInputRequired===!0)return d(pP(b));let j={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:c,retry:(V,A)=>this._requestWithSchemaViaCodec(e,V===void 0?{method:t.method}:{method:t.method,params:V},r,A)};return d(this._resolveNonCompleteResult(b,j))}let E=b.result;Ch(r,E).then(j=>{j.success?d(j.data):m(new ae(se.InvalidResult,`Invalid result for ${t.method}: ${j.error}`))},m)}),u=()=>_(n?.signal?.reason),n?.signal?.addEventListener("abort",u,{once:!0});let $=n?.timeout??fs,k=()=>_(new ae(se.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(h,$,n?.maxTotalTimeout,k,n?.resetTimeoutOnProgress??!1),this._transport.send(y,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:s,requestSignal:g?.signal}).catch(w=>{this._progressHandlers.delete(h),m(w)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),l!==void 0&&(this._responseHandlers.delete(l),this._cleanupTimeout(l))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new ae(se.NotConnected,"Not connected");if(Th(t.method)&&!e.hasNotificationMethod(t.method))throw new ae(se.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(o=>this._onerror(o))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Ph(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(o,i)=>{let a=this._negotiatedWireCodec(),s=a.validateRequest(e,o);if(!s.ok&&s.reason==="not-in-era"&&(s=a.validateInputRequest(e,o)),!s.ok)throw s.reason==="not-in-era"?new Me(fe.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value,i))}}else if(r)n=async(o,i)=>{let a=await Ch(t.params,{...o.params});if(!a.success)throw new Me(fe.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)};else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!Th(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,o)=>{let i=o.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new Me(fe.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let o=await Ch(t.params,{...n.params});if(!o.success)throw new Me(fe.InvalidParams,`Invalid params for notification ${e}: ${o.error}`);await r(o.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};mP=H((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=o;function o(s){if(!s)throw new TypeError("argument string is required");var c=typeof s=="object"?i(s):s;if(typeof c!="string")throw new TypeError("argument string is required to be a string");var u=c.indexOf(";"),l=u!==-1?c.slice(0,u).trim():c.trim();if(!n.test(l))throw new TypeError("invalid media type");var d=new a(l.toLowerCase());if(u!==-1){var m,v,g;for(t.lastIndex=u;v=t.exec(c);){if(v.index!==u)throw new TypeError("invalid parameter format");u+=v[0].length,m=v[1].toLowerCase(),g=v[2],g.charCodeAt(0)===34&&(g=g.slice(1,-1),g.indexOf("\\")!==-1&&(g=g.replace(r,"$1"))),d.parameters[m]=g}if(u!==c.length)throw new TypeError("invalid parameter format")}return d}function i(s){var c;if(typeof s.getHeader=="function"?c=s.getHeader("content-type"):typeof s.headers=="object"&&(c=s.headers&&s.headers["content-type"]),typeof c!="string")throw new TypeError("content-type header is missing from object");return c}function a(s){this.parameters=Object.create(null),this.type=s}})),fP=cc(mP(),1);ug=10*1024*1024,Kw=class{_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??ug}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(` +`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");this._buffer=this._buffer.subarray(e+1);try{return lg(t)}catch(r){if(r instanceof SyntaxError)continue;throw r}}return null}clear(){this._buffer=void 0}};ow=1e6,Ah=1e6,iw=1e4,hP=1e6,Fw=class Dn{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,n){if(t.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${t.length})`)}template;parts;get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){Dn.validateLength(t,ow,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let r=[],n="",o=0,i=0;for(;oiw)throw new Error(`Template contains too many expressions (max ${iw})`);let s=t.slice(o+1,a),c=this.getOperator(s),u=s.includes("*"),l=this.getNames(s),d=l[0];for(let m of l)Dn.validateLength(m,Ah,"Variable name");r.push({name:d,operator:c,names:l,exploded:u}),o=a+1}else n+=t[o],o++;return n&&r.push(n),r}getOperator(t){return["+","#",".","/","?","&"].find(r=>t.startsWith(r))||""}getNames(t){let r=this.getOperator(t);return t.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,r){return Dn.validateLength(t,Ah,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){let i=t.names.map(a=>{let s=r[a];return s===void 0?"":`${a}=${Array.isArray(s)?s.map(c=>this.encodeValue(c,t.operator)).join(","):this.encodeValue(s.toString(),t.operator)}`}).filter(a=>a.length>0);return i.length===0?"":(t.operator==="?"?"?":"&")+i.join("&")}if(t.names.length>1){let i=t.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[t.name];if(n===void 0)return"";let o=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,t.operator));switch(t.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(t){let r="",n=!1;for(let o of this.parts){if(typeof o=="string"){r+=o;continue}let i=this.expandPart(o,t);i&&(r+=(o.operator==="?"||o.operator==="&")&&n?i.replace("?","&"):i,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(t){return t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let r=[];for(let i of t.names)Dn.validateLength(i,Ah,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let i=0;i0;){let t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){if(this._closed)return;this._closed=!0;let t=this._otherTransport;this._otherTransport=void 0;try{await t?.close()}finally{this.onclose?.()}}async send(t,r){if(!this._otherTransport)throw new ae(se.NotConnected,"Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}});function xT(){let e=new zT.Ajv2020({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return RT(e),e}var ad,Gw,ze,Te,Gt,cd,gP,Xw,Yw,sd,yP,Xt,vP,_P,Qw,SP,ud,hs,ld,gs,dd,bP,ez,$P,wP,zP,tz,kP,dg,rz,EP,RP,xP,IP,PP,TP,CP,AP,pg,OP,NP,jP,nz,oz,iz,UP,MP,DP,mg,qP,az,LP,VP,KP,JP,FP,HP,ZP,WP,sz,BP,cz,uz,GP,XP,lz,YP,dz,pz,mz,QP,eT,tT,rT,nT,oT,iT,aT,sT,cT,uT,lT,dT,pT,mT,fT,hT,gT,yT,vT,_T,ST,bT,$T,wT,zT,kT,ET,RT,pd,SD,fz=q(()=>{cp();ad=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var r=class extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=r;var n=class extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((S,_)=>`${S}${_}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((S,_)=>(_ instanceof r&&(S[_.str]=(S[_.str]||0)+1),S),{})}};e._Code=n,e.nil=new n("");function o(y,...S){let _=[y[0]],$=0;for(;${Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=ad();var r=class extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}},n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};var o=class{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){let u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,l;if(!((l=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||l===void 0)&&l.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}};e.Scope=o;var i=class extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:l}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${l}]`}};e.ValueScopeName=i;let a=(0,t._)`\n`;var s=class extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new i(c,this._newName(c))}value(c,u){var l;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let d=this.toName(c),{prefix:m}=d,v=(l=u.key)!==null&&l!==void 0?l:u.ref,g=this._values[m];if(g){let y=g.get(v);if(y)return y}else g=this._values[m]=new Map;g.set(v,d);let h=this._scope[m]||(this._scope[m]=[]),f=h.length;return h[f]=u.ref,d.setValue(u,{property:m,itemIndex:f}),d}getValue(c,u){let l=this._values[c];if(l)return l.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,l=>{if(l.scopePath===void 0)throw new Error(`CodeGen: name "${l}" has no value`);return(0,t._)`${c}${l.scopePath}`})}scopeCode(c=this._values,u,l){return this._reduceValues(c,d=>{if(d.value===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return d.value.code},u,l)}_reduceValues(c,u,l={},d){let m=t.nil;for(let v in c){let g=c[v];if(!g)continue;let h=l[v]=l[v]||new Map;g.forEach(f=>{if(h.has(f))return;h.set(f,n.Started);let y=u(f);if(y){let S=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${S} ${f} = ${y};${this.opts._n}`}else if(y=d?.(f))m=(0,t._)`${m}${y}${this.opts._n}`;else throw new r(f);h.set(f,n.Completed)})}return m}};e.ValueScope=s})),ze=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=ad(),r=Gw();var n=ad();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=Gw();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};var i=class{optimizeNodes(){return this}optimizeNames(z,I){return this}},a=class extends i{constructor(z,I,O){super(),this.varKind=z,this.name=I,this.rhs=O}render({es5:z,_n:I}){let O=z?r.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${W};`+I}optimizeNames(z,I){if(z[this.name.str])return this.rhs&&(this.rhs=J(this.rhs,z,I)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends i{constructor(z,I,O){super(),this.lhs=z,this.rhs=I,this.sideEffects=O}render({_n:z}){return`${this.lhs} = ${this.rhs};`+z}optimizeNames(z,I){if(!(this.lhs instanceof t.Name&&!z[this.lhs.str]&&!this.sideEffects))return this.rhs=J(this.rhs,z,I),this}get names(){return Z(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(z,I,O,W){super(z,O,W),this.op=I}render({_n:z}){return`${this.lhs} ${this.op}= ${this.rhs};`+z}},u=class extends i{constructor(z){super(),this.label=z,this.names={}}render({_n:z}){return`${this.label}:`+z}},l=class extends i{constructor(z){super(),this.label=z,this.names={}}render({_n:z}){return`break${this.label?` ${this.label}`:""};`+z}},d=class extends i{constructor(z){super(),this.error=z}render({_n:z}){return`throw ${this.error};`+z}get names(){return this.error.names}},m=class extends i{constructor(z){super(),this.code=z}render({_n:z}){return`${this.code};`+z}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(z,I){return this.code=J(this.code,z,I),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},v=class extends i{constructor(z=[]){super(),this.nodes=z}render(z){return this.nodes.reduce((I,O)=>I+O.render(z),"")}optimizeNodes(){let{nodes:z}=this,I=z.length;for(;I--;){let O=z[I].optimizeNodes();Array.isArray(O)?z.splice(I,1,...O):O?z[I]=O:z.splice(I,1)}return z.length>0?this:void 0}optimizeNames(z,I){let{nodes:O}=this,W=O.length;for(;W--;){let ce=O[W];ce.optimizeNames(z,I)||(te(z,ce.names),O.splice(W,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((z,I)=>L(z,I.names),{})}},g=class extends v{render(z){return"{"+z._n+super.render(z)+"}"+z._n}},h=class extends v{},f=class extends g{};f.kind="else";var y=class id extends g{constructor(I,O){super(O),this.condition=I}render(I){let O=`if(${this.condition})`+super.render(I);return this.else&&(O+="else "+this.else.render(I)),O}optimizeNodes(){super.optimizeNodes();let I=this.condition;if(I===!0)return this.nodes;let O=this.else;if(O){let W=O.optimizeNodes();O=this.else=Array.isArray(W)?new f(W):W}if(O)return I===!1?O instanceof id?O:O.nodes:this.nodes.length?this:new id(_e(I),O instanceof id?[O]:O.nodes);if(!(I===!1||!this.nodes.length))return this}optimizeNames(I,O){var W;if(this.else=(W=this.else)===null||W===void 0?void 0:W.optimizeNames(I,O),!!(super.optimizeNames(I,O)||this.else))return this.condition=J(this.condition,I,O),this}get names(){let I=super.names;return Z(I,this.condition),this.else&&L(I,this.else.names),I}};y.kind="if";var S=class extends g{};S.kind="for";var _=class extends S{constructor(z){super(),this.iteration=z}render(z){return`for(${this.iteration})`+super.render(z)}optimizeNames(z,I){if(super.optimizeNames(z,I))return this.iteration=J(this.iteration,z,I),this}get names(){return L(super.names,this.iteration.names)}},$=class extends S{constructor(z,I,O,W){super(),this.varKind=z,this.name=I,this.from=O,this.to=W}render(z){let I=z.es5?r.varKinds.var:this.varKind,{name:O,from:W,to:ce}=this;return`for(${I} ${O}=${W}; ${O}<${ce}; ${O}++)`+super.render(z)}get names(){return Z(Z(super.names,this.from),this.to)}},k=class extends S{constructor(z,I,O,W){super(),this.loop=z,this.varKind=I,this.name=O,this.iterable=W}render(z){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(z)}optimizeNames(z,I){if(super.optimizeNames(z,I))return this.iterable=J(this.iterable,z,I),this}get names(){return L(super.names,this.iterable.names)}},w=class extends g{constructor(z,I,O){super(),this.name=z,this.args=I,this.async=O}render(z){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(z)}};w.kind="func";var b=class extends v{render(z){return"return "+super.render(z)}};b.kind="return";var E=class extends g{render(z){let I="try"+super.render(z);return this.catch&&(I+=this.catch.render(z)),this.finally&&(I+=this.finally.render(z)),I}optimizeNodes(){var z,I;return super.optimizeNodes(),(z=this.catch)===null||z===void 0||z.optimizeNodes(),(I=this.finally)===null||I===void 0||I.optimizeNodes(),this}optimizeNames(z,I){var O,W;return super.optimizeNames(z,I),(O=this.catch)===null||O===void 0||O.optimizeNames(z,I),(W=this.finally)===null||W===void 0||W.optimizeNames(z,I),this}get names(){let z=super.names;return this.catch&&L(z,this.catch.names),this.finally&&L(z,this.finally.names),z}},j=class extends g{constructor(z){super(),this.error=z}render(z){return`catch(${this.error})`+super.render(z)}};j.kind="catch";var V=class extends g{render(z){return"finally"+super.render(z)}};V.kind="finally";var A=class{constructor(z,I={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...I,_n:I.lines?` +`:""},this._extScope=z,this._scope=new r.Scope({parent:z}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(z){return this._scope.name(z)}scopeName(z){return this._extScope.name(z)}scopeValue(z,I){let O=this._extScope.value(z,I);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(z,I){return this._extScope.getValue(z,I)}scopeRefs(z){return this._extScope.scopeRefs(z,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(z,I,O,W){let ce=this._scope.toName(I);return O!==void 0&&W&&(this._constants[ce.str]=O),this._leafNode(new a(z,ce,O)),ce}const(z,I,O){return this._def(r.varKinds.const,z,I,O)}let(z,I,O){return this._def(r.varKinds.let,z,I,O)}var(z,I,O){return this._def(r.varKinds.var,z,I,O)}assign(z,I,O){return this._leafNode(new s(z,I,O))}add(z,I){return this._leafNode(new c(z,e.operators.ADD,I))}code(z){return typeof z=="function"?z():z!==t.nil&&this._leafNode(new m(z)),this}object(...z){let I=["{"];for(let[O,W]of z)I.length>1&&I.push(","),I.push(O),(O!==W||this.opts.es5)&&(I.push(":"),(0,t.addCodeArg)(I,W));return I.push("}"),new t._Code(I)}if(z,I,O){if(this._blockNode(new y(z)),I&&O)this.code(I).else().code(O).endIf();else if(I)this.code(I).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(z){return this._elseNode(new y(z))}else(){return this._elseNode(new f)}endIf(){return this._endBlockNode(y,f)}_for(z,I){return this._blockNode(z),I&&this.code(I).endFor(),this}for(z,I){return this._for(new _(z),I)}forRange(z,I,O,W,ce=this.opts.es5?r.varKinds.var:r.varKinds.let){let $e=this._scope.toName(z);return this._for(new $(ce,$e,I,O),()=>W($e))}forOf(z,I,O,W=r.varKinds.const){let ce=this._scope.toName(z);if(this.opts.es5){let $e=I instanceof t.Name?I:this.var("_arr",I);return this.forRange("_i",0,(0,t._)`${$e}.length`,B=>{this.var(ce,(0,t._)`${$e}[${B}]`),O(ce)})}return this._for(new k("of",W,ce,I),()=>O(ce))}forIn(z,I,O,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(z,(0,t._)`Object.keys(${I})`,O);let ce=this._scope.toName(z);return this._for(new k("in",W,ce,I),()=>O(ce))}endFor(){return this._endBlockNode(S)}label(z){return this._leafNode(new u(z))}break(z){return this._leafNode(new l(z))}return(z){let I=new b;if(this._blockNode(I),this.code(z),I.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(b)}try(z,I,O){if(!I&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');let W=new E;if(this._blockNode(W),this.code(z),I){let ce=this.name("e");this._currNode=W.catch=new j(ce),I(ce)}return O&&(this._currNode=W.finally=new V,this.code(O)),this._endBlockNode(j,V)}throw(z){return this._leafNode(new d(z))}block(z,I){return this._blockStarts.push(this._nodes.length),z&&this.code(z).endBlock(I),this}endBlock(z){let I=this._blockStarts.pop();if(I===void 0)throw new Error("CodeGen: not in self-balancing block");let O=this._nodes.length-I;if(O<0||z!==void 0&&O!==z)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${z} expected`);return this._nodes.length=I,this}func(z,I=t.nil,O,W){return this._blockNode(new w(z,I,O)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(w)}optimize(z=1){for(;z-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(z){return this._currNode.nodes.push(z),this}_blockNode(z){this._currNode.nodes.push(z),this._nodes.push(z)}_endBlockNode(z,I){let O=this._currNode;if(O instanceof z||I&&O instanceof I)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${I?`${z.kind}/${I.kind}`:z.kind}"`)}_elseNode(z){let I=this._currNode;if(!(I instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=I.else=z,this}get _root(){return this._nodes[0]}get _currNode(){let z=this._nodes;return z[z.length-1]}set _currNode(z){let I=this._nodes;I[I.length-1]=z}};e.CodeGen=A;function L(z,I){for(let O in I)z[O]=(z[O]||0)+(I[O]||0);return z}function Z(z,I){return I instanceof t._CodeOrName?L(z,I.names):z}function J(z,I,O){if(z instanceof t.Name)return W(z);if(!ce(z))return z;return new t._Code(z._items.reduce(($e,B)=>(B instanceof t.Name&&(B=W(B)),B instanceof t._Code?$e.push(...B._items):$e.push(B),$e),[]));function W($e){let B=O[$e.str];return B===void 0||I[$e.str]!==1?$e:(delete I[$e.str],B)}function ce($e){return $e instanceof t._Code&&$e._items.some(B=>B instanceof t.Name&&I[B.str]===1&&O[B.str]!==void 0)}}function te(z,I){for(let O in I)z[O]=(z[O]||0)-(I[O]||0)}function _e(z){return typeof z=="boolean"||typeof z=="number"||z===null?!z:(0,t._)`!${K(z)}`}e.not=_e;let ke=M(e.operators.AND);function Ne(...z){return z.reduce(ke)}e.and=Ne;let be=M(e.operators.OR);function P(...z){return z.reduce(be)}e.or=P;function M(z){return(I,O)=>I===t.nil?O:O===t.nil?I:(0,t._)`${K(I)} ${z} ${K(O)}`}function K(z){return z instanceof t.Name?z:(0,t._)`(${z})`}})),Te=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=ze(),r=ad();function n(w){let b={};for(let E of w)b[E]=!0;return b}e.toHash=n;function o(w,b){return typeof b=="boolean"?b:Object.keys(b).length===0?!0:(i(w,b),!a(b,w.self.RULES.all))}e.alwaysValidSchema=o;function i(w,b=w.schema){let{opts:E,self:j}=w;if(!E.strictSchema||typeof b=="boolean")return;let V=j.RULES.keywords;for(let A in b)V[A]||k(w,`unknown keyword: "${A}"`)}e.checkUnknownRules=i;function a(w,b){if(typeof w=="boolean")return!w;for(let E in w)if(b[E])return!0;return!1}e.schemaHasRules=a;function s(w,b){if(typeof w=="boolean")return!w;for(let E in w)if(E!=="$ref"&&b.all[E])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:w,schemaPath:b},E,j,V){if(!V){if(typeof E=="number"||typeof E=="boolean")return E;if(typeof E=="string")return(0,t._)`${E}`}return(0,t._)`${w}${b}${(0,t.getProperty)(j)}`}e.schemaRefOrVal=c;function u(w){return m(decodeURIComponent(w))}e.unescapeFragment=u;function l(w){return encodeURIComponent(d(w))}e.escapeFragment=l;function d(w){return typeof w=="number"?`${w}`:w.replace(/~/g,"~0").replace(/\//g,"~1")}e.escapeJsonPointer=d;function m(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}e.unescapeJsonPointer=m;function v(w,b){if(Array.isArray(w))for(let E of w)b(E);else b(w)}e.eachItem=v;function g({mergeNames:w,mergeToName:b,mergeValues:E,resultToName:j}){return(V,A,L,Z)=>{let J=L===void 0?A:L instanceof t.Name?(A instanceof t.Name?w(V,A,L):b(V,A,L),L):A instanceof t.Name?(b(V,L,A),A):E(A,L);return Z===t.Name&&!(J instanceof t.Name)?j(V,J):J}}e.mergeEvaluated={props:g({mergeNames:(w,b,E)=>w.if((0,t._)`${E} !== true && ${b} !== undefined`,()=>{w.if((0,t._)`${b} === true`,()=>w.assign(E,!0),()=>w.assign(E,(0,t._)`${E} || {}`).code((0,t._)`Object.assign(${E}, ${b})`))}),mergeToName:(w,b,E)=>w.if((0,t._)`${E} !== true`,()=>{b===!0?w.assign(E,!0):(w.assign(E,(0,t._)`${E} || {}`),f(w,E,b))}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:h}),items:g({mergeNames:(w,b,E)=>w.if((0,t._)`${E} !== true && ${b} !== undefined`,()=>w.assign(E,(0,t._)`${b} === true ? true : ${E} > ${b} ? ${E} : ${b}`)),mergeToName:(w,b,E)=>w.if((0,t._)`${E} !== true`,()=>w.assign(E,b===!0?!0:(0,t._)`${E} > ${b} ? ${E} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function h(w,b){if(b===!0)return w.var("props",!0);let E=w.var("props",(0,t._)`{}`);return b!==void 0&&f(w,E,b),E}e.evaluatedPropsToName=h;function f(w,b,E){Object.keys(E).forEach(j=>w.assign((0,t._)`${b}${(0,t.getProperty)(j)}`,!0))}e.setEvaluated=f;let y={};function S(w,b){return w.scopeValue("func",{ref:b,code:y[b.code]||(y[b.code]=new r._Code(b.code))})}e.useFunc=S;var _;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(_||(e.Type=_={}));function $(w,b,E){if(w instanceof t.Name){let j=b===_.Num;return E?j?(0,t._)`"[" + ${w} + "]"`:(0,t._)`"['" + ${w} + "']"`:j?(0,t._)`"/" + ${w}`:(0,t._)`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return E?(0,t.getProperty)(w).toString():"/"+d(w)}e.getErrorPath=$;function k(w,b,E=w.opts.strictSchema){if(E){if(b=`strict mode: ${b}`,E===!0)throw new Error(b);w.self.logger.warn(b)}}e.checkStrictMode=k})),Gt=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};e.default=r})),cd=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=ze(),r=Te(),n=Gt();e.keywordError={message:({keyword:f})=>(0,t.str)`must pass "${f}" keyword validation`},e.keyword$DataError={message:({keyword:f,schemaType:y})=>y?(0,t.str)`"${f}" keyword must be ${y} ($data)`:(0,t.str)`"${f}" keyword is invalid ($data)`};function o(f,y=e.keywordError,S,_){let{it:$}=f,{gen:k,compositeRule:w,allErrors:b}=$,E=d(f,y,S);_??(w||b)?c(k,E):u($,(0,t._)`[${E}]`)}e.reportError=o;function i(f,y=e.keywordError,S){let{it:_}=f,{gen:$,compositeRule:k,allErrors:w}=_;c($,d(f,y,S)),k||w||u(_,n.default.vErrors)}e.reportExtraError=i;function a(f,y){f.assign(n.default.errors,y),f.if((0,t._)`${n.default.vErrors} !== null`,()=>f.if(y,()=>f.assign((0,t._)`${n.default.vErrors}.length`,y),()=>f.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:f,keyword:y,schemaValue:S,data:_,errsCount:$,it:k}){if($===void 0)throw new Error("ajv implementation error");let w=f.name("err");f.forRange("i",$,n.default.errors,b=>{f.const(w,(0,t._)`${n.default.vErrors}[${b}]`),f.if((0,t._)`${w}.instancePath === undefined`,()=>f.assign((0,t._)`${w}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),f.assign((0,t._)`${w}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${y}`),k.opts.verbose&&(f.assign((0,t._)`${w}.schema`,S),f.assign((0,t._)`${w}.data`,_))})}e.extendErrors=s;function c(f,y){let S=f.const("err",y);f.if((0,t._)`${n.default.vErrors} === null`,()=>f.assign(n.default.vErrors,(0,t._)`[${S}]`),(0,t._)`${n.default.vErrors}.push(${S})`),f.code((0,t._)`${n.default.errors}++`)}function u(f,y){let{gen:S,validateName:_,schemaEnv:$}=f;$.$async?S.throw((0,t._)`new ${f.ValidationError}(${y})`):(S.assign((0,t._)`${_}.errors`,y),S.return(!1))}let l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function d(f,y,S){let{createErrors:_}=f.it;return _===!1?(0,t._)`{}`:m(f,y,S)}function m(f,y,S={}){let{gen:_,it:$}=f,k=[v($,S),g(f,S)];return h(f,y,k),_.object(...k)}function v({errorPath:f},{instancePath:y}){let S=y?(0,t.str)`${f}${(0,r.getErrorPath)(y,r.Type.Str)}`:f;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,S)]}function g({keyword:f,it:{errSchemaPath:y}},{schemaPath:S,parentSchema:_}){let $=_?y:(0,t.str)`${y}/${f}`;return S&&($=(0,t.str)`${$}${(0,r.getErrorPath)(S,r.Type.Str)}`),[l.schemaPath,$]}function h(f,{params:y,message:S},_){let{keyword:$,data:k,schemaValue:w,it:b}=f,{opts:E,propertyName:j,topSchemaRef:V,schemaPath:A}=b;_.push([l.keyword,$],[l.params,typeof y=="function"?y(f):y||(0,t._)`{}`]),E.messages&&_.push([l.message,typeof S=="function"?S(f):S]),E.verbose&&_.push([l.schema,w],[l.parentSchema,(0,t._)`${V}${A}`],[n.default.data,k]),j&&_.push([l.propertyName,j])}})),gP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=cd(),r=ze(),n=Gt(),o={message:"boolean schema is false"};function i(c){let{gen:u,schema:l,validateName:d}=c;l===!1?s(c,!1):typeof l=="object"&&l.$async===!0?u.return(n.default.data):(u.assign((0,r._)`${d}.errors`,null),u.return(!0))}e.topBoolOrEmptySchema=i;function a(c,u){let{gen:l,schema:d}=c;d===!1?(l.var(u,!1),s(c)):l.var(u,!0)}e.boolOrEmptySchema=a;function s(c,u){let{gen:l,data:d}=c,m={gen:l,keyword:"false schema",data:d,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c};(0,t.reportError)(m,o,void 0,u)}})),Xw=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set(["string","number","integer","boolean","null","object","array"]);function r(o){return typeof o=="string"&&t.has(o)}e.isJSONType=r;function n(){let o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=n})),Yw=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:o,self:i},a){let s=i.RULES.types[a];return s&&s!==!0&&r(o,s)}e.schemaHasRulesForType=t;function r(o,i){return i.rules.some(a=>n(o,a))}e.shouldUseGroup=r;function n(o,i){var a;return o[i.keyword]!==void 0||((a=i.definition.implements)===null||a===void 0?void 0:a.some(s=>o[s]!==void 0))}e.shouldUseRule=n})),sd=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Xw(),r=Yw(),n=cd(),o=ze(),i=Te();var a;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(a||(e.DataType=a={}));function s(_){let $=c(_.type);if($.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!$.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&$.push("null")}return $}e.getSchemaTypes=s;function c(_){let $=Array.isArray(_)?_:_?[_]:[];if($.every(t.isJSONType))return $;throw new Error("type must be JSONType or JSONType[]: "+$.join(","))}e.getJSONTypes=c;function u(_,$){let{gen:k,data:w,opts:b}=_,E=d($,b.coerceTypes),j=$.length>0&&!(E.length===0&&$.length===1&&(0,r.schemaHasRulesForType)(_,$[0]));if(j){let V=h($,w,b.strictNumbers,a.Wrong);k.if(V,()=>{E.length?m(_,$,E):y(_)})}return j}e.coerceAndCheckDataType=u;let l=new Set(["string","number","integer","boolean","null"]);function d(_,$){return $?_.filter(k=>l.has(k)||$==="array"&&k==="array"):[]}function m(_,$,k){let{gen:w,data:b,opts:E}=_,j=w.let("dataType",(0,o._)`typeof ${b}`),V=w.let("coerced",(0,o._)`undefined`);E.coerceTypes==="array"&&w.if((0,o._)`${j} == 'object' && Array.isArray(${b}) && ${b}.length == 1`,()=>w.assign(b,(0,o._)`${b}[0]`).assign(j,(0,o._)`typeof ${b}`).if(h($,b,E.strictNumbers),()=>w.assign(V,b))),w.if((0,o._)`${V} !== undefined`);for(let L of k)(l.has(L)||L==="array"&&E.coerceTypes==="array")&&A(L);w.else(),y(_),w.endIf(),w.if((0,o._)`${V} !== undefined`,()=>{w.assign(b,V),v(_,V)});function A(L){switch(L){case"string":w.elseIf((0,o._)`${j} == "number" || ${j} == "boolean"`).assign(V,(0,o._)`"" + ${b}`).elseIf((0,o._)`${b} === null`).assign(V,(0,o._)`""`);return;case"number":w.elseIf((0,o._)`${j} == "boolean" || ${b} === null + || (${j} == "string" && ${b} && ${b} == +${b})`).assign(V,(0,o._)`+${b}`);return;case"integer":w.elseIf((0,o._)`${j} === "boolean" || ${b} === null + || (${j} === "string" && ${b} && ${b} == +${b} && !(${b} % 1))`).assign(V,(0,o._)`+${b}`);return;case"boolean":w.elseIf((0,o._)`${b} === "false" || ${b} === 0 || ${b} === null`).assign(V,!1).elseIf((0,o._)`${b} === "true" || ${b} === 1`).assign(V,!0);return;case"null":w.elseIf((0,o._)`${b} === "" || ${b} === 0 || ${b} === false`),w.assign(V,null);return;case"array":w.elseIf((0,o._)`${j} === "string" || ${j} === "number" + || ${j} === "boolean" || ${b} === null`).assign(V,(0,o._)`[${b}]`)}}}function v({gen:_,parentData:$,parentDataProperty:k},w){_.if((0,o._)`${$} !== undefined`,()=>_.assign((0,o._)`${$}[${k}]`,w))}function g(_,$,k,w=a.Correct){let b=w===a.Correct?o.operators.EQ:o.operators.NEQ,E;switch(_){case"null":return(0,o._)`${$} ${b} null`;case"array":E=(0,o._)`Array.isArray(${$})`;break;case"object":E=(0,o._)`${$} && typeof ${$} == "object" && !Array.isArray(${$})`;break;case"integer":E=j((0,o._)`!(${$} % 1) && !isNaN(${$})`);break;case"number":E=j();break;default:return(0,o._)`typeof ${$} ${b} ${_}`}return w===a.Correct?E:(0,o.not)(E);function j(V=o.nil){return(0,o.and)((0,o._)`typeof ${$} == "number"`,V,k?(0,o._)`isFinite(${$})`:o.nil)}}e.checkDataType=g;function h(_,$,k,w){if(_.length===1)return g(_[0],$,k,w);let b,E=(0,i.toHash)(_);if(E.array&&E.object){let j=(0,o._)`typeof ${$} != "object"`;b=E.null?j:(0,o._)`!${$} || ${j}`,delete E.null,delete E.array,delete E.object}else b=o.nil;E.number&&delete E.integer;for(let j in E)b=(0,o.and)(b,g(j,$,k,w));return b}e.checkDataTypes=h;let f={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:$})=>typeof _=="string"?(0,o._)`{type: ${_}}`:(0,o._)`{type: ${$}}`};function y(_){let $=S(_);(0,n.reportError)($,f)}e.reportTypeError=y;function S(_){let{gen:$,data:k,schema:w}=_,b=(0,i.schemaRefOrVal)(_,w,"type");return{gen:$,keyword:"type",data:k,schema:w.type,schemaCode:b,schemaValue:b,parentSchema:w,params:{},it:_}}})),yP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=ze(),r=Te();function n(i,a){let{properties:s,items:c}=i.schema;if(a==="object"&&s)for(let u in s)o(i,u,s[u].default);else a==="array"&&Array.isArray(c)&&c.forEach((u,l)=>o(i,l,u.default))}e.assignDefaults=n;function o(i,a,s){let{gen:c,compositeRule:u,data:l,opts:d}=i;if(s===void 0)return;let m=(0,t._)`${l}${(0,t.getProperty)(a)}`;if(u){(0,r.checkStrictMode)(i,`default is ignored for: ${m}`);return}let v=(0,t._)`${m} === undefined`;d.useDefaults==="empty"&&(v=(0,t._)`${v} || ${m} === null || ${m} === ""`),c.if(v,(0,t._)`${m} = ${(0,t.stringify)(s)}`)}})),Xt=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=ze(),r=Te(),n=Gt(),o=Te();function i(_,$){let{gen:k,data:w,it:b}=_;k.if(d(k,w,$,b.opts.ownProperties),()=>{_.setParams({missingProperty:(0,t._)`${$}`},!0),_.error()})}e.checkReportMissingProp=i;function a({gen:_,data:$,it:{opts:k}},w,b){return(0,t.or)(...w.map(E=>(0,t.and)(d(_,$,E,k.ownProperties),(0,t._)`${b} = ${E}`)))}e.checkMissingProp=a;function s(_,$){_.setParams({missingProperty:$},!0),_.error()}e.reportMissingProp=s;function c(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function u(_,$,k){return(0,t._)`${c(_)}.call(${$}, ${k})`}e.isOwnProperty=u;function l(_,$,k,w){let b=(0,t._)`${$}${(0,t.getProperty)(k)} !== undefined`;return w?(0,t._)`${b} && ${u(_,$,k)}`:b}e.propertyInData=l;function d(_,$,k,w){let b=(0,t._)`${$}${(0,t.getProperty)(k)} === undefined`;return w?(0,t.or)(b,(0,t.not)(u(_,$,k))):b}e.noPropertyInData=d;function m(_){return _?Object.keys(_).filter($=>$!=="__proto__"):[]}e.allSchemaProperties=m;function v(_,$){return m($).filter(k=>!(0,r.alwaysValidSchema)(_,$[k]))}e.schemaProperties=v;function g({schemaCode:_,data:$,it:{gen:k,topSchemaRef:w,schemaPath:b,errorPath:E},it:j},V,A,L){let Z=L?(0,t._)`${_}, ${$}, ${w}${b}`:$,J=[[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,E)],[n.default.parentData,j.parentData],[n.default.parentDataProperty,j.parentDataProperty],[n.default.rootData,n.default.rootData]];j.opts.dynamicRef&&J.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let te=(0,t._)`${Z}, ${k.object(...J)}`;return A!==t.nil?(0,t._)`${V}.call(${A}, ${te})`:(0,t._)`${V}(${te})`}e.callValidateCode=g;let h=(0,t._)`new RegExp`;function f({gen:_,it:{opts:$}},k){let w=$.unicodeRegExp?"u":"",{regExp:b}=$.code,E=b(k,w);return _.scopeValue("pattern",{key:E.toString(),ref:E,code:(0,t._)`${b.code==="new RegExp"?h:(0,o.useFunc)(_,b)}(${k}, ${w})`})}e.usePattern=f;function y(_){let{gen:$,data:k,keyword:w,it:b}=_,E=$.name("valid");if(b.allErrors){let V=$.let("valid",!0);return j(()=>$.assign(V,!1)),V}return $.var(E,!0),j(()=>$.break()),E;function j(V){let A=$.const("len",(0,t._)`${k}.length`);$.forRange("i",0,A,L=>{_.subschema({keyword:w,dataProp:L,dataPropType:r.Type.Num},E),$.if((0,t.not)(E),V)})}}e.validateArray=y;function S(_){let{gen:$,schema:k,keyword:w,it:b}=_;if(!Array.isArray(k))throw new Error("ajv implementation error");if(k.some(V=>(0,r.alwaysValidSchema)(b,V))&&!b.opts.unevaluated)return;let E=$.let("valid",!1),j=$.name("_valid");$.block(()=>k.forEach((V,A)=>{let L=_.subschema({keyword:w,schemaProp:A,compositeRule:!0},j);$.assign(E,(0,t._)`${E} || ${j}`),_.mergeValidEvaluated(L,j)||$.if((0,t.not)(E))})),_.result(E,()=>_.reset(),()=>_.error(!0))}e.validateUnion=S})),vP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=ze(),r=Gt(),n=Xt(),o=cd();function i(v,g){let{gen:h,keyword:f,schema:y,parentSchema:S,it:_}=v,$=g.macro.call(_.self,y,S,_),k=l(h,f,$);_.opts.validateSchema!==!1&&_.self.validateSchema($,!0);let w=h.name("valid");v.subschema({schema:$,schemaPath:t.nil,errSchemaPath:`${_.errSchemaPath}/${f}`,topSchemaRef:k,compositeRule:!0},w),v.pass(w,()=>v.error(!0))}e.macroKeywordCode=i;function a(v,g){var h;let{gen:f,keyword:y,schema:S,parentSchema:_,$data:$,it:k}=v;u(k,g);let w=l(f,y,!$&&g.compile?g.compile.call(k.self,S,_,k):g.validate),b=f.let("valid");v.block$data(b,E),v.ok((h=g.valid)!==null&&h!==void 0?h:b);function E(){if(g.errors===!1)A(),g.modifying&&s(v),L(()=>v.error());else{let Z=g.async?j():V();g.modifying&&s(v),L(()=>c(v,Z))}}function j(){let Z=f.let("ruleErrs",null);return f.try(()=>A((0,t._)`await `),J=>f.assign(b,!1).if((0,t._)`${J} instanceof ${k.ValidationError}`,()=>f.assign(Z,(0,t._)`${J}.errors`),()=>f.throw(J))),Z}function V(){let Z=(0,t._)`${w}.errors`;return f.assign(Z,null),A(t.nil),Z}function A(Z=g.async?(0,t._)`await `:t.nil){let J=k.opts.passContext?r.default.this:r.default.self,te=!("compile"in g&&!$||g.schema===!1);f.assign(b,(0,t._)`${Z}${(0,n.callValidateCode)(v,w,J,te)}`,g.modifying)}function L(Z){var J;f.if((0,t.not)((J=g.valid)!==null&&J!==void 0?J:b),Z)}}e.funcKeywordCode=a;function s(v){let{gen:g,data:h,it:f}=v;g.if(f.parentData,()=>g.assign(h,(0,t._)`${f.parentData}[${f.parentDataProperty}]`))}function c(v,g){let{gen:h}=v;h.if((0,t._)`Array.isArray(${g})`,()=>{h.assign(r.default.vErrors,(0,t._)`${r.default.vErrors} === null ? ${g} : ${r.default.vErrors}.concat(${g})`).assign(r.default.errors,(0,t._)`${r.default.vErrors}.length`),(0,o.extendErrors)(v)},()=>v.error())}function u({schemaEnv:v},g){if(g.async&&!v.$async)throw new Error("async keyword in sync schema")}function l(v,g,h){if(h===void 0)throw new Error(`keyword "${g}" failed to compile`);return v.scopeValue("keyword",typeof h=="function"?{ref:h}:{ref:h,code:(0,t.stringify)(h)})}function d(v,g,h=!1){return!g.length||g.some(f=>f==="array"?Array.isArray(v):f==="object"?v&&typeof v=="object"&&!Array.isArray(v):typeof v==f||h&&typeof v>"u")}e.validSchemaType=d;function m({schema:v,opts:g,self:h,errSchemaPath:f},y,S){if(Array.isArray(y.keyword)?!y.keyword.includes(S):y.keyword!==S)throw new Error("ajv implementation error");let _=y.dependencies;if(_?.some($=>!Object.prototype.hasOwnProperty.call(v,$)))throw new Error(`parent schema must have dependencies of ${S}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(v[S])){let $=`keyword "${S}" value is invalid at path "${f}": `+h.errorsText(y.validateSchema.errors);if(g.validateSchema==="log")h.logger.error($);else throw new Error($)}}e.validateKeywordUsage=m})),_P=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=ze(),r=Te();function n(a,{keyword:s,schemaProp:c,schema:u,schemaPath:l,errSchemaPath:d,topSchemaRef:m}){if(s!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){let v=a.schema[s];return c===void 0?{schema:v,schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(s)}`,errSchemaPath:`${a.errSchemaPath}/${s}`}:{schema:v[c],schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(s)}${(0,t.getProperty)(c)}`,errSchemaPath:`${a.errSchemaPath}/${s}/${(0,r.escapeFragment)(c)}`}}if(u!==void 0){if(l===void 0||d===void 0||m===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:u,schemaPath:l,topSchemaRef:m,errSchemaPath:d}}throw new Error('either "keyword" or "schema" must be passed')}e.getSubschema=n;function o(a,s,{dataProp:c,dataPropType:u,data:l,dataTypes:d,propertyName:m}){if(l!==void 0&&c!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:v}=s;if(c!==void 0){let{errorPath:h,dataPathArr:f,opts:y}=s;g(v.let("data",(0,t._)`${s.data}${(0,t.getProperty)(c)}`,!0)),a.errorPath=(0,t.str)`${h}${(0,r.getErrorPath)(c,u,y.jsPropertySyntax)}`,a.parentDataProperty=(0,t._)`${c}`,a.dataPathArr=[...f,a.parentDataProperty]}l!==void 0&&(g(l instanceof t.Name?l:v.let("data",l,!0)),m!==void 0&&(a.propertyName=m)),d&&(a.dataTypes=d);function g(h){a.data=h,a.dataLevel=s.dataLevel+1,a.dataTypes=[],s.definedProperties=new Set,a.parentData=s.data,a.dataNames=[...s.dataNames,h]}}e.extendSubschemaData=o;function i(a,{jtdDiscriminator:s,jtdMetadata:c,compositeRule:u,createErrors:l,allErrors:d}){u!==void 0&&(a.compositeRule=u),l!==void 0&&(a.createErrors=l),d!==void 0&&(a.allErrors=d),a.jtdDiscriminator=s,a.jtdMetadata=c}e.extendSubschemaMode=i})),Qw=H(((e,t)=>{t.exports=function r(n,o){if(n===o)return!0;if(n&&o&&typeof n=="object"&&typeof o=="object"){if(n.constructor!==o.constructor)return!1;var i,a,s;if(Array.isArray(n)){if(i=n.length,i!=o.length)return!1;for(a=i;a--!==0;)if(!r(n[a],o[a]))return!1;return!0}if(n.constructor===RegExp)return n.source===o.source&&n.flags===o.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===o.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===o.toString();if(s=Object.keys(n),i=s.length,i!==Object.keys(o).length)return!1;for(a=i;a--!==0;)if(!Object.prototype.hasOwnProperty.call(o,s[a]))return!1;for(a=i;a--!==0;){var c=s[a];if(!r(n[c],o[c]))return!1}return!0}return n!==n&&o!==o}})),SP=H(((e,t)=>{var r=t.exports=function(i,a,s){typeof a=="function"&&(s=a,a={}),s=a.cb||s;var c=typeof s=="function"?s:s.pre||function(){},u=s.post||function(){};n(a,c,u,i,"",i)};r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},r.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function n(i,a,s,c,u,l,d,m,v,g){if(c&&typeof c=="object"&&!Array.isArray(c)){a(c,u,l,d,m,v,g);for(var h in c){var f=c[h];if(Array.isArray(f)){if(h in r.arrayKeywords)for(var y=0;y{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Te(),r=Qw(),n=SP(),o=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function i(f,y=!0){return typeof f=="boolean"?!0:y===!0?!s(f):y?c(f)<=y:!1}e.inlineRef=i;let a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(f){for(let y in f){if(a.has(y))return!0;let S=f[y];if(Array.isArray(S)&&S.some(s)||typeof S=="object"&&s(S))return!0}return!1}function c(f){let y=0;for(let S in f){if(S==="$ref")return 1/0;if(y++,!o.has(S)&&(typeof f[S]=="object"&&(0,t.eachItem)(f[S],_=>y+=c(_)),y===1/0))return 1/0}return y}function u(f,y="",S){return S!==!1&&(y=m(y)),l(f,f.parse(y))}e.getFullPath=u;function l(f,y){return f.serialize(y).split("#")[0]+"#"}e._getFullPath=l;let d=/#\/?$/;function m(f){return f?f.replace(d,""):""}e.normalizeId=m;function v(f,y,S){return S=m(S),f.resolve(y,S)}e.resolveUrl=v;let g=/^[a-z_][-a-z0-9._]*$/i;function h(f,y){if(typeof f=="boolean")return{};let{schemaId:S,uriResolver:_}=this.opts,$=m(f[S]||y),k={"":$},w=u(_,$,!1),b={},E=new Set;return n(f,{allKeys:!0},(A,L,Z,J)=>{if(J===void 0)return;let te=w+L,_e=k[J];typeof A[S]=="string"&&(_e=ke.call(this,A[S])),Ne.call(this,A.$anchor),Ne.call(this,A.$dynamicAnchor),k[L]=_e;function ke(be){let P=this.opts.uriResolver.resolve;if(be=m(_e?P(_e,be):be),E.has(be))throw V(be);E.add(be);let M=this.refs[be];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?j(A,M.schema,be):be!==m(te)&&(be[0]==="#"?(j(A,b[be],be),b[be]=A):this.refs[be]=te),be}function Ne(be){if(typeof be=="string"){if(!g.test(be))throw new Error(`invalid anchor "${be}"`);ke.call(this,`#${be}`)}}}),b;function j(A,L,Z){if(L!==void 0&&!r(A,L))throw V(Z)}function V(A){return new Error(`reference "${A}" resolves to more than one schema`)}}e.getSchemaRefs=h})),hs=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=gP(),r=sd(),n=Yw(),o=sd(),i=yP(),a=vP(),s=_P(),c=ze(),u=Gt(),l=ud(),d=Te(),m=cd();function v(R){if(w(R)&&(E(R),k(R))){y(R);return}g(R,()=>(0,t.topBoolOrEmptySchema)(R))}e.validateFunctionCode=v;function g({gen:R,validateName:T,schema:D,schemaEnv:oe,opts:ne},ie){ne.code.es5?R.func(T,(0,c._)`${u.default.data}, ${u.default.valCxt}`,oe.$async,()=>{R.code((0,c._)`"use strict"; ${_(D,ne)}`),f(R,ne),R.code(ie)}):R.func(T,(0,c._)`${u.default.data}, ${h(ne)}`,oe.$async,()=>R.code(_(D,ne)).code(ie))}function h(R){return(0,c._)`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${R.dynamicRef?(0,c._)`, ${u.default.dynamicAnchors}={}`:c.nil}}={}`}function f(R,T){R.if(u.default.valCxt,()=>{R.var(u.default.instancePath,(0,c._)`${u.default.valCxt}.${u.default.instancePath}`),R.var(u.default.parentData,(0,c._)`${u.default.valCxt}.${u.default.parentData}`),R.var(u.default.parentDataProperty,(0,c._)`${u.default.valCxt}.${u.default.parentDataProperty}`),R.var(u.default.rootData,(0,c._)`${u.default.valCxt}.${u.default.rootData}`),T.dynamicRef&&R.var(u.default.dynamicAnchors,(0,c._)`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{R.var(u.default.instancePath,(0,c._)`""`),R.var(u.default.parentData,(0,c._)`undefined`),R.var(u.default.parentDataProperty,(0,c._)`undefined`),R.var(u.default.rootData,u.default.data),T.dynamicRef&&R.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function y(R){let{schema:T,opts:D,gen:oe}=R;g(R,()=>{D.$comment&&T.$comment&&J(R),A(R),oe.let(u.default.vErrors,null),oe.let(u.default.errors,0),D.unevaluated&&S(R),j(R),te(R)})}function S(R){let{gen:T,validateName:D}=R;R.evaluated=T.const("evaluated",(0,c._)`${D}.evaluated`),T.if((0,c._)`${R.evaluated}.dynamicProps`,()=>T.assign((0,c._)`${R.evaluated}.props`,(0,c._)`undefined`)),T.if((0,c._)`${R.evaluated}.dynamicItems`,()=>T.assign((0,c._)`${R.evaluated}.items`,(0,c._)`undefined`))}function _(R,T){let D=typeof R=="object"&&R[T.schemaId];return D&&(T.code.source||T.code.process)?(0,c._)`/*# sourceURL=${D} */`:c.nil}function $(R,T){if(w(R)&&(E(R),k(R))){b(R,T);return}(0,t.boolOrEmptySchema)(R,T)}function k({schema:R,self:T}){if(typeof R=="boolean")return!R;for(let D in R)if(T.RULES.all[D])return!0;return!1}function w(R){return typeof R.schema!="boolean"}function b(R,T){let{schema:D,gen:oe,opts:ne}=R;ne.$comment&&D.$comment&&J(R),L(R),Z(R);let ie=oe.const("_errs",u.default.errors);j(R,ie),oe.var(T,(0,c._)`${ie} === ${u.default.errors}`)}function E(R){(0,d.checkUnknownRules)(R),V(R)}function j(R,T){if(R.opts.jtd)return ke(R,[],!1,T);let D=(0,r.getSchemaTypes)(R.schema);ke(R,D,!(0,r.coerceAndCheckDataType)(R,D),T)}function V(R){let{schema:T,errSchemaPath:D,opts:oe,self:ne}=R;T.$ref&&oe.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(T,ne.RULES)&&ne.logger.warn(`$ref: keywords ignored in schema at path "${D}"`)}function A(R){let{schema:T,opts:D}=R;T.default!==void 0&&D.useDefaults&&D.strictSchema&&(0,d.checkStrictMode)(R,"default is ignored in the schema root")}function L(R){let T=R.schema[R.opts.schemaId];T&&(R.baseId=(0,l.resolveUrl)(R.opts.uriResolver,R.baseId,T))}function Z(R){if(R.schema.$async&&!R.schemaEnv.$async)throw new Error("async schema in sync schema")}function J({gen:R,schemaEnv:T,schema:D,errSchemaPath:oe,opts:ne}){let ie=D.$comment;if(ne.$comment===!0)R.code((0,c._)`${u.default.self}.logger.log(${ie})`);else if(typeof ne.$comment=="function"){let me=(0,c.str)`${oe}/$comment`,Pe=R.scopeValue("root",{ref:T.root});R.code((0,c._)`${u.default.self}.opts.$comment(${ie}, ${me}, ${Pe}.schema)`)}}function te(R){let{gen:T,schemaEnv:D,validateName:oe,ValidationError:ne,opts:ie}=R;D.$async?T.if((0,c._)`${u.default.errors} === 0`,()=>T.return(u.default.data),()=>T.throw((0,c._)`new ${ne}(${u.default.vErrors})`)):(T.assign((0,c._)`${oe}.errors`,u.default.vErrors),ie.unevaluated&&_e(R),T.return((0,c._)`${u.default.errors} === 0`))}function _e({gen:R,evaluated:T,props:D,items:oe}){D instanceof c.Name&&R.assign((0,c._)`${T}.props`,D),oe instanceof c.Name&&R.assign((0,c._)`${T}.items`,oe)}function ke(R,T,D,oe){let{gen:ne,schema:ie,data:me,allErrors:Pe,opts:Ee,self:Ze}=R,{RULES:je}=Ze;if(ie.$ref&&(Ee.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(ie,je))){ne.block(()=>$e(R,"$ref",je.all.$ref.definition));return}Ee.jtd||be(R,T),ne.block(()=>{for(let nt of je.rules)De(nt);De(je.post)});function De(nt){(0,n.shouldUseGroup)(ie,nt)&&(nt.type?(ne.if((0,o.checkDataType)(nt.type,me,Ee.strictNumbers)),Ne(R,nt),T.length===1&&T[0]===nt.type&&D&&(ne.else(),(0,o.reportTypeError)(R)),ne.endIf()):Ne(R,nt),Pe||ne.if((0,c._)`${u.default.errors} === ${oe||0}`))}}function Ne(R,T){let{gen:D,schema:oe,opts:{useDefaults:ne}}=R;ne&&(0,i.assignDefaults)(R,T.type),D.block(()=>{for(let ie of T.rules)(0,n.shouldUseRule)(oe,ie)&&$e(R,ie.keyword,ie.definition,T.type)})}function be(R,T){R.schemaEnv.meta||!R.opts.strictTypes||(P(R,T),R.opts.allowUnionTypes||M(R,T),K(R,R.dataTypes))}function P(R,T){if(T.length){if(!R.dataTypes.length){R.dataTypes=T;return}T.forEach(D=>{I(R.dataTypes,D)||W(R,`type "${D}" not allowed by context "${R.dataTypes.join(",")}"`)}),O(R,T)}}function M(R,T){T.length>1&&!(T.length===2&&T.includes("null"))&&W(R,"use allowUnionTypes to allow union type keyword")}function K(R,T){let D=R.self.RULES.all;for(let oe in D){let ne=D[oe];if(typeof ne=="object"&&(0,n.shouldUseRule)(R.schema,ne)){let{type:ie}=ne.definition;ie.length&&!ie.some(me=>z(T,me))&&W(R,`missing type "${ie.join(",")}" for keyword "${oe}"`)}}}function z(R,T){return R.includes(T)||T==="number"&&R.includes("integer")}function I(R,T){return R.includes(T)||T==="integer"&&R.includes("number")}function O(R,T){let D=[];for(let oe of R.dataTypes)I(T,oe)?D.push(oe):T.includes("integer")&&oe==="number"&&D.push("integer");R.dataTypes=D}function W(R,T){let D=R.schemaEnv.baseId+R.errSchemaPath;T+=` at "${D}" (strictTypes)`,(0,d.checkStrictMode)(R,T,R.opts.strictTypes)}var ce=class{constructor(R,T,D){if((0,a.validateKeywordUsage)(R,T,D),this.gen=R.gen,this.allErrors=R.allErrors,this.keyword=D,this.data=R.data,this.schema=R.schema[D],this.$data=T.$data&&R.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(R,this.schema,D,this.$data),this.schemaType=T.schemaType,this.parentSchema=R.schema,this.params={},this.it=R,this.def=T,this.$data)this.schemaCode=R.gen.const("vSchema",Fe(this.$data,R));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,T.schemaType,T.allowUndefined))throw new Error(`${D} value must be ${JSON.stringify(T.schemaType)}`);("code"in T?T.trackErrors:T.errors!==!1)&&(this.errsCount=R.gen.const("_errs",u.default.errors))}result(R,T,D){this.failResult((0,c.not)(R),T,D)}failResult(R,T,D){this.gen.if(R),D?D():this.error(),T?(this.gen.else(),T(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(R,T){this.failResult((0,c.not)(R),void 0,T)}fail(R){if(R===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(R),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(R){if(!this.$data)return this.fail(R);let{schemaCode:T}=this;this.fail((0,c._)`${T} !== undefined && (${(0,c.or)(this.invalid$data(),R)})`)}error(R,T,D){if(T){this.setParams(T),this._error(R,D),this.setParams({});return}this._error(R,D)}_error(R,T){(R?m.reportExtraError:m.reportError)(this,this.def.error,T)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(R){this.allErrors||this.gen.if(R)}setParams(R,T){T?Object.assign(this.params,R):this.params=R}block$data(R,T,D=c.nil){this.gen.block(()=>{this.check$data(R,D),T()})}check$data(R=c.nil,T=c.nil){if(!this.$data)return;let{gen:D,schemaCode:oe,schemaType:ne,def:ie}=this;D.if((0,c.or)((0,c._)`${oe} === undefined`,T)),R!==c.nil&&D.assign(R,!0),(ne.length||ie.validateSchema)&&(D.elseIf(this.invalid$data()),this.$dataError(),R!==c.nil&&D.assign(R,!1)),D.else()}invalid$data(){let{gen:R,schemaCode:T,schemaType:D,def:oe,it:ne}=this;return(0,c.or)(ie(),me());function ie(){if(D.length){if(!(T instanceof c.Name))throw new Error("ajv implementation error");let Pe=Array.isArray(D)?D:[D];return(0,c._)`${(0,o.checkDataTypes)(Pe,T,ne.opts.strictNumbers,o.DataType.Wrong)}`}return c.nil}function me(){if(oe.validateSchema){let Pe=R.scopeValue("validate$data",{ref:oe.validateSchema});return(0,c._)`!${Pe}(${T})`}return c.nil}}subschema(R,T){let D=(0,s.getSubschema)(this.it,R);(0,s.extendSubschemaData)(D,this.it,R),(0,s.extendSubschemaMode)(D,R);let oe={...this.it,...D,items:void 0,props:void 0};return $(oe,T),oe}mergeEvaluated(R,T){let{it:D,gen:oe}=this;D.opts.unevaluated&&(D.props!==!0&&R.props!==void 0&&(D.props=d.mergeEvaluated.props(oe,R.props,D.props,T)),D.items!==!0&&R.items!==void 0&&(D.items=d.mergeEvaluated.items(oe,R.items,D.items,T)))}mergeValidEvaluated(R,T){let{it:D,gen:oe}=this;if(D.opts.unevaluated&&(D.props!==!0||D.items!==!0))return oe.if(T,()=>this.mergeEvaluated(R,c.Name)),!0}};e.KeywordCxt=ce;function $e(R,T,D,oe){let ne=new ce(R,D,T);"code"in D?D.code(ne,oe):ne.$data&&D.validate?(0,a.funcKeywordCode)(ne,D):"macro"in D?(0,a.macroKeywordCode)(ne,D):(D.compile||D.validate)&&(0,a.funcKeywordCode)(ne,D)}let B=/^\/(?:[^~]|~0|~1)*$/,Re=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Fe(R,{dataLevel:T,dataNames:D,dataPathArr:oe}){let ne,ie;if(R==="")return u.default.rootData;if(R[0]==="/"){if(!B.test(R))throw new Error(`Invalid JSON-pointer: ${R}`);ne=R,ie=u.default.rootData}else{let Ze=Re.exec(R);if(!Ze)throw new Error(`Invalid JSON-pointer: ${R}`);let je=+Ze[1];if(ne=Ze[2],ne==="#"){if(je>=T)throw new Error(Ee("property/index",je));return oe[T-je]}if(je>T)throw new Error(Ee("data",je));if(ie=D[T-je],!ne)return ie}let me=ie,Pe=ne.split("/");for(let Ze of Pe)Ze&&(ie=(0,c._)`${ie}${(0,c.getProperty)((0,d.unescapeJsonPointer)(Ze))}`,me=(0,c._)`${me} && ${ie}`);return me;function Ee(Ze,je){return`Cannot access ${Ze} ${je} levels up, current level is ${T}`}}e.getData=Fe})),ld=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}};e.default=t})),gs=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ud();var r=class extends Error{constructor(n,o,i,a){super(a||`can't resolve reference ${i} from id ${o}`),this.missingRef=(0,t.resolveUrl)(n,o,i),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}};e.default=r})),dd=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=ze(),r=ld(),n=Gt(),o=ud(),i=Te(),a=hs();var s=class{constructor(y){var S;this.refs={},this.dynamicAnchors={};let _;typeof y.schema=="object"&&(_=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(S=y.baseId)!==null&&S!==void 0?S:(0,o.normalizeId)(_?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=_?.$async,this.refs={}}};e.SchemaEnv=s;function c(y){let S=d.call(this,y);if(S)return S;let _=(0,o.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:$,lines:k}=this.opts.code,{ownProperties:w}=this.opts,b=new t.CodeGen(this.scope,{es5:$,lines:k,ownProperties:w}),E;y.$async&&(E=b.scopeValue("Error",{ref:r.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let j=b.scopeName("validate");y.validateName=j;let V={gen:b,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:b.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,t.stringify)(y.schema)}:{ref:y.schema}),validateName:j,ValidationError:E,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:t.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this},A;try{this._compilations.add(y),(0,a.validateFunctionCode)(V),b.optimize(this.opts.code.optimize);let L=b.toString();A=`${b.scopeRefs(n.default.scope)}return ${L}`,this.opts.code.process&&(A=this.opts.code.process(A,y));let Z=new Function(`${n.default.self}`,`${n.default.scope}`,A)(this,this.scope.get());if(this.scope.value(j,{ref:Z}),Z.errors=null,Z.schema=y.schema,Z.schemaEnv=y,y.$async&&(Z.$async=!0),this.opts.code.source===!0&&(Z.source={validateName:j,validateCode:L,scopeValues:b._values}),this.opts.unevaluated){let{props:J,items:te}=V;Z.evaluated={props:J instanceof t.Name?void 0:J,items:te instanceof t.Name?void 0:te,dynamicProps:J instanceof t.Name,dynamicItems:te instanceof t.Name},Z.source&&(Z.source.evaluated=(0,t.stringify)(Z.evaluated))}return y.validate=Z,y}catch(L){throw delete y.validate,delete y.validateName,A&&this.logger.error("Error compiling schema, function code:",A),L}finally{this._compilations.delete(y)}}e.compileSchema=c;function u(y,S,_){var $;_=(0,o.resolveUrl)(this.opts.uriResolver,S,_);let k=y.refs[_];if(k)return k;let w=v.call(this,y,_);if(w===void 0){let b=($=y.localRefs)===null||$===void 0?void 0:$[_],{schemaId:E}=this.opts;b&&(w=new s({schema:b,schemaId:E,root:y,baseId:S}))}if(w!==void 0)return y.refs[_]=l.call(this,w)}e.resolveRef=u;function l(y){return(0,o.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:c.call(this,y)}function d(y){for(let S of this._compilations)if(m(S,y))return S}e.getCompilingSchema=d;function m(y,S){return y.schema===S.schema&&y.root===S.root&&y.baseId===S.baseId}function v(y,S){let _;for(;typeof(_=this.refs[S])=="string";)S=_;return _||this.schemas[S]||g.call(this,y,S)}function g(y,S){let _=this.opts.uriResolver.parse(S),$=(0,o._getFullPath)(this.opts.uriResolver,_),k=(0,o.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&$===k)return f.call(this,_,y);let w=(0,o.normalizeId)($),b=this.refs[w]||this.schemas[w];if(typeof b=="string"){let E=g.call(this,y,b);return typeof E?.schema!="object"?void 0:f.call(this,_,E)}if(typeof b?.schema=="object"){if(b.validate||c.call(this,b),w===(0,o.normalizeId)(S)){let{schema:E}=b,{schemaId:j}=this.opts,V=E[j];return V&&(k=(0,o.resolveUrl)(this.opts.uriResolver,k,V)),new s({schema:E,schemaId:j,root:y,baseId:k})}return f.call(this,_,b)}}e.resolveSchema=g;let h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function f(y,{baseId:S,schema:_,root:$}){var k;if(((k=y.fragment)===null||k===void 0?void 0:k[0])!=="/")return;for(let E of y.fragment.slice(1).split("/")){if(typeof _=="boolean")return;let j=_[(0,i.unescapeFragment)(E)];if(j===void 0)return;_=j;let V=typeof _=="object"&&_[this.opts.schemaId];!h.has(E)&&V&&(S=(0,o.resolveUrl)(this.opts.uriResolver,S,V))}let w;if(typeof _!="boolean"&&_.$ref&&!(0,i.schemaHasRulesButRef)(_,this.RULES)){let E=(0,o.resolveUrl)(this.opts.uriResolver,S,_.$ref);w=g.call(this,$,E)}let{schemaId:b}=this.opts;if(w=w||new s({schema:_,schemaId:b,root:$,baseId:S}),w.schema!==w.root.schema)return w}})),bP=H(((e,t)=>{t.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}})),ez=H(((e,t)=>{let r=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),n=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function o(g){let h="",f=0,y=0;for(y=0;y=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";h+=g[y];break}for(y+=1;y=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";h+=g[y]}return h}let i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function a(g){return g.length=0,!0}function s(g,h,f){if(g.length){let y=o(g);if(y!=="")h.push(y);else return f.error=!0,!1;g.length=0}return!0}function c(g){let h=0,f={error:!1,address:"",zone:""},y=[],S=[],_=!1,$=!1,k=s;for(let w=0;w7){f.error=!0;break}w>0&&g[w-1]===":"&&(_=!0),y.push(":");continue}else if(b==="%"){if(!k(S,y,f))break;k=a}else{S.push(b);continue}}return S.length&&(k===a?f.zone=S.join(""):$?y.push(S.join("")):y.push(o(S))),f.address=y.join(""),f}function u(g){if(l(g,":")<2)return{host:g,isIPV6:!1};let h=c(g);if(h.error)return{host:g,isIPV6:!1};{let f=h.address,y=h.address;return h.zone&&(f+="%"+h.zone,y+="%25"+h.zone),{host:f,isIPV6:!0,escapedHost:y}}}function l(g,h){let f=0;for(let y=0;y{let{isUUID:r}=ez(),n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,o=["http","https","ws","wss","urn","urn:uuid"];function i(b){return o.indexOf(b)!==-1}function a(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function c(b){let E=String(b.scheme).toLowerCase()==="https";return(b.port===(E?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function u(b){return b.secure=a(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(a(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){let[E,j]=b.resourceName.split("?");b.path=E&&E!=="/"?E:void 0,b.query=j,b.resourceName=void 0}return b.fragment=void 0,b}function d(b,E){if(!b.path)return b.error="URN can not be parsed",b;let j=b.path.match(n);if(j){let V=E.scheme||b.scheme||"urn";b.nid=j[1].toLowerCase(),b.nss=j[2];let A=w(`${V}:${E.nid||b.nid}`);b.path=void 0,A&&(b=A.parse(b,E))}else b.error=b.error||"URN can not be parsed.";return b}function m(b,E){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");let j=E.scheme||b.scheme||"urn",V=b.nid.toLowerCase(),A=w(`${j}:${E.nid||V}`);A&&(b=A.serialize(b,E));let L=b,Z=b.nss;return L.path=`${V||E.nid}:${Z}`,E.skipEscape=!0,L}function v(b,E){let j=b;return j.uuid=j.nss,j.nss=void 0,!E.tolerant&&(!j.uuid||!r(j.uuid))&&(j.error=j.error||"UUID is not valid."),j}function g(b){let E=b;return E.nss=(b.uuid||"").toLowerCase(),E}let h={scheme:"http",domainHost:!0,parse:s,serialize:c},f={scheme:"https",domainHost:h.domainHost,parse:s,serialize:c},y={scheme:"ws",domainHost:!0,parse:u,serialize:l},S={scheme:"wss",domainHost:y.domainHost,parse:y.parse,serialize:y.serialize},k={http:h,https:f,ws:y,wss:S,urn:{scheme:"urn",parse:d,serialize:m,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:v,serialize:g,skipNormalize:!0}};Object.setPrototypeOf(k,null);function w(b){return b&&(k[b]||k[b.toLowerCase()])||void 0}t.exports={wsIsSecure:a,SCHEMES:k,isValidSchemeName:i,getSchemeHandler:w}})),wP=H(((e,t)=>{let{normalizeIPv6:r,removeDotSegments:n,recomposeAuthority:o,normalizeComponentEncoding:i,isIPv4:a,nonSimpleDomain:s}=ez(),{SCHEMES:c,getSchemeHandler:u}=$P();function l(S,_){return typeof S=="string"?S=g(f(S,_),_):typeof S=="object"&&(S=f(g(S,_),_)),S}function d(S,_,$){let k=$?Object.assign({scheme:"null"},$):{scheme:"null"},w=m(f(S,k),f(_,k),k,!0);return k.skipEscape=!0,g(w,k)}function m(S,_,$,k){let w={};return k||(S=f(g(S,$),$),_=f(g(_,$),$)),$=$||{},!$.tolerant&&_.scheme?(w.scheme=_.scheme,w.userinfo=_.userinfo,w.host=_.host,w.port=_.port,w.path=n(_.path||""),w.query=_.query):(_.userinfo!==void 0||_.host!==void 0||_.port!==void 0?(w.userinfo=_.userinfo,w.host=_.host,w.port=_.port,w.path=n(_.path||""),w.query=_.query):(_.path?(_.path[0]==="/"?w.path=n(_.path):((S.userinfo!==void 0||S.host!==void 0||S.port!==void 0)&&!S.path?w.path="/"+_.path:S.path?w.path=S.path.slice(0,S.path.lastIndexOf("/")+1)+_.path:w.path=_.path,w.path=n(w.path)),w.query=_.query):(w.path=S.path,_.query!==void 0?w.query=_.query:w.query=S.query),w.userinfo=S.userinfo,w.host=S.host,w.port=S.port),w.scheme=S.scheme),w.fragment=_.fragment,w}function v(S,_,$){return typeof S=="string"?(S=unescape(S),S=g(i(f(S,$),!0),{...$,skipEscape:!0})):typeof S=="object"&&(S=g(i(S,!0),{...$,skipEscape:!0})),typeof _=="string"?(_=unescape(_),_=g(i(f(_,$),!0),{...$,skipEscape:!0})):typeof _=="object"&&(_=g(i(_,!0),{...$,skipEscape:!0})),S.toLowerCase()===_.toLowerCase()}function g(S,_){let $={host:S.host,scheme:S.scheme,userinfo:S.userinfo,port:S.port,path:S.path,query:S.query,nid:S.nid,nss:S.nss,uuid:S.uuid,fragment:S.fragment,reference:S.reference,resourceName:S.resourceName,secure:S.secure,error:""},k=Object.assign({},_),w=[],b=u(k.scheme||$.scheme);b&&b.serialize&&b.serialize($,k),$.path!==void 0&&(k.skipEscape?$.path=unescape($.path):($.path=escape($.path),$.scheme!==void 0&&($.path=$.path.split("%3A").join(":")))),k.reference!=="suffix"&&$.scheme&&w.push($.scheme,":");let E=o($);if(E!==void 0&&(k.reference!=="suffix"&&w.push("//"),w.push(E),$.path&&$.path[0]!=="/"&&w.push("/")),$.path!==void 0){let j=$.path;!k.absolutePath&&(!b||!b.absolutePath)&&(j=n(j)),E===void 0&&j[0]==="/"&&j[1]==="/"&&(j="/%2F"+j.slice(2)),w.push(j)}return $.query!==void 0&&w.push("?",$.query),$.fragment!==void 0&&w.push("#",$.fragment),w.join("")}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f(S,_){let $=Object.assign({},_),k={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},w=!1;$.reference==="suffix"&&($.scheme?S=$.scheme+":"+S:S="//"+S);let b=S.match(h);if(b){if(k.scheme=b[1],k.userinfo=b[3],k.host=b[4],k.port=parseInt(b[5],10),k.path=b[6]||"",k.query=b[7],k.fragment=b[8],isNaN(k.port)&&(k.port=b[5]),k.host)if(a(k.host)===!1){let j=r(k.host);k.host=j.host.toLowerCase(),w=j.isIPV6}else w=!0;k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&k.query===void 0&&!k.path?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",$.reference&&$.reference!=="suffix"&&$.reference!==k.reference&&(k.error=k.error||"URI is not a "+$.reference+" reference.");let E=u($.scheme||k.scheme);if(!$.unicodeSupport&&(!E||!E.unicodeSupport)&&k.host&&($.domainHost||E&&E.domainHost)&&w===!1&&s(k.host))try{k.host=URL.domainToASCII(k.host.toLowerCase())}catch(j){k.error=k.error||"Host's domain name can not be converted to ASCII: "+j}(!E||E&&!E.skipNormalize)&&(S.indexOf("%")!==-1&&(k.scheme!==void 0&&(k.scheme=unescape(k.scheme)),k.host!==void 0&&(k.host=unescape(k.host))),k.path&&(k.path=escape(unescape(k.path))),k.fragment&&(k.fragment=encodeURI(decodeURIComponent(k.fragment)))),E&&E.parse&&E.parse(k,$)}else k.error=k.error||"URI can not be parsed.";return k}let y={SCHEMES:c,normalize:l,resolve:d,resolveComponent:m,equal:v,serialize:g,parse:f};t.exports=y,t.exports.default=y,t.exports.fastUri=y})),zP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wP();t.code='require("ajv/dist/runtime/uri").default',e.default=t})),tz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=hs();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=ze();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});let n=ld(),o=gs(),i=Xw(),a=dd(),s=ze(),c=ud(),u=sd(),l=Te(),d=bP(),m=zP(),v=(P,M)=>new RegExp(P,M);v.code="new RegExp";let g=["removeAdditional","useDefaults","coerceTypes"],h=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),f={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."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},S=200;function _(P){var M,K,z,I,O,W,ce,$e,B,Re,Fe,R,T,D,oe,ne,ie,me,Pe,Ee,Ze,je,De,nt,Jt;let yt=P.strict,ut=(M=P.code)===null||M===void 0?void 0:M.optimize,Ft=ut===!0||ut===void 0?1:ut||0,rr=(z=(K=P.code)===null||K===void 0?void 0:K.regExp)!==null&&z!==void 0?z:v,hn=(I=P.uriResolver)!==null&&I!==void 0?I:m.default;return{strictSchema:(W=(O=P.strictSchema)!==null&&O!==void 0?O:yt)!==null&&W!==void 0?W:!0,strictNumbers:($e=(ce=P.strictNumbers)!==null&&ce!==void 0?ce:yt)!==null&&$e!==void 0?$e:!0,strictTypes:(Re=(B=P.strictTypes)!==null&&B!==void 0?B:yt)!==null&&Re!==void 0?Re:"log",strictTuples:(R=(Fe=P.strictTuples)!==null&&Fe!==void 0?Fe:yt)!==null&&R!==void 0?R:"log",strictRequired:(D=(T=P.strictRequired)!==null&&T!==void 0?T:yt)!==null&&D!==void 0?D:!1,code:P.code?{...P.code,optimize:Ft,regExp:rr}:{optimize:Ft,regExp:rr},loopRequired:(oe=P.loopRequired)!==null&&oe!==void 0?oe:S,loopEnum:(ne=P.loopEnum)!==null&&ne!==void 0?ne:S,meta:(ie=P.meta)!==null&&ie!==void 0?ie:!0,messages:(me=P.messages)!==null&&me!==void 0?me:!0,inlineRefs:(Pe=P.inlineRefs)!==null&&Pe!==void 0?Pe:!0,schemaId:(Ee=P.schemaId)!==null&&Ee!==void 0?Ee:"$id",addUsedSchema:(Ze=P.addUsedSchema)!==null&&Ze!==void 0?Ze:!0,validateSchema:(je=P.validateSchema)!==null&&je!==void 0?je:!0,validateFormats:(De=P.validateFormats)!==null&&De!==void 0?De:!0,unicodeRegExp:(nt=P.unicodeRegExp)!==null&&nt!==void 0?nt:!0,int32range:(Jt=P.int32range)!==null&&Jt!==void 0?Jt:!0,uriResolver:hn}}var $=class{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,..._(P)};let{es5:M,lines:K}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:M,lines:K}),this.logger=L(P.logger);let z=P.validateFormats;P.validateFormats=!1,this.RULES=(0,i.getRules)(),k.call(this,f,P,"NOT SUPPORTED"),k.call(this,y,P,"DEPRECATED","warn"),this._metaOpts=V.call(this),P.formats&&E.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&j.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),b.call(this),P.validateFormats=z}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:P,meta:M,schemaId:K}=this.opts,z=d;K==="id"&&(z={...d},z.id=z.$id,delete z.$id),M&&P&&this.addMetaSchema(z,z[K],!1)}defaultMeta(){let{meta:P,schemaId:M}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[M]||P:void 0}validate(P,M){let K;if(typeof P=="string"){if(K=this.getSchema(P),!K)throw new Error(`no schema with key or ref "${P}"`)}else K=this.compile(P);let z=K(M);return"$async"in K||(this.errors=K.errors),z}compile(P,M){let K=this._addSchema(P,M);return K.validate||this._compileSchemaEnv(K)}compileAsync(P,M){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:K}=this.opts;return z.call(this,P,M);async function z(B,Re){await I.call(this,B.$schema);let Fe=this._addSchema(B,Re);return Fe.validate||O.call(this,Fe)}async function I(B){B&&!this.getSchema(B)&&await z.call(this,{$ref:B},!0)}async function O(B){try{return this._compileSchemaEnv(B)}catch(Re){if(!(Re instanceof o.default))throw Re;return W.call(this,Re),await ce.call(this,Re.missingSchema),O.call(this,B)}}function W({missingSchema:B,missingRef:Re}){if(this.refs[B])throw new Error(`AnySchema ${B} is loaded but ${Re} cannot be resolved`)}async function ce(B){let Re=await $e.call(this,B);this.refs[B]||await I.call(this,Re.$schema),this.refs[B]||this.addSchema(Re,B,M)}async function $e(B){let Re=this._loading[B];if(Re)return Re;try{return await(this._loading[B]=K(B))}finally{delete this._loading[B]}}}addSchema(P,M,K,z=this.opts.validateSchema){if(Array.isArray(P)){for(let O of P)this.addSchema(O,void 0,K,z);return this}let I;if(typeof P=="object"){let{schemaId:O}=this.opts;if(I=P[O],I!==void 0&&typeof I!="string")throw new Error(`schema ${O} must be string`)}return M=(0,c.normalizeId)(M||I),this._checkUnique(M),this.schemas[M]=this._addSchema(P,K,M,z,!0),this}addMetaSchema(P,M,K=this.opts.validateSchema){return this.addSchema(P,M,!0,K),this}validateSchema(P,M){if(typeof P=="boolean")return!0;let K;if(K=P.$schema,K!==void 0&&typeof K!="string")throw new Error("$schema must be a string");if(K=K||this.opts.defaultMeta||this.defaultMeta(),!K)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let z=this.validate(K,P);if(!z&&M){let I="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(I);else throw new Error(I)}return z}getSchema(P){let M;for(;typeof(M=w.call(this,P))=="string";)P=M;if(M===void 0){let{schemaId:K}=this.opts,z=new a.SchemaEnv({schema:{},schemaId:K});if(M=a.resolveSchema.call(this,z,P),!M)return;this.refs[P]=M}return M.validate||this._compileSchemaEnv(M)}removeSchema(P){if(P instanceof RegExp)return this._removeAllSchemas(this.schemas,P),this._removeAllSchemas(this.refs,P),this;switch(typeof P){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let M=w.call(this,P);return typeof M=="object"&&this._cache.delete(M.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{let M=P;this._cache.delete(M);let K=P[this.opts.schemaId];return K&&(K=(0,c.normalizeId)(K),delete this.schemas[K],delete this.refs[K]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(P){for(let M of P)this.addKeyword(M);return this}addKeyword(P,M){let K;if(typeof P=="string")K=P,typeof M=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),M.keyword=K);else if(typeof P=="object"&&M===void 0){if(M=P,K=M.keyword,Array.isArray(K)&&!K.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(J.call(this,K,M),!M)return(0,l.eachItem)(K,I=>te.call(this,I)),this;ke.call(this,M);let z={...M,type:(0,u.getJSONTypes)(M.type),schemaType:(0,u.getJSONTypes)(M.schemaType)};return(0,l.eachItem)(K,z.type.length===0?I=>te.call(this,I,z):I=>z.type.forEach(O=>te.call(this,I,z,O))),this}getKeyword(P){let M=this.RULES.all[P];return typeof M=="object"?M.definition:!!M}removeKeyword(P){let{RULES:M}=this;delete M.keywords[P],delete M.all[P];for(let K of M.rules){let z=K.rules.findIndex(I=>I.keyword===P);z>=0&&K.rules.splice(z,1)}return this}addFormat(P,M){return typeof M=="string"&&(M=new RegExp(M)),this.formats[P]=M,this}errorsText(P=this.errors,{separator:M=", ",dataVar:K="data"}={}){return!P||P.length===0?"No errors":P.map(z=>`${K}${z.instancePath} ${z.message}`).reduce((z,I)=>z+M+I)}$dataMetaSchema(P,M){let K=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(let z of M){let I=z.split("/").slice(1),O=P;for(let W of I)O=O[W];for(let W in K){let ce=K[W];if(typeof ce!="object")continue;let{$data:$e}=ce.definition,B=O[W];$e&&B&&(O[W]=be(B))}}return P}_removeAllSchemas(P,M){for(let K in P){let z=P[K];(!M||M.test(K))&&(typeof z=="string"?delete P[K]:z&&!z.meta&&(this._cache.delete(z.schema),delete P[K]))}}_addSchema(P,M,K,z=this.opts.validateSchema,I=this.opts.addUsedSchema){let O,{schemaId:W}=this.opts;if(typeof P=="object")O=P[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof P!="boolean")throw new Error("schema must be object or boolean")}let ce=this._cache.get(P);if(ce!==void 0)return ce;K=(0,c.normalizeId)(O||K);let $e=c.getSchemaRefs.call(this,P,K);return ce=new a.SchemaEnv({schema:P,schemaId:W,meta:M,baseId:K,localRefs:$e}),this._cache.set(ce.schema,ce),I&&!K.startsWith("#")&&(K&&this._checkUnique(K),this.refs[K]=ce),z&&this.validateSchema(P,!0),ce}_checkUnique(P){if(this.schemas[P]||this.refs[P])throw new Error(`schema with key or id "${P}" already exists`)}_compileSchemaEnv(P){if(P.meta?this._compileMetaSchema(P):a.compileSchema.call(this,P),!P.validate)throw new Error("ajv implementation error");return P.validate}_compileMetaSchema(P){let M=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,P)}finally{this.opts=M}}};$.ValidationError=n.default,$.MissingRefError=o.default,e.default=$;function k(P,M,K,z="error"){for(let I in P){let O=I;O in M&&this.logger[z](`${K}: option ${I}. ${P[O]}`)}}function w(P){return P=(0,c.normalizeId)(P),this.schemas[P]||this.refs[P]}function b(){let P=this.opts.schemas;if(P)if(Array.isArray(P))this.addSchema(P);else for(let M in P)this.addSchema(P[M],M)}function E(){for(let P in this.opts.formats){let M=this.opts.formats[P];M&&this.addFormat(P,M)}}function j(P){if(Array.isArray(P)){this.addVocabulary(P);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let M in P){let K=P[M];K.keyword||(K.keyword=M),this.addKeyword(K)}}function V(){let P={...this.opts};for(let M of g)delete P[M];return P}let A={log(){},warn(){},error(){}};function L(P){if(P===!1)return A;if(P===void 0)return console;if(P.log&&P.warn&&P.error)return P;throw new Error("logger must implement log, warn and error methods")}let Z=/^[a-z_$][a-z0-9_$:-]*$/i;function J(P,M){let{RULES:K}=this;if((0,l.eachItem)(P,z=>{if(K.keywords[z])throw new Error(`Keyword ${z} is already defined`);if(!Z.test(z))throw new Error(`Keyword ${z} has invalid name`)}),!!M&&M.$data&&!("code"in M||"validate"in M))throw new Error('$data keyword must have "code" or "validate" function')}function te(P,M,K){var z;let I=M?.post;if(K&&I)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:O}=this,W=I?O.post:O.rules.find(({type:$e})=>$e===K);if(W||(W={type:K,rules:[]},O.rules.push(W)),O.keywords[P]=!0,!M)return;let ce={keyword:P,definition:{...M,type:(0,u.getJSONTypes)(M.type),schemaType:(0,u.getJSONTypes)(M.schemaType)}};M.before?_e.call(this,W,ce,M.before):W.rules.push(ce),O.all[P]=ce,(z=M.implements)===null||z===void 0||z.forEach($e=>this.addKeyword($e))}function _e(P,M,K){let z=P.rules.findIndex(I=>I.keyword===K);z>=0?P.rules.splice(z,0,M):(P.rules.push(M),this.logger.warn(`rule ${K} is not defined`))}function ke(P){let{metaSchema:M}=P;M!==void 0&&(P.$data&&this.opts.$data&&(M=be(M)),P.validateSchema=this.compile(M,!0))}let Ne={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function be(P){return{anyOf:[P,Ne]}}})),kP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};e.default=t})),dg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=gs(),r=Xt(),n=ze(),o=Gt(),i=dd(),a=Te(),s={keyword:"$ref",schemaType:"string",code(l){let{gen:d,schema:m,it:v}=l,{baseId:g,schemaEnv:h,validateName:f,opts:y,self:S}=v,{root:_}=h;if((m==="#"||m==="#/")&&g===_.baseId)return k();let $=i.resolveRef.call(S,_,g,m);if($===void 0)throw new t.default(v.opts.uriResolver,g,m);if($ instanceof i.SchemaEnv)return w($);return b($);function k(){if(h===_)return u(l,f,h,h.$async);let E=d.scopeValue("root",{ref:_});return u(l,(0,n._)`${E}.validate`,_,_.$async)}function w(E){u(l,c(l,E),E,E.$async)}function b(E){let j=d.scopeValue("schema",y.code.source===!0?{ref:E,code:(0,n.stringify)(E)}:{ref:E}),V=d.name("valid"),A=l.subschema({schema:E,dataTypes:[],schemaPath:n.nil,topSchemaRef:j,errSchemaPath:m},V);l.mergeEvaluated(A),l.ok(V)}}};function c(l,d){let{gen:m}=l;return d.validate?m.scopeValue("validate",{ref:d.validate}):(0,n._)`${m.scopeValue("wrapper",{ref:d})}.validate`}e.getValidate=c;function u(l,d,m,v){let{gen:g,it:h}=l,{allErrors:f,schemaEnv:y,opts:S}=h,_=S.passContext?o.default.this:n.nil;v?$():k();function $(){if(!y.$async)throw new Error("async schema referenced by sync schema");let E=g.let("valid");g.try(()=>{g.code((0,n._)`await ${(0,r.callValidateCode)(l,d,_)}`),b(d),f||g.assign(E,!0)},j=>{g.if((0,n._)`!(${j} instanceof ${h.ValidationError})`,()=>g.throw(j)),w(j),f||g.assign(E,!1)}),l.ok(E)}function k(){l.result((0,r.callValidateCode)(l,d,_),()=>b(d),()=>w(d))}function w(E){let j=(0,n._)`${E}.errors`;g.assign(o.default.vErrors,(0,n._)`${o.default.vErrors} === null ? ${j} : ${o.default.vErrors}.concat(${j})`),g.assign(o.default.errors,(0,n._)`${o.default.vErrors}.length`)}function b(E){var j;if(!h.opts.unevaluated)return;let V=(j=m?.validate)===null||j===void 0?void 0:j.evaluated;if(h.props!==!0)if(V&&!V.dynamicProps)V.props!==void 0&&(h.props=a.mergeEvaluated.props(g,V.props,h.props));else{let A=g.var("props",(0,n._)`${E}.evaluated.props`);h.props=a.mergeEvaluated.props(g,A,h.props,n.Name)}if(h.items!==!0)if(V&&!V.dynamicItems)V.items!==void 0&&(h.items=a.mergeEvaluated.items(g,V.items,h.items));else{let A=g.var("items",(0,n._)`${E}.evaluated.items`);h.items=a.mergeEvaluated.items(g,A,h.items,n.Name)}}}e.callRef=u,e.default=s})),rz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kP(),r=dg(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,r.default];e.default=n})),EP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=t.operators,n={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:i,schemaCode:a})=>(0,t.str)`must be ${n[i].okStr} ${a}`,params:({keyword:i,schemaCode:a})=>(0,t._)`{comparison: ${n[i].okStr}, limit: ${a}}`},code(i){let{keyword:a,data:s,schemaCode:c}=i;i.fail$data((0,t._)`${s} ${n[a].fail} ${c} || isNaN(${s})`)}};e.default=o})),RP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){let{gen:o,data:i,schemaCode:a,it:s}=n,c=s.opts.multipleOfPrecision,u=o.let("res"),l=c?(0,t._)`Math.abs(Math.round(${u}) - ${u}) > 1e-${c}`:(0,t._)`${u} !== parseInt(${u})`;n.fail$data((0,t._)`(${a} === 0 || (${u} = ${i}/${a}, ${l}))`)}};e.default=r})),xP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(r){let n=r.length,o=0,i=0,a;for(;i=55296&&a<=56319&&i{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=xP(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:i,schemaCode:a}){let s=i==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${s} than ${a} characters`},params:({schemaCode:i})=>(0,t._)`{limit: ${i}}`},code(i){let{keyword:a,data:s,schemaCode:c,it:u}=i,l=a==="maxLength"?t.operators.GT:t.operators.LT,d=u.opts.unicode===!1?(0,t._)`${s}.length`:(0,t._)`${(0,r.useFunc)(i.gen,n.default)}(${s})`;i.fail$data((0,t._)`${d} ${l} ${c}`)}};e.default=o})),PP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=Te(),n=ze(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:i})=>(0,n.str)`must match pattern "${i}"`,params:({schemaCode:i})=>(0,n._)`{pattern: ${i}}`},code(i){let{gen:a,data:s,$data:c,schema:u,schemaCode:l,it:d}=i,m=d.opts.unicodeRegExp?"u":"";if(c){let{regExp:v}=d.opts.code,g=v.code==="new RegExp"?(0,n._)`new RegExp`:(0,r.useFunc)(a,v),h=a.let("valid");a.try(()=>a.assign(h,(0,n._)`${g}(${l}, ${m}).test(${s})`),()=>a.assign(h,!1)),i.fail$data((0,n._)`!${h}`)}else{let v=(0,t.usePattern)(i,u);i.fail$data((0,n._)`!${v}.test(${s})`)}}};e.default=o})),TP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let i=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${o} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:i,schemaCode:a}=n,s=o==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${i}).length ${s} ${a}`)}};e.default=r})),CP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=ze(),n=Te(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:i}})=>(0,r.str)`must have required property '${i}'`,params:({params:{missingProperty:i}})=>(0,r._)`{missingProperty: ${i}}`},code(i){let{gen:a,schema:s,schemaCode:c,data:u,$data:l,it:d}=i,{opts:m}=d;if(!l&&s.length===0)return;let v=s.length>=m.loopRequired;if(d.allErrors?g():h(),m.strictRequired){let S=i.parentSchema.properties,{definedProperties:_}=i.it;for(let $ of s)if(S?.[$]===void 0&&!_.has($)){let k=`required property "${$}" is not defined at "${d.schemaEnv.baseId+d.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(d,k,d.opts.strictRequired)}}function g(){if(v||l)i.block$data(r.nil,f);else for(let S of s)(0,t.checkReportMissingProp)(i,S)}function h(){let S=a.let("missing");if(v||l){let _=a.let("valid",!0);i.block$data(_,()=>y(S,_)),i.ok(_)}else a.if((0,t.checkMissingProp)(i,s,S)),(0,t.reportMissingProp)(i,S),a.else()}function f(){a.forOf("prop",c,S=>{i.setParams({missingProperty:S}),a.if((0,t.noPropertyInData)(a,u,S,m.ownProperties),()=>i.error())})}function y(S,_){i.setParams({missingProperty:S}),a.forOf(S,c,()=>{a.assign(_,(0,t.propertyInData)(a,u,S,m.ownProperties)),a.if((0,r.not)(_),()=>{i.error(),a.break()})},r.nil)}}};e.default=o})),AP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let i=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${o} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:i,schemaCode:a}=n,s=o==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${i}.length ${s} ${a}`)}};e.default=r})),pg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qw();t.code='require("ajv/dist/runtime/equal").default',e.default=t})),OP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=sd(),r=ze(),n=Te(),o=pg(),i={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:s}})=>(0,r.str)`must NOT have duplicate items (items ## ${s} and ${a} are identical)`,params:({params:{i:a,j:s}})=>(0,r._)`{i: ${a}, j: ${s}}`},code(a){let{gen:s,data:c,$data:u,schema:l,parentSchema:d,schemaCode:m,it:v}=a;if(!u&&!l)return;let g=s.let("valid"),h=d.items?(0,t.getSchemaTypes)(d.items):[];a.block$data(g,f,(0,r._)`${m} === false`),a.ok(g);function f(){let $=s.let("i",(0,r._)`${c}.length`),k=s.let("j");a.setParams({i:$,j:k}),s.assign(g,!0),s.if((0,r._)`${$} > 1`,()=>(y()?S:_)($,k))}function y(){return h.length>0&&!h.some($=>$==="object"||$==="array")}function S($,k){let w=s.name("item"),b=(0,t.checkDataTypes)(h,w,v.opts.strictNumbers,t.DataType.Wrong),E=s.const("indices",(0,r._)`{}`);s.for((0,r._)`;${$}--;`,()=>{s.let(w,(0,r._)`${c}[${$}]`),s.if(b,(0,r._)`continue`),h.length>1&&s.if((0,r._)`typeof ${w} == "string"`,(0,r._)`${w} += "_"`),s.if((0,r._)`typeof ${E}[${w}] == "number"`,()=>{s.assign(k,(0,r._)`${E}[${w}]`),a.error(),s.assign(g,!1).break()}).code((0,r._)`${E}[${w}] = ${$}`)})}function _($,k){let w=(0,n.useFunc)(s,o.default),b=s.name("outer");s.label(b).for((0,r._)`;${$}--;`,()=>s.for((0,r._)`${k} = ${$}; ${k}--;`,()=>s.if((0,r._)`${w}(${c}[${$}], ${c}[${k}])`,()=>{a.error(),s.assign(g,!1).break(b)})))}}};e.default=i})),NP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=pg(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:i})=>(0,t._)`{allowedValue: ${i}}`},code(i){let{gen:a,data:s,$data:c,schemaCode:u,schema:l}=i;c||l&&typeof l=="object"?i.fail$data((0,t._)`!${(0,r.useFunc)(a,n.default)}(${s}, ${u})`):i.fail((0,t._)`${l} !== ${s}`)}};e.default=o})),jP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=pg(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:i})=>(0,t._)`{allowedValues: ${i}}`},code(i){let{gen:a,data:s,$data:c,schema:u,schemaCode:l,it:d}=i;if(!c&&u.length===0)throw new Error("enum must have non-empty array");let m=u.length>=d.opts.loopEnum,v,g=()=>v??(v=(0,r.useFunc)(a,n.default)),h;if(m||c)h=a.let("valid"),i.block$data(h,f);else{if(!Array.isArray(u))throw new Error("ajv implementation error");let S=a.const("vSchema",l);h=(0,t.or)(...u.map((_,$)=>y(S,$)))}i.pass(h);function f(){a.assign(h,!1),a.forOf("v",l,S=>a.if((0,t._)`${g()}(${s}, ${S})`,()=>a.assign(h,!0).break()))}function y(S,_){let $=u[_];return typeof $=="object"&&$!==null?(0,t._)`${g()}(${s}, ${S}[${_}])`:(0,t._)`${s} === ${$}`}}};e.default=o})),nz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=EP(),r=RP(),n=IP(),o=PP(),i=TP(),a=CP(),s=AP(),c=OP(),u=NP(),l=jP(),d=[t.default,r.default,n.default,o.default,i.default,a.default,s.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];e.default=d})),oz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=ze(),r=Te(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,t.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,t._)`{limit: ${i}}`},code(i){let{parentSchema:a,it:s}=i,{items:c}=a;if(!Array.isArray(c)){(0,r.checkStrictMode)(s,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(i,c)}};function o(i,a){let{gen:s,schema:c,data:u,keyword:l,it:d}=i;d.items=!0;let m=s.const("len",(0,t._)`${u}.length`);if(c===!1)i.setParams({len:a.length}),i.pass((0,t._)`${m} <= ${a.length}`);else if(typeof c=="object"&&!(0,r.alwaysValidSchema)(d,c)){let g=s.var("valid",(0,t._)`${m} <= ${a.length}`);s.if((0,t.not)(g),()=>v(g)),i.ok(g)}function v(g){s.forRange("i",a.length,m,h=>{i.subschema({keyword:l,dataProp:h,dataPropType:r.Type.Num},g),d.allErrors||s.if((0,t.not)(g),()=>s.break())})}}e.validateAdditionalItems=o,e.default=n})),iz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=ze(),r=Te(),n=Xt(),o={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){let{schema:s,it:c}=a;if(Array.isArray(s))return i(a,"additionalItems",s);c.items=!0,!(0,r.alwaysValidSchema)(c,s)&&a.ok((0,n.validateArray)(a))}};function i(a,s,c=a.schema){let{gen:u,parentSchema:l,data:d,keyword:m,it:v}=a;f(l),v.opts.unevaluated&&c.length&&v.items!==!0&&(v.items=r.mergeEvaluated.items(u,c.length,v.items));let g=u.name("valid"),h=u.const("len",(0,t._)`${d}.length`);c.forEach((y,S)=>{(0,r.alwaysValidSchema)(v,y)||(u.if((0,t._)`${h} > ${S}`,()=>a.subschema({keyword:m,schemaProp:S,dataProp:S},g)),a.ok(g))});function f(y){let{opts:S,errSchemaPath:_}=v,$=c.length,k=$===y.minItems&&($===y.maxItems||y[s]===!1);if(S.strictTuples&&!k){let w=`"${m}" is ${$}-tuple, but minItems or maxItems/${s} are not specified or different at path "${_}"`;(0,r.checkStrictMode)(v,w,S.strictTuples)}}}e.validateTuple=i,e.default=o})),UP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=iz(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,t.validateTuple)(n,"items")};e.default=r})),MP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=Xt(),o=oz(),i={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){let{schema:s,parentSchema:c,it:u}=a,{prefixItems:l}=c;u.items=!0,!(0,r.alwaysValidSchema)(u,s)&&(l?(0,o.validateAdditionalItems)(a,l):a.ok((0,n.validateArray)(a)))}};e.default=i})),DP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:i}})=>i===void 0?(0,t.str)`must contain at least ${o} valid item(s)`:(0,t.str)`must contain at least ${o} and no more than ${i} valid item(s)`,params:({params:{min:o,max:i}})=>i===void 0?(0,t._)`{minContains: ${o}}`:(0,t._)`{minContains: ${o}, maxContains: ${i}}`},code(o){let{gen:i,schema:a,parentSchema:s,data:c,it:u}=o,l,d,{minContains:m,maxContains:v}=s;u.opts.next?(l=m===void 0?1:m,d=v):l=1;let g=i.const("len",(0,t._)`${c}.length`);if(o.setParams({min:l,max:d}),d===void 0&&l===0){(0,r.checkStrictMode)(u,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(d!==void 0&&l>d){(0,r.checkStrictMode)(u,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,r.alwaysValidSchema)(u,a)){let _=(0,t._)`${g} >= ${l}`;d!==void 0&&(_=(0,t._)`${_} && ${g} <= ${d}`),o.pass(_);return}u.items=!0;let h=i.name("valid");d===void 0&&l===1?y(h,()=>i.if(h,()=>i.break())):l===0?(i.let(h,!0),d!==void 0&&i.if((0,t._)`${c}.length > 0`,f)):(i.let(h,!1),f()),o.result(h,()=>o.reset());function f(){let _=i.name("_valid"),$=i.let("count",0);y(_,()=>i.if(_,()=>S($)))}function y(_,$){i.forRange("i",0,g,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:r.Type.Num,compositeRule:!0},_),$()})}function S(_){i.code((0,t._)`${_}++`),d===void 0?i.if((0,t._)`${_} >= ${l}`,()=>i.assign(h,!0).break()):(i.if((0,t._)`${_} > ${d}`,()=>i.assign(h,!1).break()),l===1?i.assign(h,!0):i.if((0,t._)`${_} >= ${l}`,()=>i.assign(h,!0)))}}};e.default=n})),mg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=ze(),r=Te(),n=Xt();e.error={message:({params:{property:c,depsCount:u,deps:l}})=>{let d=u===1?"property":"properties";return(0,t.str)`must have ${d} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:d}})=>(0,t._)`{property: ${c}, + missingProperty: ${d}, + depsCount: ${u}, + deps: ${l}}`};let o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){let[u,l]=i(c);a(c,u),s(c,l)}};function i({schema:c}){let u={},l={};for(let d in c){if(d==="__proto__")continue;let m=Array.isArray(c[d])?u:l;m[d]=c[d]}return[u,l]}function a(c,u=c.schema){let{gen:l,data:d,it:m}=c;if(Object.keys(u).length===0)return;let v=l.let("missing");for(let g in u){let h=u[g];if(h.length===0)continue;let f=(0,n.propertyInData)(l,d,g,m.opts.ownProperties);c.setParams({property:g,depsCount:h.length,deps:h.join(", ")}),m.allErrors?l.if(f,()=>{for(let y of h)(0,n.checkReportMissingProp)(c,y)}):(l.if((0,t._)`${f} && (${(0,n.checkMissingProp)(c,h,v)})`),(0,n.reportMissingProp)(c,v),l.else())}}e.validatePropertyDeps=a;function s(c,u=c.schema){let{gen:l,data:d,keyword:m,it:v}=c,g=l.name("valid");for(let h in u)(0,r.alwaysValidSchema)(v,u[h])||(l.if((0,n.propertyInData)(l,d,h,v.opts.ownProperties),()=>{let f=c.subschema({keyword:m,schemaProp:h},g);c.mergeValidEvaluated(f,g)},()=>l.var(g,!0)),c.ok(g))}e.validateSchemaDeps=s,e.default=o})),qP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,t._)`{propertyName: ${o.propertyName}}`},code(o){let{gen:i,schema:a,data:s,it:c}=o;if((0,r.alwaysValidSchema)(c,a))return;let u=i.name("valid");i.forIn("key",s,l=>{o.setParams({propertyName:l}),o.subschema({keyword:"propertyNames",data:l,dataTypes:["string"],propertyName:l,compositeRule:!0},u),i.if((0,t.not)(u),()=>{o.error(!0),c.allErrors||i.break()})}),o.ok(u)}};e.default=n})),az=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=ze(),n=Gt(),o=Te(),i={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,r._)`{additionalProperty: ${a.additionalProperty}}`},code(a){let{gen:s,schema:c,parentSchema:u,data:l,errsCount:d,it:m}=a;if(!d)throw new Error("ajv implementation error");let{allErrors:v,opts:g}=m;if(m.props=!0,g.removeAdditional!=="all"&&(0,o.alwaysValidSchema)(m,c))return;let h=(0,t.allSchemaProperties)(u.properties),f=(0,t.allSchemaProperties)(u.patternProperties);y(),a.ok((0,r._)`${d} === ${n.default.errors}`);function y(){s.forIn("key",l,w=>{!h.length&&!f.length?$(w):s.if(S(w),()=>$(w))})}function S(w){let b;if(h.length>8){let E=(0,o.schemaRefOrVal)(m,u.properties,"properties");b=(0,t.isOwnProperty)(s,E,w)}else h.length?b=(0,r.or)(...h.map(E=>(0,r._)`${w} === ${E}`)):b=r.nil;return f.length&&(b=(0,r.or)(b,...f.map(E=>(0,r._)`${(0,t.usePattern)(a,E)}.test(${w})`))),(0,r.not)(b)}function _(w){s.code((0,r._)`delete ${l}[${w}]`)}function $(w){if(g.removeAdditional==="all"||g.removeAdditional&&c===!1){_(w);return}if(c===!1){a.setParams({additionalProperty:w}),a.error(),v||s.break();return}if(typeof c=="object"&&!(0,o.alwaysValidSchema)(m,c)){let b=s.name("valid");g.removeAdditional==="failing"?(k(w,b,!1),s.if((0,r.not)(b),()=>{a.reset(),_(w)})):(k(w,b),v||s.if((0,r.not)(b),()=>s.break()))}}function k(w,b,E){let j={keyword:"additionalProperties",dataProp:w,dataPropType:o.Type.Str};E===!1&&Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(j,b)}}};e.default=i})),LP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=hs(),r=Xt(),n=Te(),o=az(),i={keyword:"properties",type:"object",schemaType:"object",code(a){let{gen:s,schema:c,parentSchema:u,data:l,it:d}=a;d.opts.removeAdditional==="all"&&u.additionalProperties===void 0&&o.default.code(new t.KeywordCxt(d,o.default,"additionalProperties"));let m=(0,r.allSchemaProperties)(c);for(let y of m)d.definedProperties.add(y);d.opts.unevaluated&&m.length&&d.props!==!0&&(d.props=n.mergeEvaluated.props(s,(0,n.toHash)(m),d.props));let v=m.filter(y=>!(0,n.alwaysValidSchema)(d,c[y]));if(v.length===0)return;let g=s.name("valid");for(let y of v)h(y)?f(y):(s.if((0,r.propertyInData)(s,l,y,d.opts.ownProperties)),f(y),d.allErrors||s.else().var(g,!0),s.endIf()),a.it.definedProperties.add(y),a.ok(g);function h(y){return d.opts.useDefaults&&!d.compositeRule&&c[y].default!==void 0}function f(y){a.subschema({keyword:"properties",schemaProp:y,dataProp:y},g)}}};e.default=i})),VP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=ze(),n=Te(),o=Te(),i={keyword:"patternProperties",type:"object",schemaType:"object",code(a){let{gen:s,schema:c,data:u,parentSchema:l,it:d}=a,{opts:m}=d,v=(0,t.allSchemaProperties)(c),g=v.filter(k=>(0,n.alwaysValidSchema)(d,c[k]));if(v.length===0||g.length===v.length&&(!d.opts.unevaluated||d.props===!0))return;let h=m.strictSchema&&!m.allowMatchingProperties&&l.properties,f=s.name("valid");d.props!==!0&&!(d.props instanceof r.Name)&&(d.props=(0,o.evaluatedPropsToName)(s,d.props));let{props:y}=d;S();function S(){for(let k of v)h&&_(k),d.allErrors?$(k):(s.var(f,!0),$(k),s.if(f))}function _(k){for(let w in h)new RegExp(k).test(w)&&(0,n.checkStrictMode)(d,`property ${w} matches pattern ${k} (use allowMatchingProperties)`)}function $(k){s.forIn("key",u,w=>{s.if((0,r._)`${(0,t.usePattern)(a,k)}.test(${w})`,()=>{let b=g.includes(k);b||a.subschema({keyword:"patternProperties",schemaProp:k,dataProp:w,dataPropType:o.Type.Str},f),d.opts.unevaluated&&y!==!0?s.assign((0,r._)`${y}[${w}]`,!0):!b&&!d.allErrors&&s.if((0,r.not)(f),()=>s.break())})})}}};e.default=i})),KP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:o,schema:i,it:a}=n;if((0,t.alwaysValidSchema)(a,i)){n.fail();return}let s=o.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),n.failResult(s,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};e.default=r})),JP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Xt().validateUnion,error:{message:"must match a schema in anyOf"}};e.default=t})),FP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,t._)`{passingSchemas: ${o.passing}}`},code(o){let{gen:i,schema:a,parentSchema:s,it:c}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(c.opts.discriminator&&s.discriminator)return;let u=a,l=i.let("valid",!1),d=i.let("passing",null),m=i.name("_valid");o.setParams({passing:d}),i.block(v),o.result(l,()=>o.reset(),()=>o.error(!0));function v(){u.forEach((g,h)=>{let f;(0,r.alwaysValidSchema)(c,g)?i.var(m,!0):f=o.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},m),h>0&&i.if((0,t._)`${m} && ${l}`).assign(l,!1).assign(d,(0,t._)`[${d}, ${h}]`).else(),i.if(m,()=>{i.assign(l,!0),i.assign(d,h),f&&o.mergeEvaluated(f,t.Name)})})}}};e.default=n})),HP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:o,schema:i,it:a}=n;if(!Array.isArray(i))throw new Error("ajv implementation error");let s=o.name("valid");i.forEach((c,u)=>{if((0,t.alwaysValidSchema)(a,c))return;let l=n.subschema({keyword:"allOf",schemaProp:u},s);n.ok(s),n.mergeEvaluated(l)})}};e.default=r})),ZP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:i})=>(0,t.str)`must match "${i.ifClause}" schema`,params:({params:i})=>(0,t._)`{failingKeyword: ${i.ifClause}}`},code(i){let{gen:a,parentSchema:s,it:c}=i;s.then===void 0&&s.else===void 0&&(0,r.checkStrictMode)(c,'"if" without "then" and "else" is ignored');let u=o(c,"then"),l=o(c,"else");if(!u&&!l)return;let d=a.let("valid",!0),m=a.name("_valid");if(v(),i.reset(),u&&l){let h=a.let("ifClause");i.setParams({ifClause:h}),a.if(m,g("then",h),g("else",h))}else u?a.if(m,g("then")):a.if((0,t.not)(m),g("else"));i.pass(d,()=>i.error(!0));function v(){let h=i.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},m);i.mergeEvaluated(h)}function g(h,f){return()=>{let y=i.subschema({keyword:h},m);a.assign(d,m),i.mergeValidEvaluated(y,d),f?a.assign(f,(0,t._)`${h}`):i.setParams({ifClause:h})}}}};function o(i,a){let s=i.schema[a];return s!==void 0&&!(0,r.alwaysValidSchema)(i,s)}e.default=n})),WP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:o,it:i}){o.if===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "if" is ignored`)}};e.default=r})),sz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=oz(),r=UP(),n=iz(),o=MP(),i=DP(),a=mg(),s=qP(),c=az(),u=LP(),l=VP(),d=KP(),m=JP(),v=FP(),g=HP(),h=ZP(),f=WP();function y(S=!1){let _=[d.default,m.default,v.default,g.default,h.default,f.default,s.default,c.default,a.default,u.default,l.default];return S?_.push(r.default,o.default):_.push(t.default,n.default),_.push(i.default),_}e.default=y})),BP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,o){let{gen:i,data:a,$data:s,schema:c,schemaCode:u,it:l}=n,{opts:d,errSchemaPath:m,schemaEnv:v,self:g}=l;if(!d.validateFormats)return;s?h():f();function h(){let y=i.scopeValue("formats",{ref:g.formats,code:d.code.formats}),S=i.const("fDef",(0,t._)`${y}[${u}]`),_=i.let("fType"),$=i.let("format");i.if((0,t._)`typeof ${S} == "object" && !(${S} instanceof RegExp)`,()=>i.assign(_,(0,t._)`${S}.type || "string"`).assign($,(0,t._)`${S}.validate`),()=>i.assign(_,(0,t._)`"string"`).assign($,S)),n.fail$data((0,t.or)(k(),w()));function k(){return d.strictSchema===!1?t.nil:(0,t._)`${u} && !${$}`}function w(){let b=v.$async?(0,t._)`(${S}.async ? await ${$}(${a}) : ${$}(${a}))`:(0,t._)`${$}(${a})`,E=(0,t._)`(typeof ${$} == "function" ? ${b} : ${$}.test(${a}))`;return(0,t._)`${$} && ${$} !== true && ${_} === ${o} && !${E}`}}function f(){let y=g.formats[c];if(!y){k();return}if(y===!0)return;let[S,_,$]=w(y);S===o&&n.pass(b());function k(){if(d.strictSchema===!1){g.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${c}" ignored in schema at path "${m}"`}}function w(E){let j=E instanceof RegExp?(0,t.regexpCode)(E):d.code.formats?(0,t._)`${d.code.formats}${(0,t.getProperty)(c)}`:void 0,V=i.scopeValue("formats",{key:c,ref:E,code:j});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,t._)`${V}.validate`]:["string",E,V]}function b(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!v.$async)throw new Error("async format in sync schema");return(0,t._)`await ${$}(${a})`}return typeof _=="function"?(0,t._)`${$}(${a})`:(0,t._)`${$}.test(${a})`}}}};e.default=r})),cz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=[BP().default];e.default=t})),uz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],e.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]})),GP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rz(),r=nz(),n=sz(),o=cz(),i=uz(),a=[t.default,r.default,(0,n.default)(),o.default,i.metadataVocabulary,i.contentVocabulary];e.default=a})),XP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(r){r.Tag="tag",r.Mapping="mapping"})(t||(e.DiscrError=t={}))})),lz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=XP(),n=dd(),o=gs(),i=Te(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:s,tagName:c}})=>s===r.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:s,tag:c,tagName:u}})=>(0,t._)`{error: ${s}, tag: ${u}, tagValue: ${c}}`},code(s){let{gen:c,data:u,schema:l,parentSchema:d,it:m}=s,{oneOf:v}=d;if(!m.opts.discriminator)throw new Error("discriminator: requires discriminator option");let g=l.propertyName;if(typeof g!="string")throw new Error("discriminator: requires propertyName");if(l.mapping)throw new Error("discriminator: mapping is not supported");if(!v)throw new Error("discriminator: requires oneOf keyword");let h=c.let("valid",!1),f=c.const("tag",(0,t._)`${u}${(0,t.getProperty)(g)}`);c.if((0,t._)`typeof ${f} == "string"`,()=>y(),()=>s.error(!1,{discrError:r.DiscrError.Tag,tag:f,tagName:g})),s.ok(h);function y(){let $=_();c.if(!1);for(let k in $)c.elseIf((0,t._)`${f} === ${k}`),c.assign(h,S($[k]));c.else(),s.error(!1,{discrError:r.DiscrError.Mapping,tag:f,tagName:g}),c.endIf()}function S($){let k=c.name("valid"),w=s.subschema({keyword:"oneOf",schemaProp:$},k);return s.mergeEvaluated(w,t.Name),k}function _(){var $;let k={},w=E(d),b=!0;for(let A=0;A{t.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}})),dz=H(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let r=tz(),n=GP(),o=lz(),i=YP(),a=["/properties"],s="http://json-schema.org/draft-07/schema";var c=class extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let v=this.opts.$data?this.$dataMetaSchema(i,a):i;this.addMetaSchema(v,s,!1),this.refs["http://json-schema.org/schema"]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=hs();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=ze();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=ld();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var m=gs();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return m.default}})})),pz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=ze(),r=Gt(),n=dd(),o=dg(),i={keyword:"$dynamicAnchor",schemaType:"string",code:c=>a(c,c.schema)};function a(c,u){let{gen:l,it:d}=c;d.schemaEnv.root.dynamicAnchors[u]=!0;let m=(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(u)}`,v=d.errSchemaPath==="#"?d.validateName:s(c);l.if((0,t._)`!${m}`,()=>l.assign(m,v))}e.dynamicAnchor=a;function s(c){let{schemaEnv:u,schema:l,self:d}=c.it,{root:m,baseId:v,localRefs:g,meta:h}=u.root,{schemaId:f}=d.opts,y=new n.SchemaEnv({schema:l,schemaId:f,root:m,baseId:v,localRefs:g,meta:h});return n.compileSchema.call(d,y),(0,o.getValidate)(c,y)}e.default=i})),mz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=ze(),r=Gt(),n=dg(),o={keyword:"$dynamicRef",schemaType:"string",code:a=>i(a,a.schema)};function i(a,s){let{gen:c,keyword:u,it:l}=a;if(s[0]!=="#")throw new Error(`"${u}" only supports hash fragment reference`);let d=s.slice(1);if(l.allErrors)m();else{let g=c.let("valid",!1);m(g),a.ok(g)}function m(g){if(l.schemaEnv.root.dynamicAnchors[d]){let h=c.let("_v",(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(d)}`);c.if(h,v(h,g),v(l.validateName,g))}else v(l.validateName,g)()}function v(g,h){return h?()=>c.block(()=>{(0,n.callRef)(a,g),c.let(h,!0)}):()=>(0,n.callRef)(a,g)}}e.dynamicRef=i,e.default=o})),QP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=pz(),r=Te(),n={keyword:"$recursiveAnchor",schemaType:"boolean",code(o){o.schema?(0,t.dynamicAnchor)(o,""):(0,r.checkStrictMode)(o.it,"$recursiveAnchor: false is ignored")}};e.default=n})),eT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mz(),r={keyword:"$recursiveRef",schemaType:"string",code:n=>(0,t.dynamicRef)(n,n.schema)};e.default=r})),tT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=pz(),r=mz(),n=QP(),o=eT(),i=[t.default,r.default,n.default,o.default];e.default=i})),rT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mg(),r={keyword:"dependentRequired",type:"object",schemaType:"object",error:t.error,code:n=>(0,t.validatePropertyDeps)(n)};e.default=r})),nT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mg(),r={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0,t.validateSchemaDeps)(n)};e.default=r})),oT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:o,it:i}){o.contains===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "contains" is ignored`)}};e.default=r})),iT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rT(),r=nT(),n=oT(),o=[t.default,r.default,n.default];e.default=o})),aT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=Gt(),o={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:i})=>(0,t._)`{unevaluatedProperty: ${i.unevaluatedProperty}}`},code(i){let{gen:a,schema:s,data:c,errsCount:u,it:l}=i;if(!u)throw new Error("ajv implementation error");let{allErrors:d,props:m}=l;m instanceof t.Name?a.if((0,t._)`${m} !== true`,()=>a.forIn("key",c,f=>a.if(g(m,f),()=>v(f)))):m!==!0&&a.forIn("key",c,f=>m===void 0?v(f):a.if(h(m,f),()=>v(f))),l.props=!0,i.ok((0,t._)`${u} === ${n.default.errors}`);function v(f){if(s===!1){i.setParams({unevaluatedProperty:f}),i.error(),d||a.break();return}if(!(0,r.alwaysValidSchema)(l,s)){let y=a.name("valid");i.subschema({keyword:"unevaluatedProperties",dataProp:f,dataPropType:r.Type.Str},y),d||a.if((0,t.not)(y),()=>a.break())}}function g(f,y){return(0,t._)`!${f} || !${f}[${y}]`}function h(f,y){let S=[];for(let _ in f)f[_]===!0&&S.push((0,t._)`${y} !== ${_}`);return(0,t.and)(...S)}}};e.default=o})),sT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){let{gen:i,schema:a,data:s,it:c}=o,u=c.items||0;if(u===!0)return;let l=i.const("len",(0,t._)`${s}.length`);if(a===!1)o.setParams({len:u}),o.fail((0,t._)`${l} > ${u}`);else if(typeof a=="object"&&!(0,r.alwaysValidSchema)(c,a)){let m=i.var("valid",(0,t._)`${l} <= ${u}`);i.if((0,t.not)(m),()=>d(m,u)),o.ok(m)}c.items=!0;function d(m,v){i.forRange("i",v,l,g=>{o.subschema({keyword:"unevaluatedItems",dataProp:g,dataPropType:r.Type.Num},m),c.allErrors||i.if((0,t.not)(m),()=>i.break())})}}};e.default=n})),cT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=aT(),r=sT(),n=[t.default,r.default];e.default=n})),uT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rz(),r=nz(),n=sz(),o=tT(),i=iT(),a=cT(),s=cz(),c=uz(),u=[o.default,t.default,r.default,(0,n.default)(!0),s.default,c.metadataVocabulary,c.contentVocabulary,i.default,a.default];e.default=u})),lT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}})),dT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}})),pT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}})),mT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}})),fT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}})),hT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}})),gT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),yT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),vT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lT(),r=dT(),n=pT(),o=mT(),i=fT(),a=hT(),s=gT(),c=yT(),u=["/properties"];function l(d){return[t,r,n,o,i,m(this,a),s,m(this,c)].forEach(v=>this.addMetaSchema(v,void 0,!1)),this;function m(v,g){return d?v.$dataMetaSchema(g,u):g}}e.default=l})),_T=H(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2020=void 0;let r=tz(),n=uT(),o=lz(),i=vT(),a="https://json-schema.org/draft/2020-12/schema";var s=class extends r.default{constructor(m={}){super({...m,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:m,meta:v}=this.opts;v&&(i.default.call(this,m),this.refs["http://json-schema.org/schema"]=a)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}};e.Ajv2020=s,t.exports=e=s,t.exports.Ajv2020=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s;var c=hs();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=ze();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var l=ld();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return l.default}});var d=gs();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})),ST=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(A,L){return{validate:A,compare:L}}e.fullFormats={date:t(i,a),time:t(c(!0),u),"date-time":t(m(!0),v),"iso-time":t(c(),l),"iso-date-time":t(m(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"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:V,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:w},int64:{type:"number",validate:b},float:{type:"number",validate:E},double:{type:"number",validate:E},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,v),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(A){return A%4===0&&(A%100!==0||A%400===0)}let n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(A){let L=n.exec(A);if(!L)return!1;let Z=+L[1],J=+L[2],te=+L[3];return J>=1&&J<=12&&te>=1&&te<=(J===2&&r(Z)?29:o[J])}function a(A,L){if(A&&L)return A>L?1:A23||M>59||A&&!Ne)return!1;if(te<=23&&_e<=59&&ke<60)return!0;let K=_e-M*be,z=te-P*be-(K<0?1:0);return(z===23||z===-1)&&(K===59||K===-1)&&ke<61}}function u(A,L){if(!(A&&L))return;let Z=new Date("2020-01-01T"+A).valueOf(),J=new Date("2020-01-01T"+L).valueOf();if(Z&&J)return Z-J}function l(A,L){if(!(A&&L))return;let Z=s.exec(A),J=s.exec(L);if(Z&&J)return A=Z[1]+Z[2]+Z[3],L=J[1]+J[2]+J[3],A>L?1:A=$}function b(A){return Number.isInteger(A)}function E(){return!0}let j=/[^\\]\\Z/;function V(A){if(j.test(A))return!1;try{return new RegExp(A),!0}catch{return!1}}})),bT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=dz(),r=ze(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},i={message:({keyword:s,schemaCode:c})=>(0,r.str)`should be ${o[s].okStr} ${c}`,params:({keyword:s,schemaCode:c})=>(0,r._)`{comparison: ${o[s].okStr}, limit: ${c}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:i,code(s){let{gen:c,data:u,schemaCode:l,keyword:d,it:m}=s,{opts:v,self:g}=m;if(!v.validateFormats)return;let h=new t.KeywordCxt(m,g.RULES.all.format.definition,"format");h.$data?f():y();function f(){let _=c.scopeValue("formats",{ref:g.formats,code:v.code.formats}),$=c.const("fmt",(0,r._)`${_}[${h.schemaCode}]`);s.fail$data((0,r.or)((0,r._)`typeof ${$} != "object"`,(0,r._)`${$} instanceof RegExp`,(0,r._)`typeof ${$}.compare != "function"`,S($)))}function y(){let _=h.schema,$=g.formats[_];if(!$||$===!0)return;if(typeof $!="object"||$ instanceof RegExp||typeof $.compare!="function")throw new Error(`"${d}": format "${_}" does not define "compare" function`);let k=c.scopeValue("formats",{key:_,ref:$,code:v.code.formats?(0,r._)`${v.code.formats}${(0,r.getProperty)(_)}`:void 0});s.fail$data(S(k))}function S(_){return(0,r._)`${_}.compare(${u}, ${l}) ${o[d].fail} 0`}},dependencies:["format"]};let a=s=>(s.addKeyword(e.formatLimitDefinition),s);e.default=a})),$T=H(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let r=ST(),n=bT(),o=ze(),i=new o.Name("fullFormats"),a=new o.Name("fastFormats"),s=(u,l={keywords:!0})=>{if(Array.isArray(l))return c(u,l,r.fullFormats,i),u;let[d,m]=l.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,i];return c(u,l.formats||r.formatNames,d,m),l.keywords&&(0,n.default)(u),u};s.get=(u,l="full")=>{let d=(l==="fast"?r.fastFormats:r.fullFormats)[u];if(!d)throw new Error(`Unknown format "${u}"`);return d};function c(u,l,d,m){var v,g;(v=(g=u.opts.code).formats)!==null&&v!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${m}`);for(let h of l)u.addFormat(h,d[h])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),wT=dz(),zT=_T(),kT=cc($T(),1),ET=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),RT=kT.default;pd=class{_ajv;_userAjv;constructor(e){this._userAjv=e!==void 0,this._ajv=e}get ajv(){return this._ajv??=xT()}getValidator(e){if(!this._userAjv&&"$schema"in e&&typeof e.$schema=="string"&&!ET.has(e.$schema.replace(/#$/,""))){let n=e.$schema.slice(0,200);throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${n}"). The default validator supports JSON Schema 2020-12 only; pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.`)}let t=this.ajv,r="$id"in e&&typeof e.$id=="string"?t.getSchema(e.$id)??t.compile(e):t.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:t.errorsText(r.errors)}}},SD=wT.Ajv});var hz,gz=q(()=>{fz();hz=!1});async function IT(e){return(await fg).getRandomValues(new Uint8Array(e))}async function PT(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await TT(e),r=await CT(t);return{code_verifier:t,code_challenge:r}}var fg,yz=q(()=>{fg=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto)});function gg(e){}function fd(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=gg,onError:r=gg,onRetry:n=gg,onComment:o}=e,i="",a=!0,s,c="",u="";function l(h){let f=a?h.replace(/^\xEF\xBB\xBF/,""):h,[y,S]=AT(`${i}${f}`);for(let _ of y)d(_);i=S,a=!1}function d(h){if(h===""){v();return}if(h.startsWith(":")){o&&o(h.slice(h.startsWith(": ")?2:1));return}let f=h.indexOf(":");if(f!==-1){let y=h.slice(0,f),S=h[f+1]===" "?2:1,_=h.slice(f+S);m(y,_,h);return}m(h,"",h)}function m(h,f,y){switch(h){case"event":u=f;break;case"data":c=`${c}${f} +`;break;case"id":s=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?n(parseInt(f,10)):r(new md(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:y}));break;default:r(new md(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:f,line:y}));break}}function v(){c.length>0&&t({id:s,event:u||void 0,data:c.endsWith(` +`)?c.slice(0,-1):c}),s=void 0,c="",u=""}function g(h={}){i&&h.consume&&d(i),a=!0,s=void 0,c="",u="",i=""}return{feed:l,reset:g}}function AT(e){let t=[],r="",n=0;for(;n{md=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function OT(e){let t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function vg(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(vg).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${vg(e.cause)}`:e.message:`${e}`}function vz(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function NT(){let e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var gd,Sz,Eg,Ce,st,We,Pr,Pt,Kn,Ko,hd,yd,_s,Ho,Ss,cn,Jo,Zo,Fo,ys,Yt,_g,Sg,bg,_z,$g,wg,vs,zg,kg,Jn,bz=q(()=>{yg();gd=class extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(vz(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(vz(this),r)}};Sz=e=>{throw TypeError(e)},Eg=(e,t,r)=>t.has(e)||Sz("Cannot "+r),Ce=(e,t,r)=>(Eg(e,t,"read from private field"),r?r.call(e):t.get(e)),st=(e,t,r)=>t.has(e)?Sz("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),We=(e,t,r,n)=>(Eg(e,t,"write to private field"),t.set(e,r),r),Pr=(e,t,r)=>(Eg(e,t,"access private method"),r),Jn=class extends EventTarget{constructor(t,r){var n,o;super(),st(this,Yt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,st(this,Pt),st(this,Kn),st(this,Ko),st(this,hd),st(this,yd),st(this,_s),st(this,Ho),st(this,Ss,null),st(this,cn),st(this,Jo),st(this,Zo,null),st(this,Fo,null),st(this,ys,null),st(this,Sg,async i=>{var a;Ce(this,Jo).reset();let{body:s,redirected:c,status:u,headers:l}=i;if(u===204){Pr(this,Yt,vs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?We(this,Ko,new URL(i.url)):We(this,Ko,void 0),u!==200){Pr(this,Yt,vs).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){Pr(this,Yt,vs).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Ce(this,Pt)===this.CLOSED)return;We(this,Pt,this.OPEN);let d=new Event("open");if((a=Ce(this,ys))==null||a.call(this,d),this.dispatchEvent(d),typeof s!="object"||!s||!("getReader"in s)){Pr(this,Yt,vs).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let m=new TextDecoder,v=s.getReader(),g=!0;do{let{done:h,value:f}=await v.read();f&&Ce(this,Jo).feed(m.decode(f,{stream:!h})),h&&(g=!1,Ce(this,Jo).reset(),Pr(this,Yt,zg).call(this))}while(g)}),st(this,bg,i=>{We(this,cn,void 0),!(i.name==="AbortError"||i.type==="aborted")&&Pr(this,Yt,zg).call(this,vg(i))}),st(this,$g,i=>{typeof i.id=="string"&&We(this,Ss,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:Ce(this,Ko)?Ce(this,Ko).origin:Ce(this,Kn).origin,lastEventId:i.id||""});Ce(this,Fo)&&(!i.event||i.event==="message")&&Ce(this,Fo).call(this,a),this.dispatchEvent(a)}),st(this,wg,i=>{We(this,_s,i)}),st(this,kg,()=>{We(this,Ho,void 0),Ce(this,Pt)===this.CONNECTING&&Pr(this,Yt,_g).call(this)});try{if(t instanceof URL)We(this,Kn,t);else if(typeof t=="string")We(this,Kn,new URL(t,NT()));else throw new Error("Invalid URL")}catch{throw OT("An invalid or illegal string was specified")}We(this,Jo,fd({onEvent:Ce(this,$g),onRetry:Ce(this,wg)})),We(this,Pt,this.CONNECTING),We(this,_s,3e3),We(this,yd,(n=r?.fetch)!=null?n:globalThis.fetch),We(this,hd,(o=r?.withCredentials)!=null?o:!1),Pr(this,Yt,_g).call(this)}get readyState(){return Ce(this,Pt)}get url(){return Ce(this,Kn).href}get withCredentials(){return Ce(this,hd)}get onerror(){return Ce(this,Zo)}set onerror(t){We(this,Zo,t)}get onmessage(){return Ce(this,Fo)}set onmessage(t){We(this,Fo,t)}get onopen(){return Ce(this,ys)}set onopen(t){We(this,ys,t)}addEventListener(t,r,n){let o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){let o=r;super.removeEventListener(t,o,n)}close(){Ce(this,Ho)&&clearTimeout(Ce(this,Ho)),Ce(this,Pt)!==this.CLOSED&&(Ce(this,cn)&&Ce(this,cn).abort(),We(this,Pt,this.CLOSED),We(this,cn,void 0))}};Pt=new WeakMap,Kn=new WeakMap,Ko=new WeakMap,hd=new WeakMap,yd=new WeakMap,_s=new WeakMap,Ho=new WeakMap,Ss=new WeakMap,cn=new WeakMap,Jo=new WeakMap,Zo=new WeakMap,Fo=new WeakMap,ys=new WeakMap,Yt=new WeakSet,_g=function(){We(this,Pt,this.CONNECTING),We(this,cn,new AbortController),Ce(this,yd)(Ce(this,Kn),Pr(this,Yt,_z).call(this)).then(Ce(this,Sg)).catch(Ce(this,bg))},Sg=new WeakMap,bg=new WeakMap,_z=function(){var e;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ce(this,Ss)?{"Last-Event-ID":Ce(this,Ss)}:void 0},cache:"no-store",signal:(e=Ce(this,cn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},$g=new WeakMap,wg=new WeakMap,vs=function(e,t){var r;Ce(this,Pt)!==this.CLOSED&&We(this,Pt,this.CLOSED);let n=new gd("error",{code:t,message:e});(r=Ce(this,Zo))==null||r.call(this,n),this.dispatchEvent(n)},zg=function(e,t){var r;if(Ce(this,Pt)===this.CLOSED)return;We(this,Pt,this.CONNECTING);let n=new gd("error",{code:t,message:e});(r=Ce(this,Zo))==null||r.call(this,n),this.dispatchEvent(n),We(this,Ho,setTimeout(Ce(this,kg),Ce(this,_s)))},kg=new WeakMap,Jn.CONNECTING=0,Jn.OPEN=1,Jn.CLOSED=2});var vd,$z=q(()=>{yg();vd=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(i){o=fd({onEvent:a=>{i.enqueue(a)},onError(a){t==="terminate"?i.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(i){o.feed(i)}})}}});function ot(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Rg(e,t,r){if(t<0||t>=_d)throw new RangeError(`value must be >= 0 and <= ${_d-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function xg(e){let t=Math.floor(e/_d),r=e%_d,n=new Uint8Array(8);return Rg(n,t,0),Rg(n,r,4),n}function Sd(e){let t=new Uint8Array(4);return Rg(t,e),t}function Qe(e){let t=new Uint8Array(e.length);for(let r=0;r127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var Fn,ct,_d,gt=q(()=>{Fn=new TextEncoder,ct=new TextDecoder,_d=2**32});function bs(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n{});var $d={};nr($d,{decode:()=>mt,encode:()=>qe});function mt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:ct.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=ct.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return bd(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function qe(e){let t=e;return typeof t=="string"&&(t=Fn.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):bs(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var ft=q(()=>{gt();Ig()});function jT(e){return parseInt(e.name.slice(4),10)}function wd(e,t){if(jT(e.hash)!==t)throw wt(`SHA-${t}`,"algorithm.hash")}function UT(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function wz(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function zz(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!dr(e.algorithm,"HMAC"))throw wt("HMAC");wd(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!dr(e.algorithm,"RSASSA-PKCS1-v1_5"))throw wt("RSASSA-PKCS1-v1_5");wd(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!dr(e.algorithm,"RSA-PSS"))throw wt("RSA-PSS");wd(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!dr(e.algorithm,"Ed25519"))throw wt("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!dr(e.algorithm,t))throw wt(t);break}case"ES256":case"ES384":case"ES512":{if(!dr(e.algorithm,"ECDSA"))throw wt("ECDSA");let n=UT(t);if(e.algorithm.namedCurve!==n)throw wt(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}wz(e,r)}function Mt(e,t,r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!dr(e.algorithm,"AES-GCM"))throw wt("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw wt(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!dr(e.algorithm,"AES-KW"))throw wt("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw wt(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":break;default:throw wt("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!dr(e.algorithm,"PBKDF2"))throw wt("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!dr(e.algorithm,"RSA-OAEP"))throw wt("RSA-OAEP");wd(e.algorithm,parseInt(t.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}wz(e,r)}var wt,dr,Hn=q(()=>{wt=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),dr=(e,t)=>e.name===t});function kz(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Vt,Pg,Zn=q(()=>{Vt=(e,...t)=>kz("Key must be ",e,...t),Pg=(e,t,...r)=>kz(`Key for the ${e} algorithm must be `,t,...r)});var Tg={};nr(Tg,{JOSEAlgNotAllowed:()=>un,JOSEError:()=>it,JOSENotSupported:()=>he,JWEDecryptionFailed:()=>Tr,JWEInvalid:()=>Q,JWKInvalid:()=>$s,JWKSInvalid:()=>Bo,JWKSMultipleMatchingKeys:()=>ws,JWKSNoMatchingKey:()=>Wn,JWKSTimeout:()=>zs,JWSInvalid:()=>Ae,JWSSignatureVerificationFailed:()=>Bn,JWTClaimValidationFailed:()=>ht,JWTExpired:()=>Wo,JWTInvalid:()=>tt});var it,ht,Wo,un,he,Tr,Q,Ae,tt,$s,Bo,Wn,ws,zs,Bn,Oe=q(()=>{it=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},ht=class extends it{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},Wo=class extends it{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},un=class extends it{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},he=class extends it{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Tr=class extends it{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}},Q=class extends it{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Ae=class extends it{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},tt=class extends it{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},$s=class extends it{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},Bo=class extends it{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Wn=class extends it{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},ws=class extends it{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}},zs=class extends it{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}},Bn=class extends it{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}}});function Go(e){if(!Qt(e))throw new Error("CryptoKey instance expected")}var Qt,Gn,ks,ln=q(()=>{Qt=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Gn=e=>e?.[Symbol.toStringTag]==="KeyObject",ks=e=>Qt(e)||Gn(e)});function kd(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new he(`Unsupported JWE Algorithm: ${e}`)}}function zd(e,t){let r=e.byteLength<<3;if(r!==t)throw new Q(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}function Ez(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new he(`Unsupported JWE Algorithm: ${e}`)}}function Rz(e,t){if(t.length<<3!==Ez(e))throw new Q("Invalid Initialization Vector length")}async function xz(e,t,r){if(!(t instanceof Uint8Array))throw new TypeError(Vt(t,"Uint8Array"));let n=parseInt(e.slice(1,4),10),o=await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:o,macKey:i,keySize:n}}async function Iz(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function DT(e,t,r,n,o){let{encKey:i,macKey:a,keySize:s}=await xz(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),u=ot(o,n,c,xg(o.length<<3)),l=await Iz(a,u,s);return{ciphertext:c,tag:l,iv:n}}async function qT(e,t){if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign(r,n,e)),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),a=0,s=-1;for(;++s<32;)a|=o[s]^i[s];return a===0}async function LT(e,t,r,n,o,i){let{encKey:a,macKey:s,keySize:c}=await xz(e,t,"decrypt"),u=ot(i,n,r,xg(i.length<<3)),l=await Iz(s,u,c),d;try{d=await qT(o,l)}catch{}if(!d)throw new Tr;let m;try{m=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},a,r))}catch{}if(!m)throw new Tr;return m}async function VT(e,t,r,n,o){let i;r instanceof Uint8Array?i=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(Mt(r,e,"encrypt"),i=r);let a=new Uint8Array(await crypto.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},i,t)),s=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:s,iv:n}}async function KT(e,t,r,n,o,i){let a;t instanceof Uint8Array?a=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(Mt(t,e,"decrypt"),a=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},a,ot(r,o)))}catch{throw new Tr}}async function Ed(e,t,r,n,o){if(!Qt(r)&&!(r instanceof Uint8Array))throw new TypeError(Vt(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Rz(e,n):n=MT(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&zd(r,parseInt(e.slice(-3),10)),DT(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&zd(r,parseInt(e.slice(1,4),10)),VT(e,t,r,n,o);default:throw new he(Pz)}}async function Rd(e,t,r,n,o,i){if(!Qt(t)&&!(t instanceof Uint8Array))throw new TypeError(Vt(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Q("JWE Initialization Vector missing");if(!o)throw new Q("JWE Authentication Tag missing");switch(Rz(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&zd(t,parseInt(e.slice(-3),10)),LT(e,t,r,n,o,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&zd(t,parseInt(e.slice(1,4),10)),KT(e,t,r,n,o,i);default:throw new he(Pz)}}var pr,MT,Pz,Xn=q(()=>{gt();Hn();Zn();Oe();ln();pr=e=>crypto.getRandomValues(new Uint8Array(kd(e)>>3));MT=e=>crypto.getRandomValues(new Uint8Array(Ez(e)>>3));Pz="Unsupported JWE Content Encryption Algorithm"});function Be(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function zt(e,t,r){try{return mt(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}async function Id(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}var xd,er=q(()=>{ft();xd=Symbol()});function Ue(e){if(!JT(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function mr(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var JT,Yn,Tz,Cz,Az,rt=q(()=>{JT=e=>typeof e=="object"&&e!==null;Yn=e=>Ue(e)&&typeof e.kty=="string",Tz=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),Cz=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Az=e=>e.kty==="oct"&&typeof e.k=="string"});function Oz(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Nz(e,t,r){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):(Mt(e,t,r),e)}async function Es(e,t,r){let n=await Nz(t,e,"wrapKey");Oz(n,e);let o=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",o,n,"AES-KW"))}async function Rs(e,t,r){let n=await Nz(t,e,"unwrapKey");Oz(n,e);let o=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",o))}var Cg=q(()=>{Hn()});function Ag(e){return ot(Sd(e.length),e)}async function HT(e,t,r){let n=t>>3,o=32,i=Math.ceil(n/o),a=new Uint8Array(i*o);for(let s=1;s<=i;s++){let c=new Uint8Array(4+e.length+r.length);c.set(Sd(s),0),c.set(e,4),c.set(r,4+e.length);let u=await Id("sha256",c);a.set(u,(s-1)*o)}return a.slice(0,n)}async function Og(e,t,r,n,o=new Uint8Array,i=new Uint8Array){Mt(e,"ECDH"),Mt(t,"ECDH","deriveBits");let a=Ag(Qe(r)),s=Ag(o),c=Ag(i),u=Sd(n),l=new Uint8Array,d=ot(a,s,c,u,l),m=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,ZT(e)));return HT(m,n,d)}function ZT(e){return e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function Ng(e){switch(e.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return e.algorithm.name==="X25519"}}var Uz=q(()=>{gt();Hn();er()});function BT(e,t){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]):(Mt(e,t,"deriveBits"),e)}async function Mz(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new Q("PBES2 Salt Input must be 8 or more octets");let o=GT(t,e),i=parseInt(t.slice(13,16),10),a={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s=await BT(n,t);return new Uint8Array(await crypto.subtle.deriveBits(a,s,i))}async function Dz(e,t,r,n=2048,o=crypto.getRandomValues(new Uint8Array(16))){let i=await Mz(o,e,n,t);return{encryptedKey:await Es(e.slice(-6),i,r),p2c:n,p2s:qe(o)}}async function qz(e,t,r,n,o){let i=await Mz(o,e,n,t);return Rs(e.slice(-6),i,r)}var GT,Lz=q(()=>{ft();Cg();Hn();gt();Oe();GT=(e,t)=>ot(Qe(e),Uint8Array.of(0),t)});function xs(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Vz(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new he(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Kz(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Vt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return zz(t,e,r),t}async function Jz(e,t,r){let n=await Kz(e,t,"sign");xs(e,n);let o=await crypto.subtle.sign(Vz(e,n.algorithm),n,r);return new Uint8Array(o)}async function Fz(e,t,r,n){let o=await Kz(e,t,"verify");xs(e,o);let i=Vz(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var Pd=q(()=>{Oe();Hn();Zn()});async function Zz(e,t,r){return Mt(t,e,"encrypt"),xs(e,t),new Uint8Array(await crypto.subtle.encrypt(Hz(e),t,r))}async function Wz(e,t,r){return Mt(t,e,"decrypt"),xs(e,t),new Uint8Array(await crypto.subtle.decrypt(Hz(e),t,r))}var Hz,Bz=q(()=>{Hn();Pd();Oe();Hz=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new he(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}});function QT(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new he(Td)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new he(Td)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new he(Td)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new he(Td)}break}default:throw new he('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function Xo(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=QT(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var Td,jg=q(()=>{Oe();Td='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function Kt(e,t){if(e instanceof Uint8Array||Qt(e))return e;if(Gn(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return eC(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return Gz(e,r,t)}if(Yn(e))return e.k?mt(e.k):Gz(e,e,t,!0);throw new Error("unreachable")}var Yo,Qo,Gz,eC,Qn=q(()=>{rt();ft();jg();ln();Yo="given KeyObject instance cannot be used for this algorithm",Gz=async(e,t,r,n=!1)=>{Qo||=new WeakMap;let o=Qo.get(e);if(o?.[r])return o[r];let i=await Xo({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:Qo.set(e,{[r]:i}),i},eC=(e,t)=>{Qo||=new WeakMap;let r=Qo.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Yo)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(Yo);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(Yo);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let a;switch(t){case"RSA-OAEP":a="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":a="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":a="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":a="SHA-512";break;default:throw new TypeError(Yo)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:a},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:a},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let s=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!s)throw new TypeError(Yo);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[t]&&s===c[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:s},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(Yo);return r?r[t]=i:Qo.set(e,{[t]:i}),i}});function rC(e){fr(e,48,"Invalid PKCS#8 structure"),tr(e),fr(e,2,"Expected version field");let t=tr(e);e.pos+=t,fr(e,48,"Expected algorithm identifier");let r=tr(e);return{algIdStart:e.pos,algIdLength:r}}function nC(e){fr(e,48,"Invalid SPKI structure"),tr(e),fr(e,48,"Expected algorithm identifier");let t=tr(e);return{algIdStart:e.pos,algIdLength:t}}function oC(e){let t=Dg(e);fr(t,48,"Invalid certificate structure"),tr(t),fr(t,48,"Invalid tbsCertificate structure"),tr(t),e[t.pos]===160?Mg(t,6):Mg(t,5);let r=t.pos;fr(t,48,"Invalid SPKI structure");let n=tr(t);return e.subarray(r,r+n+(t.pos-r))}function iC(e){let t=qg(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);return oC(t)}var Xz,Yz,Qz,e0,Ug,Dg,tr,Mg,fr,t0,tC,r0,n0,qg,o0,Lg,i0,Vg=q(()=>{Zn();Ig();Oe();ln();Xz=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` +`);return`-----BEGIN ${t}----- +${r} +-----END ${t}-----`},Yz=async(e,t,r)=>{if(Gn(r)){if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return r.export({format:"pem",type:t})}if(!Qt(r))throw new TypeError(Vt(r,"CryptoKey","KeyObject"));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return Xz(bs(new Uint8Array(await crypto.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Qz=e=>Yz("public","spki",e),e0=e=>Yz("private","pkcs8",e),Ug=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r({data:e,pos:0}),tr=e=>{let t=e.data[e.pos++];if(t&128){let r=t&127,n=0;for(let o=0;o{if(t<=0)return;e.pos++;let r=tr(e);e.pos+=r,t>1&&Mg(e,t-1)},fr=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},t0=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},tC=e=>{fr(e,6,"Expected algorithm OID");let t=tr(e);return t0(e,t)};r0=e=>{let t=tC(e);if(Ug(t,[43,101,110]))return"X25519";if(!Ug(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");fr(e,6,"Expected curve OID");let r=tr(e),n=t0(e,r);for(let{name:o,oid:i}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(Ug(n,i))return o;throw new Error("Unsupported named curve")},n0=async(e,t,r,n)=>{let o,i,a=e==="spki",s=()=>a?["verify"]:["sign"],c=()=>a?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},i=s();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},i=s();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},i=c();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},i=s();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let u=n.getNamedCurve(t);o=u==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:u}}catch{throw new he("Invalid or unsupported key format")}i=a?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},i=s();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},i=s();break;default:throw new he('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!a,i)},qg=(e,t)=>bd(e.replace(t,"")),o0=(e,t,r)=>{let n=qg(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=i=>{let a=Dg(i);return rC(a),r0(a)}),n0("pkcs8",n,t,o)},Lg=(e,t,r)=>{let n=qg(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=i=>{let a=Dg(i);return nC(a),r0(a)}),n0("spki",n,t,o)};i0=(e,t,r)=>{let n;try{n=iC(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return Lg(Xz(bs(n),"PUBLIC KEY"),t,r)}});async function a0(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Lg(e,t,r)}async function s0(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return i0(e,t,r)}async function c0(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return o0(e,t,r)}async function dn(e,t,r){if(!Ue(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return mt(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new he('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return Xo({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return Xo({...e,ext:n})}case"EC":case"OKP":return Xo({...e,alg:t,ext:n});default:throw new he('Unsupported "kty" (Key Type) Parameter value')}}var Is=q(()=>{ft();Vg();jg();Oe();rt()});async function u0(e){if(Gn(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:qe(e)};if(!Qt(e))throw new TypeError(Vt(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...i}=await crypto.subtle.exportKey("jwk",e);return i.kty==="AKP"&&(i.alg=n),i}var l0=q(()=>{Zn();ft();ln()});async function d0(e){return Qz(e)}async function p0(e){return e0(e)}async function ei(e){return u0(e)}var Cd=q(()=>{Vg();l0()});async function m0(e,t,r,n){let o=e.slice(0,7),i=await Ed(o,r,t,n,new Uint8Array);return{encryptedKey:i.ciphertext,iv:qe(i.iv),tag:qe(i.tag)}}async function f0(e,t,r,n,o){let i=e.slice(0,7);return Rd(i,t,r,n,o,new Uint8Array)}var h0=q(()=>{Xn();ft()});function Ps(e){if(e===void 0)throw new Q("JWE Encrypted Key missing")}async function y0(e,t,r,n,o){switch(e){case"dir":{if(r!==void 0)throw new Q("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new Q("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ue(n.epk))throw new Q('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(Go(t),!Ng(t))throw new he("ECDH with the provided key is not allowed or not supported by your javascript runtime");let i=await dn(n.epk,e);Go(i);let a,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Q('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=zt(n.apu,"apu",Q)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Q('JOSE Header "apv" (Agreement PartyVInfo) invalid');s=zt(n.apv,"apv",Q)}let c=await Og(i,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?kd(n.enc):parseInt(e.slice(-5,-2),10),a,s);return e==="ECDH-ES"?c:(Ps(r),Rs(e.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return Ps(r),Go(t),Wz(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(Ps(r),typeof n.p2c!="number")throw new Q('JOSE Header "p2c" (PBES2 Count) missing or invalid');let i=o?.maxPBES2Count||1e4;if(n.p2c>i)throw new Q('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Q('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let a;return a=zt(n.p2s,"p2s",Q),qz(e,t,r,n.p2c,a)}case"A128KW":case"A192KW":case"A256KW":return Ps(r),Rs(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(Ps(r),typeof n.iv!="string")throw new Q('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Q('JOSE Header "tag" (Authentication Tag) missing or invalid');let i;i=zt(n.iv,"iv",Q);let a;return a=zt(n.tag,"tag",Q),f0(e,t,r,i,a)}default:throw new he(g0)}}async function Ad(e,t,r,n,o={}){let i,a,s;switch(e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(Go(r),!Ng(r))throw new he("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:u}=o,l;o.epk?l=await Kt(o.epk,e):l=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:m,crv:v,kty:g}=await ei(l),h=await Og(r,l,e==="ECDH-ES"?t:e,e==="ECDH-ES"?kd(t):parseInt(e.slice(-5,-2),10),c,u);if(a={epk:{x:d,crv:v,kty:g}},g==="EC"&&(a.epk.y=m),c&&(a.apu=qe(c)),u&&(a.apv=qe(u)),e==="ECDH-ES"){s=h;break}s=n||pr(t);let f=e.slice(-6);i=await Es(f,h,s);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||pr(t),Go(r),i=await Zz(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||pr(t);let{p2c:c,p2s:u}=o;({encryptedKey:i,...a}=await Dz(e,r,s,c,u));break}case"A128KW":case"A192KW":case"A256KW":{s=n||pr(t),i=await Es(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||pr(t);let{iv:c}=o;({encryptedKey:i,...a}=await m0(e,r,s,c));break}default:throw new he(g0)}return{cek:s,encryptedKey:i,parameters:a}}var g0,Od=q(()=>{Cg();Uz();Lz();Bz();ft();Qn();Oe();er();Xn();Is();Cd();rt();h0();ln();g0='Invalid or unsupported "alg" (JWE Algorithm) header value'});function hr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let a of n.crit){if(!i.has(a))throw new he(`Extension Header Parameter "${a}" is not recognized`);if(o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var ti=q(()=>{Oe()});function Ts(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var Kg=q(()=>{});function gr(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":aC(e,t,r);break;default:sC(e,t,r)}}var ri,Jg,aC,sC,ni=q(()=>{Zn();ln();rt();ri=e=>e?.[Symbol.toStringTag],Jg=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},aC=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(Yn(t)){if(Az(t)&&Jg(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ks(t))throw new TypeError(Pg(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ri(t)} instances for symmetric algorithms must be of type "secret"`)}},sC=(e,t,r)=>{if(Yn(t))switch(r){case"decrypt":case"sign":if(Tz(t)&&Jg(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Cz(t)&&Jg(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ks(t))throw new TypeError(Pg(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${ri(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${ri(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ri(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${ri(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ri(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function v0(e){if(typeof globalThis[e]>"u")throw new he(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function _0(e){v0("CompressionStream");let t=new CompressionStream("deflate-raw"),r=t.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let n=[],o=t.readable.getReader();for(;;){let{value:i,done:a}=await o.read();if(a)break;n.push(i)}return ot(...n)}async function S0(e,t){v0("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let o=[],i=0,a=r.readable.getReader();for(;;){let{value:s,done:c}=await a.read();if(c)break;if(o.push(s),i+=s.byteLength,t!==1/0&&i>t)throw new Q("Decompressed plaintext exceeded the configured limit")}return ot(...o)}var Fg=q(()=>{Oe();gt()});async function oi(e,t,r){if(!Ue(e))throw new Q("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new Q("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new Q("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new Q("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new Q("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new Q("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new Q("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new Q("JWE AAD incorrect type");if(e.header!==void 0&&!Ue(e.header))throw new Q("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!Ue(e.unprotected))throw new Q("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let $=mt(e.protected);n=JSON.parse(ct.decode($))}catch{throw new Q("JWE Protected Header is invalid")}if(!mr(n,e.header,e.unprotected))throw new Q("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...n,...e.header,...e.unprotected};if(hr(Q,new Map,r?.crit,n,o),o.zip!==void 0&&o.zip!=="DEF")throw new he('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(o.zip!==void 0&&!n?.zip)throw new Q('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:a}=o;if(typeof i!="string"||!i)throw new Q("missing JWE Algorithm (alg) in JWE Header");if(typeof a!="string"||!a)throw new Q("missing JWE Encryption Algorithm (enc) in JWE Header");let s=r&&Ts("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&Ts("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(s&&!s.has(i)||!s&&i.startsWith("PBES2"))throw new un('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(a))throw new un('"enc" (Encryption Algorithm) Header Parameter value not allowed');let u;e.encrypted_key!==void 0&&(u=zt(e.encrypted_key,"encrypted_key",Q));let l=!1;typeof t=="function"&&(t=await t(n,e),l=!0),gr(i==="dir"?a:i,t,"decrypt");let d=await Kt(t,i),m;try{m=await y0(i,d,u,o,r)}catch($){if($ instanceof TypeError||$ instanceof Q||$ instanceof he)throw $;m=pr(a)}let v,g;e.iv!==void 0&&(v=zt(e.iv,"iv",Q)),e.tag!==void 0&&(g=zt(e.tag,"tag",Q));let h=e.protected!==void 0?Qe(e.protected):new Uint8Array,f;e.aad!==void 0?f=ot(h,Qe("."),Qe(e.aad)):f=h;let y=zt(e.ciphertext,"ciphertext",Q),S=await Rd(a,m,y,v,g,f),_={plaintext:S};if(o.zip==="DEF"){let $=r?.maxDecompressedLength??25e4;if($===0)throw new he('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if($!==1/0&&(!Number.isSafeInteger($)||$<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");_.plaintext=await S0(S,$).catch(k=>{throw k instanceof Q?k:new Q("Failed to decompress plaintext",{cause:k})})}return e.protected!==void 0&&(_.protectedHeader=n),e.aad!==void 0&&(_.additionalAuthenticatedData=zt(e.aad,"aad",Q)),e.unprotected!==void 0&&(_.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(_.unprotectedHeader=e.header),l?{..._,key:d}:_}var Nd=q(()=>{ft();Xn();er();Oe();rt();rt();Od();gt();Xn();ti();Kg();Qn();ni();Fg()});async function jd(e,t,r){if(e instanceof Uint8Array&&(e=ct.decode(e)),typeof e!="string")throw new Q("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:i,3:a,4:s,length:c}=e.split(".");if(c!==5)throw new Q("Invalid Compact JWE");let u=await oi({ciphertext:a,iv:i||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),l={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t=="function"?{...l,key:u.key}:l}var Hg=q(()=>{Nd();Oe();gt()});async function b0(e,t,r){if(!Ue(e))throw new Q("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(Ue))throw new Q("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new Q("JWE Recipients has no members");for(let n of e.recipients)try{return await oi({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new Tr}var $0=q(()=>{Nd();Oe();rt()});var Cr,Ud=q(()=>{ft();er();Xn();Od();Oe();rt();gt();ti();Qn();ni();Fg();Cr=class{#e;#t;#r;#n;#i;#a;#s;#o;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=t}setKeyManagementParameters(t){return Be(this.#o,"setKeyManagementParameters"),this.#o=t,this}setProtectedHeader(t){return Be(this.#t,"setProtectedHeader"),this.#t=t,this}setSharedUnprotectedHeader(t){return Be(this.#r,"setSharedUnprotectedHeader"),this.#r=t,this}setUnprotectedHeader(t){return Be(this.#n,"setUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#i=t,this}setContentEncryptionKey(t){return Be(this.#a,"setContentEncryptionKey"),this.#a=t,this}setInitializationVector(t){return Be(this.#s,"setInitializationVector"),this.#s=t,this}async encrypt(t,r){if(!this.#t&&!this.#n&&!this.#r)throw new Q("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!mr(this.#t,this.#n,this.#r))throw new Q("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(hr(Q,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new he('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Q('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:o,enc:i}=n;if(typeof o!="string"||!o)throw new Q('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof i!="string"||!i)throw new Q('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(this.#a&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);gr(o==="dir"?i:o,t,"encrypt");let s;{let y,S=await Kt(t,o);({cek:s,encryptedKey:a,parameters:y}=await Ad(o,i,S,this.#a,this.#o)),y&&(r&&xd in r?this.#n?this.#n={...this.#n,...y}:this.setUnprotectedHeader(y):this.#t?this.#t={...this.#t,...y}:this.setProtectedHeader(y))}let c,u,l,d;if(this.#t?(u=qe(JSON.stringify(this.#t)),l=Qe(u)):(u="",l=new Uint8Array),this.#i){d=qe(this.#i);let y=Qe(d);c=ot(l,Qe("."),y)}else c=l;let m=this.#e;n.zip==="DEF"&&(m=await _0(m).catch(y=>{throw new Q("Failed to compress plaintext",{cause:y})}));let{ciphertext:v,tag:g,iv:h}=await Ed(i,m,s,this.#s,c),f={ciphertext:qe(v)};return h&&(f.iv=qe(h)),g&&(f.tag=qe(g)),a&&(f.encrypted_key=qe(a)),d&&(f.aad=d),this.#t&&(f.protected=u),this.#r&&(f.unprotected=this.#r),this.#n&&(f.header=this.#n),f}}});var Zg,Md,w0=q(()=>{Ud();er();Oe();Xn();rt();Od();ft();ti();Qn();ni();Zg=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(t,r,n){this.#e=t,this.key=r,this.options=n}setUnprotectedHeader(t){return Be(this.unprotectedHeader,"setUnprotectedHeader"),this.unprotectedHeader=t,this}setKeyManagementParameters(t){return Be(this.keyManagementParameters,"setKeyManagementParameters"),this.keyManagementParameters=t,this}addRecipient(...t){return this.#e.addRecipient(...t)}encrypt(...t){return this.#e.encrypt(...t)}done(){return this.#e}},Md=class{#e;#t=[];#r;#n;#i;constructor(t){this.#e=t}addRecipient(t,r){let n=new Zg(this,t,{crit:r?.crit});return this.#t.push(n),n}setProtectedHeader(t){return Be(this.#r,"setProtectedHeader"),this.#r=t,this}setSharedUnprotectedHeader(t){return Be(this.#n,"setSharedUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#i=t,this}async encrypt(){if(!this.#t.length)throw new Q("at least one recipient must be added");if(this.#t.length===1){let[o]=this.#t,i=await new Cr(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#r).setSharedUnprotectedHeader(this.#n).setUnprotectedHeader(o.unprotectedHeader).encrypt(o.key,{...o.options}),a={ciphertext:i.ciphertext,iv:i.iv,recipients:[{}],tag:i.tag};return i.aad&&(a.aad=i.aad),i.protected&&(a.protected=i.protected),i.unprotected&&(a.unprotected=i.unprotected),i.encrypted_key&&(a.recipients[0].encrypted_key=i.encrypted_key),i.header&&(a.recipients[0].header=i.header),a}let t;for(let o=0;o{ft();Pd();Oe();gt();er();rt();rt();ni();ti();Kg();Qn()});async function qd(e,t,r){if(e instanceof Uint8Array&&(e=ct.decode(e)),typeof e!="string")throw new Ae("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:a}=e.split(".");if(a!==3)throw new Ae("Invalid Compact JWS");let s=await ii({payload:o,protected:n,signature:i},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...c,key:s.key}:c}var Wg=q(()=>{Dd();Oe();gt()});async function z0(e,t,r){if(!Ue(e))throw new Ae("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(Ue))throw new Ae("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await ii({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Bn}var k0=q(()=>{Dd();Oe();rt()});function Cs(e){let t=lC.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*R0);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*x0);break;case"day":case"days":case"d":o=Math.round(r*Bg);break;case"week":case"weeks":case"w":o=Math.round(r*cC);break;default:o=Math.round(r*uC);break}return t[1]==="-"||t[4]==="ago"?-o:o}function eo(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function ai(e,t,r={}){let n;try{n=JSON.parse(ct.decode(t))}catch{}if(!Ue(n))throw new tt("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||E0(e.typ)!==E0(o)))throw new ht('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=r,l=[...i];u!==void 0&&l.push("iat"),c!==void 0&&l.push("aud"),s!==void 0&&l.push("sub"),a!==void 0&&l.push("iss");for(let g of new Set(l.reverse()))if(!(g in n))throw new ht(`missing required "${g}" claim`,n,g,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new ht('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new ht('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!dC(n.aud,typeof c=="string"?[c]:c))throw new ht('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Cs(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:m}=r,v=pn(m||new Date);if((n.iat!==void 0||u)&&typeof n.iat!="number")throw new ht('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new ht('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>v+d)throw new ht('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new ht('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=v-d)throw new Wo('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){let g=v-n.iat,h=typeof u=="number"?u:Cs(u);if(g-d>h)throw new Wo('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(g<0-d)throw new ht('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var pn,R0,x0,Bg,cC,uC,lC,E0,dC,mn,si=q(()=>{Oe();gt();rt();pn=e=>Math.floor(e.getTime()/1e3),R0=60,x0=R0*60,Bg=x0*24,cC=Bg*7,uC=Bg*365.25,lC=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;E0=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,dC=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;mn=class{#e;constructor(t){if(!Ue(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Fn.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(t){this.#e.iss=t}get sub(){return this.#e.sub}set sub(t){this.#e.sub=t}get aud(){return this.#e.aud}set aud(t){this.#e.aud=t}set jti(t){this.#e.jti=t}set nbf(t){typeof t=="number"?this.#e.nbf=eo("setNotBefore",t):t instanceof Date?this.#e.nbf=eo("setNotBefore",pn(t)):this.#e.nbf=pn(new Date)+Cs(t)}set exp(t){typeof t=="number"?this.#e.exp=eo("setExpirationTime",t):t instanceof Date?this.#e.exp=eo("setExpirationTime",pn(t)):this.#e.exp=pn(new Date)+Cs(t)}set iat(t){t===void 0?this.#e.iat=pn(new Date):t instanceof Date?this.#e.iat=eo("setIssuedAt",pn(t)):typeof t=="string"?this.#e.iat=eo("setIssuedAt",pn(new Date)+Cs(t)):this.#e.iat=eo("setIssuedAt",t)}}});async function I0(e,t,r){let n=await qd(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new tt("JWTs MUST NOT use unencoded payload");let i={payload:ai(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}var P0=q(()=>{Wg();si();Oe()});async function T0(e,t,r){let n=await jd(e,t,r),o=ai(n.protectedHeader,n.plaintext,r),{protectedHeader:i}=n;if(i.iss!==void 0&&i.iss!==o.iss)throw new ht('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(i.sub!==void 0&&i.sub!==o.sub)throw new ht('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(i.aud!==void 0&&JSON.stringify(i.aud)!==JSON.stringify(o.aud))throw new ht('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let a={payload:o,protectedHeader:i};return typeof t=="function"?{...a,key:n.key}:a}var C0=q(()=>{Hg();si();Oe()});var ci,Gg=q(()=>{Ud();ci=class{#e;constructor(t){this.#e=new Cr(t)}setContentEncryptionKey(t){return this.#e.setContentEncryptionKey(t),this}setInitializationVector(t){return this.#e.setInitializationVector(t),this}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}setKeyManagementParameters(t){return this.#e.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this.#e.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var fn,Ld=q(()=>{ft();Pd();rt();Oe();gt();ni();ti();Qn();er();fn=class{#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=t}setProtectedHeader(t){return Be(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Be(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,r){if(!this.#t&&!this.#r)throw new Ae("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!mr(this.#t,this.#r))throw new Ae("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},o=hr(Ae,new Map([["b64",!0]]),r?.crit,this.#t,n),i=!0;if(o.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new Ae('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new Ae('JWS "alg" (Algorithm) Header Parameter missing or invalid');gr(a,t,"sign");let s,c;i?(s=qe(this.#e),c=Qe(s)):(c=this.#e,s="");let u,l;this.#t?(u=qe(JSON.stringify(this.#t)),l=Qe(u)):(u="",l=new Uint8Array);let d=ot(l,Qe("."),c),m=await Kt(t,a),v=await Jz(a,m,d),g={signature:qe(v),payload:s};return this.#r&&(g.header=this.#r),this.#t&&(g.protected=u),g}}});var ui,Xg=q(()=>{Ld();ui=class{#e;constructor(t){this.#e=new fn(t)}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}async sign(t,r){let n=await this.#e.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var Yg,Vd,A0=q(()=>{Ld();Oe();er();Yg=class{#e;protectedHeader;unprotectedHeader;options;key;constructor(t,r,n){this.#e=t,this.key=r,this.options=n}setProtectedHeader(t){return Be(this.protectedHeader,"setProtectedHeader"),this.protectedHeader=t,this}setUnprotectedHeader(t){return Be(this.unprotectedHeader,"setUnprotectedHeader"),this.unprotectedHeader=t,this}addSignature(...t){return this.#e.addSignature(...t)}sign(...t){return this.#e.sign(...t)}done(){return this.#e}},Vd=class{#e;#t=[];constructor(t){this.#e=t}addSignature(t,r){let n=new Yg(this,t,r);return this.#t.push(n),n}async sign(){if(!this.#t.length)throw new Ae("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r{Xg();Oe();si();Kd=class{#e;#t;constructor(t={}){this.#t=new mn(t)}setIssuer(t){return this.#t.iss=t,this}setSubject(t){return this.#t.sub=t,this}setAudience(t){return this.#t.aud=t,this}setJti(t){return this.#t.jti=t,this}setNotBefore(t){return this.#t.nbf=t,this}setExpirationTime(t){return this.#t.exp=t,this}setIssuedAt(t){return this.#t.iat=t,this}setProtectedHeader(t){return this.#e=t,this}async sign(t,r){let n=new ui(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new tt("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}}});var Jd,N0=q(()=>{Gg();si();er();Jd=class{#e;#t;#r;#n;#i;#a;#s;#o;constructor(t={}){this.#o=new mn(t)}setIssuer(t){return this.#o.iss=t,this}setSubject(t){return this.#o.sub=t,this}setAudience(t){return this.#o.aud=t,this}setJti(t){return this.#o.jti=t,this}setNotBefore(t){return this.#o.nbf=t,this}setExpirationTime(t){return this.#o.exp=t,this}setIssuedAt(t){return this.#o.iat=t,this}setProtectedHeader(t){return Be(this.#n,"setProtectedHeader"),this.#n=t,this}setKeyManagementParameters(t){return Be(this.#r,"setKeyManagementParameters"),this.#r=t,this}setContentEncryptionKey(t){return Be(this.#e,"setContentEncryptionKey"),this.#e=t,this}setInitializationVector(t){return Be(this.#t,"setInitializationVector"),this.#t=t,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#a=!0,this}replicateAudienceAsHeader(){return this.#s=!0,this}async encrypt(t,r){let n=new ci(this.#o.data());return this.#n&&(this.#i||this.#a||this.#s)&&(this.#n={...this.#n,iss:this.#i?this.#o.iss:void 0,sub:this.#a?this.#o.sub:void 0,aud:this.#s?this.#o.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(t,r)}}});async function Qg(e,t){let r;if(Yn(e))r=e;else if(ks(e))r=await ei(e);else throw new TypeError(Vt(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":yr(r.alg,'"alg" (Algorithm) Parameter'),yr(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":yr(r.crv,'"crv" (Curve) Parameter'),yr(r.x,'"x" (X Coordinate) Parameter'),yr(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":yr(r.crv,'"crv" (Subtype of Key Pair) Parameter'),yr(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":yr(r.e,'"e" (Exponent) Parameter'),yr(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":yr(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new he('"kty" (Key Type) Parameter missing or unsupported')}let o=Qe(JSON.stringify(n));return qe(await Id(t,o))}async function j0(e,t){t??="sha256";let r=await Qg(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}var yr,U0=q(()=>{er();ft();Oe();gt();ln();rt();Cd();Zn();yr=(e,t)=>{if(typeof e!="string"||!e)throw new $s(`${t} missing or invalid`)}});async function M0(e,t){let r={...e,...t?.header};if(!Ue(r.jwk))throw new Ae('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await dn({...r.jwk,ext:!0},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new Ae('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var D0=q(()=>{Is();rt();Oe()});function pC(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new he('Unsupported "alg" value for a JSON Web Key Set')}}function mC(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(fC)}function fC(e){return Ue(e)}async function q0(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await dn({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Bo("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function As(e){let t=new ey(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var ey,ty=q(()=>{Is();Oe();rt();ey=class{#e;#t=new WeakMap;constructor(t){if(!mC(t))throw new Bo("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=pC(n),a=this.#e.keys.filter(u=>{let l=i===u.kty;if(l&&typeof o=="string"&&(l=o===u.kid),l&&(typeof u.alg=="string"||i==="AKP")&&(l=n===u.alg),l&&typeof u.use=="string"&&(l=u.use==="sig"),l&&Array.isArray(u.key_ops)&&(l=u.key_ops.includes("verify")),l)switch(n){case"ES256":l=u.crv==="P-256";break;case"ES384":l=u.crv==="P-384";break;case"ES512":l=u.crv==="P-521";break;case"Ed25519":case"EdDSA":l=u.crv==="Ed25519";break}return l}),{0:s,length:c}=a;if(c===0)throw new Wn;if(c!==1){let u=new ws,l=this.#t;throw u[Symbol.asyncIterator]=async function*(){for(let d of a)try{yield await q0(l,d,n)}catch{}},u}return q0(this.#t,s,n)}}});function hC(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function gC(e,t,r,n=fetch){let o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(i=>{throw i.name==="TimeoutError"?new zs:i});if(o.status!==200)throw new it("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new it("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function yC(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!Ue(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Ue))}function L0(e,t){let r=new ny(e,t),n=async(o,i)=>r.getKey(o,i);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var ry,oy,Os,ny,V0=q(()=>{Oe();ty();rt();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ry="jose/v6.2.2");oy=Symbol();Os=Symbol();ny=class{#e;#t;#r;#n;#i;#a;#s;#o;#c;#u;constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(t.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#s=new Headers(r?.headers),ry&&!this.#s.has("User-Agent")&&this.#s.set("User-Agent",ry),this.#s.has("accept")||(this.#s.set("accept","application/json"),this.#s.append("accept","application/jwk-set+json")),this.#o=r?.[oy],r?.[Os]!==void 0&&(this.#u=r?.[Os],yC(r?.[Os],this.#n)&&(this.#i=this.#u.uat,this.#c=As(this.#u.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i=="number"?Date.now(){this.#c=As(t),this.#u&&(this.#u.uat=Date.now(),this.#u.jwks=t),this.#i=Date.now(),this.#a=void 0}).catch(t=>{throw this.#a=void 0,t}),await this.#a}}});var Fd,K0=q(()=>{ft();gt();Oe();si();Fd=class{#e;constructor(t={}){this.#e=new mn(t)}encode(){let t=qe(JSON.stringify({alg:"none"})),r=qe(this.#e.data());return`${t}.${r}.`}setIssuer(t){return this.#e.iss=t,this}setSubject(t){return this.#e.sub=t,this}setAudience(t){return this.#e.aud=t,this}setJti(t){return this.#e.jti=t,this}setNotBefore(t){return this.#e.nbf=t,this}setExpirationTime(t){return this.#e.exp=t,this}setIssuedAt(t){return this.#e.iat=t,this}static decode(t,r){if(typeof t!="string")throw new tt("Unsecured JWT must be a string");let{0:n,1:o,2:i,length:a}=t.split(".");if(a!==3||i!=="")throw new tt("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(ct.decode(mt(n))),s.alg!=="none")throw new Error}catch{throw new tt("Invalid Unsecured JWT")}return{payload:ai(s,mt(o),r),header:s}}}});function J0(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(ct.decode(mt(t)));if(!Ue(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var F0=q(()=>{ft();gt();rt()});function H0(e){if(typeof e!="string")throw new tt("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new tt("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new tt("Invalid JWT");if(!t)throw new tt("JWTs must contain a payload");let n;try{n=mt(t)}catch{throw new tt("Failed to base64url decode the payload")}let o;try{o=JSON.parse(ct.decode(n))}catch{throw new tt("Failed to parse the decoded payload as JSON")}if(!Ue(o))throw new tt("Invalid JWT Claims Set");return o}var Z0=q(()=>{ft();gt();rt();Oe()});function iy(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new he("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function W0(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:iy(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:iy(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:iy(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":case"EdDSA":{n=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{n=["sign","verify"],r={name:e};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveBits"];let o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":r={name:"X25519"};break;default:throw new he("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new he('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,t?.extractable??!1,n)}var B0=q(()=>{Oe()});async function G0(e,t){let r,n,o;switch(e){case"HS256":case"HS384":case"HS512":r=parseInt(e.slice(-3),10),n={name:"HMAC",hash:`SHA-${r}`,length:r},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(r>>3));case"A128KW":case"A192KW":case"A256KW":r=parseInt(e.slice(1,4),10),n={name:"AES-KW",length:r},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10),n={name:"AES-GCM",length:r},o=["encrypt","decrypt"];break;default:throw new he('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(n,t?.extractable??!1,o)}var X0=q(()=>{Oe()});var Y0={};nr(Y0,{CompactEncrypt:()=>ci,CompactSign:()=>ui,EmbeddedJWK:()=>M0,EncryptJWT:()=>Jd,FlattenedEncrypt:()=>Cr,FlattenedSign:()=>fn,GeneralEncrypt:()=>Md,GeneralSign:()=>Vd,SignJWT:()=>Kd,UnsecuredJWT:()=>Fd,base64url:()=>$d,calculateJwkThumbprint:()=>Qg,calculateJwkThumbprintUri:()=>j0,compactDecrypt:()=>jd,compactVerify:()=>qd,createLocalJWKSet:()=>As,createRemoteJWKSet:()=>L0,cryptoRuntime:()=>vC,customFetch:()=>oy,decodeJwt:()=>H0,decodeProtectedHeader:()=>J0,errors:()=>Tg,exportJWK:()=>ei,exportPKCS8:()=>p0,exportSPKI:()=>d0,flattenedDecrypt:()=>oi,flattenedVerify:()=>ii,generalDecrypt:()=>b0,generalVerify:()=>z0,generateKeyPair:()=>W0,generateSecret:()=>G0,importJWK:()=>dn,importPKCS8:()=>c0,importSPKI:()=>a0,importX509:()=>s0,jwksCache:()=>Os,jwtDecrypt:()=>T0,jwtVerify:()=>I0});var vC,Q0=q(()=>{Hg();Nd();$0();w0();Wg();Dd();k0();P0();C0();Gg();Ud();Xg();Ld();A0();O0();N0();U0();D0();ty();V0();K0();Cd();Is();F0();Z0();Oe();B0();X0();ft();vC="WebCryptoAPI"});var Uk={};nr(Uk,{AuthorizationServerMismatchError:()=>Wd,BAGGAGE_META_KEY:()=>ou,CLIENT_CAPABILITIES_META_KEY:()=>Gr,CLIENT_INFO_META_KEY:()=>On,Client:()=>oA,ClientCredentialsProvider:()=>CC,CrossAppAccessProvider:()=>NC,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>tu,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>fs,INTERNAL_ERROR:()=>uu,INVALID_PARAMS:()=>cu,INVALID_REQUEST:()=>au,InMemoryResponseCacheStore:()=>Ik,InMemoryTransport:()=>Hw,InsecureTokenEndpointError:()=>fy,InsufficientScopeError:()=>dy,IssuerMismatchError:()=>Xd,JSONRPC_VERSION:()=>Xr,LATEST_PROTOCOL_VERSION:()=>Br,LOG_LEVEL_META_KEY:()=>Nn,MAX_CACHE_TTL_MS:()=>Pk,METHOD_NOT_FOUND:()=>su,MissingRequiredClientCapabilityError:()=>Bh,OAuthClientFlowError:()=>di,OAuthError:()=>xr,OAuthErrorCode:()=>Rr,PARSE_ERROR:()=>iu,PROTOCOL_VERSION_META_KEY:()=>cr,PrivateKeyJwtProvider:()=>AC,Protocol:()=>ag,ProtocolError:()=>Me,ProtocolErrorCode:()=>fe,RELATED_TASK_META_KEY:()=>Ra,ReadBuffer:()=>Kw,RegistrationRejectedError:()=>lk,ResourceNotFoundError:()=>Zh,SERVER_INFO_META_KEY:()=>ur,SSEClientTransport:()=>dA,STDIO_DEFAULT_MAX_BUFFER_SIZE:()=>ug,SUBSCRIPTION_ID_META_KEY:()=>xo,SUPPORTED_PROTOCOL_VERSIONS:()=>Ea,SdkError:()=>ae,SdkErrorCode:()=>se,SdkHttpError:()=>lr,SseError:()=>jk,StaticPrivateKeyJwtProvider:()=>OC,StreamableHTTPClientTransport:()=>hA,TRACEPARENT_META_KEY:()=>ru,TRACESTATE_META_KEY:()=>nu,UnauthorizedError:()=>at,UnsupportedProtocolVersionError:()=>ms,UriTemplate:()=>Fw,UrlElicitationRequiredError:()=>Wh,applyMiddlewares:()=>uA,assertCompleteRequestPrompt:()=>xw,assertCompleteRequestResourceTemplate:()=>Iw,assertSecureTokenEndpoint:()=>Qd,auth:()=>li,buildDiscoveryUrls:()=>wk,checkResourceAllowed:()=>Lh,computeScopeUnion:()=>Bd,createFetchWithInit:()=>od,createMiddleware:()=>lA,createPrivateKeyJwtAuth:()=>xk,deserializeMessage:()=>lg,discoverAndRequestJwtAuthGrant:()=>iA,discoverAuthorizationServerMetadata:()=>ep,discoverOAuthMetadata:()=>PC,discoverOAuthProtectedResourceMetadata:()=>gy,discoverOAuthServerInfo:()=>yy,exchangeAuthorization:()=>TC,exchangeJwtAuthGrant:()=>aA,extractResourceMetadataUrl:()=>RC,extractWWWAuthenticateParams:()=>Ar,fetchToken:()=>Ek,fromJsonSchema:()=>yA,getDisplayName:()=>Vw,getSupportedElicitationModes:()=>Ok,isCallToolResult:()=>Ew,isHttpsUrl:()=>hy,isInitializeRequest:()=>rd,isInitializedNotification:()=>eg,isInputRequiredResult:()=>td,isJSONRPCErrorResponse:()=>Vn,isJSONRPCNotification:()=>Qh,isJSONRPCRequest:()=>sn,isJSONRPCResponse:()=>kw,isJSONRPCResultResponse:()=>qn,isJsonContentType:()=>Lw,isSpecType:()=>og,isStrictScopeSuperset:()=>fk,isTaskAugmentedRequestParams:()=>Rw,mergeCapabilities:()=>sg,parseErrorResponse:()=>py,parseJSONRPCMessage:()=>zw,preloadSchemas:()=>Zw,prepareAuthorizationCodeRequest:()=>vy,refreshAuthorization:()=>kk,registerClient:()=>Rk,requestJwtAuthorizationGrant:()=>Nk,resolveClientMetadata:()=>_k,resourceUrlFromServerUrl:()=>qh,selectClientAuthMethod:()=>gk,selectResourceURL:()=>Sk,serializeMessage:()=>Jw,specTypeSchemas:()=>Dw,startAuthorization:()=>zk,validateAuthorizationResponseIssuer:()=>Ns,validateClientMetadataUrl:()=>EC,withInputRequired:()=>Ow,withLogging:()=>cA,withOAuth:()=>sA});function ek(e,t,r){if(e!==void 0)return e.issuer===void 0?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e):dk(e.issuer,t)?e:void 0}function dk(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function pk(e){if(e==null)return!1;let t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function _C(e,t,r){let{resourceMetadataUrl:n,scope:o}=Ar(t.response);if(await li(e,{serverUrl:t.serverUrl,resourceMetadataUrl:n,scope:o,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new at}function mk(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async r=>_C(e,r,t)}}function Yd(e){return e?.authorization_response_iss_parameter_supported===!0}function Ns({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Xd("authorization_response",t,void 0);return}if(e!==t)throw new Xd("authorization_response",t,e)}}function Bd(...e){let t=new Set;for(let r of e)if(r)for(let n of r.split(/\s+/))n&&t.add(n);return t.size>0?[...t].join(" "):void 0}function fk(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let n of e.split(/\s+/))if(n&&!r.has(n))return!0;return!1}async function hk(e,t,r,n,o){if(typeof e=="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,a=e.get("code");if(a)return{authorizationCode:a,iss:i};let s=(await r.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await yy(n,o)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new at("Authorization callback failed and the issuer could not be verified");Ns({iss:i,expectedIssuer:s.issuer,issParameterSupported:Yd(s)});let c=e.get("error");throw c?new xr(c,e.get("error_description")??c,e.get("error_uri")??void 0):new at("Authorization callback contained neither `code` nor `error`")}function SC(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function gk(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&SC(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function yk(e,t,r,n){let{client_id:o,client_secret:i}=t;switch(e){case"client_secret_basic":bC(o,i,r);return;case"client_secret_post":$C(o,i,n);return;case"none":wC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function bC(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function $C(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function wC(e,t){t.set("client_id",e)}function vk(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Qd(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!vk(t.hostname))throw new fy(t.href);return t}function zC(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||vk(r.hostname))return"native"}return"web"}function _k(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??zC(t.redirect_uris)}}async function py(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Mn.parse(JSON.parse(r));return xr.fromResponse(n)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new xr(Rr.ServerError,o)}}async function li(e,t){try{return await cy(e,t)}catch(r){if(r instanceof xr){if(r.code===Rr.InvalidClient||r.code===Rr.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await cy(e,t);if(r.code===Rr.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await cy(e,t)}throw r}}function kC(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:n,clientMetadata:o}=e,i=t||r?.scopes_supported?.join(" ")||o.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&o.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}async function cy(e,{serverUrl:t,authorizationCode:r,iss:n,scope:o,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:s,forceReauthorization:c}){let u=_k(e),l=await e.discoveryState?.(),d,m,v,g,h=i;if(!h&&l?.resourceMetadataUrl&&(h=new URL(l.resourceMetadataUrl)),l?.authorizationServerUrl){if(m=l.authorizationServerUrl,d=l.resourceMetadata,v=l.authorizationServerMetadata??await ep(m,{fetchFn:a,skipIssuerValidation:s}),!d)try{d=await gy(t,{resourceMetadataUrl:h},a)}catch(A){if(A instanceof TypeError)throw A}(v!==l.authorizationServerMetadata||d!==l.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(m),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:v})}else{let A=await yy(t,{resourceMetadataUrl:h,fetchFn:a,skipIssuerMetadataValidation:s});m=A.authorizationServerUrl,v=A.authorizationServerMetadata,d=A.resourceMetadata,g={authorizationServerUrl:String(m),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:v}}let f=v?.issuer??String(m),y={issuer:f};if(await e.saveAuthorizationServerUrl?.(f),r!==void 0){let A=l?.authorizationServerMetadata?.issuer??l?.authorizationServerUrl;if(A===void 0){if(e.saveDiscoveryState!==void 0)throw new Wd("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",f);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!dk(A,f))throw new Wd(A,f)}g&&await e.saveDiscoveryState?.(g);let S=await Sk(t,e,d);S&&await e.saveResourceUrl?.(String(S));let _=kC({requestedScope:o,resourceMetadata:d,authServerMetadata:v,clientMetadata:e.clientMetadata}),$=await Promise.resolve(e.clientInformation(y)),k=ek($,f,{canPersistStamp:e.saveClientInformation!==void 0});if(k===void 0&&$?.issuer&&e.saveClientInformation===void 0)throw new Wd($.issuer,f);if(k&&k.issuer===void 0&&(k={...k,issuer:f},await e.saveClientInformation?.(k,y)),!k){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let A=v?.client_id_metadata_document_supported===!0,L=e.clientMetadataUrl;if(L&&!hy(L))throw new xr(Rr.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${L}`);if(A&&L)k={client_id:L,issuer:f},await e.saveClientInformation?.(k,y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");k={...await Rk(m,{metadata:v,clientMetadata:u,scope:_,fetchFn:a}),issuer:f},await e.saveClientInformation(k,y)}}let w=!e.redirectUrl;if(r!==void 0||w){r!==void 0&&Ns({iss:n,expectedIssuer:v?.issuer,issParameterSupported:Yd(v)});let A=await Ek(e,m,{metadata:v,resource:S,authorizationCode:r,iss:n,scope:_,fetchFn:a});return await e.saveTokens({...A,issuer:f},y),"AUTHORIZED"}let b=ek(await e.tokens(y),f);if(b&&b.issuer===void 0&&(b={...b,issuer:f},await e.saveTokens(b,y)),b?.refresh_token&&!c)try{let A=await kk(m,{metadata:v,clientInformation:k,refreshToken:b.refresh_token,resource:S,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens({...A,issuer:f},y),"AUTHORIZED"}catch(A){if(A instanceof fy||!(!(A instanceof xr)||A.code===Rr.ServerError))throw A}let E=e.state?await e.state():void 0,{authorizationUrl:j,codeVerifier:V}=await zk(m,{metadata:v,clientInformation:k,state:E,redirectUrl:e.redirectUrl,scope:_,resource:S});return await e.saveCodeVerifier(V),await e.redirectToAuthorization(j),"REDIRECT"}function EC(e){if(e&&!hy(e))throw new xr(Rr.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${e}`)}function hy(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Sk(e,t,r){let n=qh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Lh({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Ar(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!n)return{};let o=Hd(e,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let a=Hd(e,"scope")||void 0,s=Hd(e,"error")||void 0,c=Hd(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:s,errorDescription:c}}function Hd(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),o=r.match(n);if(o){let i=o[1]||o[2];if(i)return i}return null}function RC(e){let t=e.headers.get("WWW-Authenticate");if(!t)return;let[r,n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!n)return;let o=/resource_metadata="([^"]*)"/.exec(t);if(!(!o||!o[1]))try{return new URL(o[1])}catch{return}}async function gy(e,t,r=fetch){let n=await $k(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return rs.parse(await n.json())}async function bk(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!hz)throw n;if(t)try{return await r(e,{})}catch(o){if(!(o instanceof TypeError))throw o;return}return}}function xC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function tk(e,t,r=fetch){return await bk(e,{"MCP-Protocol-Version":t},r)}function IC(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}async function $k(e,t,r,n){let o=new URL(e),i=n?.protocolVersion??Br,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let c=xC(t,o.pathname);a=new URL(c,n?.metadataServerUrl??o),a.search=o.search}let s=await tk(a,i,r);return!n?.metadataUrl&&IC(s,o.pathname)&&(s=await tk(new URL(`/.well-known/${t}`,o),i,r)),s}async function PC(e,{authorizationServerUrl:t,protocolVersion:r}={},n=fetch){typeof e=="string"&&(e=new URL(e)),t||(t=e),typeof t=="string"&&(t=new URL(t)),r??=Br;let o=await $k(t,"oauth-authorization-server",n,{protocolVersion:r,metadataServerUrl:t});if(!o||o.status===404){await o?.text?.().catch(()=>{});return}if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth metadata`);return Un.parse(await o.json())}function wk(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"},{url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function ep(e,{fetchFn:t=fetch,protocolVersion:r=Br,skipIssuerValidation:n=!1}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=wk(e);for(let{url:a,type:s}of i){let c=await bk(a,o,t);if(!c)continue;if(!c.ok){if(await c.text?.().catch(()=>{}),c.status>=400&&c.status<500||c.status===502)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let u=s==="oauth"?Un.parse(await c.json()):ns.parse(await c.json());if(!n){let l=typeof e=="string"?e:e.href;if(!(u.issuer===l||l.endsWith("/")&&u.issuer===l.slice(0,-1)))throw new Xd("metadata",l,u.issuer)}return u}}async function yy(e,t){let r,n;try{r=await gy(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));let o=await ep(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function zk(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:a}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ay))throw new Error(`Incompatible auth server: does not support response type ${ay}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(sy))throw new Error(`Incompatible auth server: does not support code challenge method ${sy}`)}else s=new URL("/authorize",e);let c=await hg(),u=c.code_verifier,l=c.code_challenge;return s.searchParams.set("response_type",ay),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",l),s.searchParams.set("code_challenge_method",sy),s.searchParams.set("redirect_uri",String(n)),i&&s.searchParams.set("state",i),o&&s.searchParams.set("scope",o),o?.split(" ").includes("offline_access")&&s.searchParams.append("prompt","consent"),a&&s.searchParams.set("resource",a.href),{authorizationUrl:s,codeVerifier:u}}function vy(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function _y(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:a}){let s=Qd(t?.token_endpoint??new URL("/token",e)),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",i.href),o?await o(c,r,s,t):n&&yk(gk(n,t?.token_endpoint_auth_methods_supported??[]),n,c,r);let u=await(a??fetch)(s,{method:"POST",headers:c,body:r});if(!u.ok)throw await py(u);let l=await u.json();try{return Lo.parse(l)}catch(d){throw typeof l=="object"&&l!==null&&"error"in l?await py(JSON.stringify(l)):d}}async function TC(e,{metadata:t,clientInformation:r,authorizationCode:n,iss:o,codeVerifier:i,redirectUri:a,resource:s,addClientAuthentication:c,fetchFn:u}){return Ns({iss:o,expectedIssuer:t?.issuer,issParameterSupported:Yd(t)}),_y(e,{metadata:t,tokenRequestParams:vy(n,i,a),clientInformation:r,addClientAuthentication:c,resource:s,fetchFn:u})}async function kk(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:a}){return{refresh_token:n,...await _y(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:a})}}async function Ek(e,t,{metadata:r,resource:n,authorizationCode:o,iss:i,scope:a,fetchFn:s}={}){o!==void 0&&Ns({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Yd(r)});let c=a??e.clientMetadata.scope,u;if(e.prepareTokenRequest&&(u=await e.prepareTokenRequest(c)),!u){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");u=vy(o,await e.codeVerifier(),e.redirectUrl)}let l=await e.clientInformation({issuer:r?.issuer??String(t)});return _y(t,{metadata:r,tokenRequestParams:u,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Rk(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...r,...n===void 0?{}:{scope:n}},s=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!s.ok)throw new lk({status:s.status,body:await s.text(),submittedMetadata:a});return is.parse(await s.json())}function xk(e){return async(t,r,n,o)=>{if(globalThis.crypto===void 0)throw new TypeError("crypto is not available, please ensure you have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)");let i=await Promise.resolve().then(()=>(Q0(),Y0)),a=String(e.audience??o?.issuer??n),s=e.lifetimeSeconds??300,c=Math.floor(Date.now()/1e3),u=`${Date.now()}-${Math.random().toString(36).slice(2)}`,l={iss:e.issuer,sub:e.subject,aud:a,exp:c+s,iat:c,jti:u},d=e.claims?{...l,...e.claims}:l,m=e.alg,v;if(typeof e.privateKey=="string")if(m.startsWith("RS")||m.startsWith("ES")||m.startsWith("PS"))v=await i.importPKCS8(e.privateKey,m);else if(m.startsWith("HS"))v=new TextEncoder().encode(e.privateKey);else throw new Error(`Unsupported algorithm ${m}`);else e.privateKey instanceof Uint8Array?v=m.startsWith("HS")?e.privateKey:await i.importPKCS8(new TextDecoder().decode(e.privateKey),m):v=await i.importJWK(e.privateKey,m);let g=await new i.SignJWT(d).setProtectedHeader({alg:m,typ:"JWT"}).setIssuer(e.issuer).setSubject(e.subject).setAudience(a).setIssuedAt(c).setExpirationTime(c+s).setJti(u).sign(v);r.set("client_assertion",g),r.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")}}function uy(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function ly(e,t){return t===void 0?e:`${e}\0${t}`}function UC(e){let t;try{t=JSON.stringify(e)}catch(r){throw new TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}function qC(e,t){switch(e.kind){case"result":return LC(e.result,t);case"rpc-error":return Tk(e,t);case"http-error":return VC(e,t);case"network-error":return rk(e.error,t);case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:rk(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new ae(se.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function LC(e,t){let r=Er(ed).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let n=r.value.supportedVersions,o=t.clientModernVersions.find(i=>n.includes(i));return o!==void 0?{kind:"modern",version:o,discover:r.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new ms({supported:[...n],requested:t.requestedVersion})}}function Tk(e,t){let{code:r,message:n,data:o}=e;if(r===MC){let i=FC(o);if(i===void 0)return{kind:"legacy"};let a=new ms({supported:i,requested:HC(o)??t.requestedVersion},n),s=ps(i),c=t.clientModernVersions.find(u=>s.includes(u));return c!==void 0?{kind:"corrective",version:c,error:a}:s.length>0?{kind:"error",error:a}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:a}}return DC.has(r)?{kind:"legacy"}:{kind:"legacy"}}function VC(e,t){let r=ZC(e.body);return r!==void 0?Tk(r,t):{kind:"legacy"}}function rk(e,t){return t.environment==="browser"&&KC(e)?{kind:"legacy"}:{kind:"error",error:new ae(se.EraNegotiationFailed,`Version negotiation probe failed: ${JC(e)}`,{cause:e})}}function KC(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function JC(e){return e instanceof Error?e.message:String(e)}function FC(e){if(typeof e!="object"||e===null)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(r=>typeof r=="string")))return t}function HC(e){if(typeof e!="object"||e===null)return;let t=e.requested;return typeof t=="string"?t:void 0}function ZC(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let r=t.error;if(typeof r!="object"||r===null)return;let{code:n,message:o,data:i}=r;if(typeof n=="number")return{code:n,message:typeof o=="string"?o:"",data:i}}function BC(e,t){let r=e?.mode??WC;if(r==="legacy")return{kind:"legacy"};let n=e?.probe??{};if(typeof r=="object"){if(!Ir(r.pin))throw new TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:n}}let o=t?ps(t):[];return{kind:"auto",modernVersions:o.length>0?o:[...Vh],fallbackAvailable:t?Kh(t).length>0:!0,probe:n}}function nk(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function ok(e){return"stderr"in e&&"pid"in e?"stdio":"http"}function ik(e){let t=my.get(e);my.delete(e),t?.()}function XC(e,t,r,n){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Er(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:n})}}}function YC(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(r instanceof lr){let n=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof n=="string"?n:void 0}}return r instanceof at||r instanceof Error&&r.name==="UnauthorizedError"?{kind:"auth-required",error:r}:{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Ak(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,n=Math.max(0,e.probe.maxRetries??0),o=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,a=await GC.open(t.transport),s=async()=>{let u=o[0],l=!1,d=n;for(;;){let m=await a.exchange(h=>XC(h,u,t.clientInfo,t.capabilities),r);if(m.kind==="timeout"&&d>0){d--;continue}let v=YC(m,r),g=qC(v,{clientModernVersions:o,requestedVersion:u,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(g.kind){case"modern":return{era:"modern",version:g.version,discover:g.discover};case"corrective":if(l)throw g.error;l=!0,u=g.version;continue;case"legacy":{let h=v.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new ae(se.EraNegotiationFailed,h===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${h} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new ae(se.EraNegotiationFailed,h===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${h} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(h!==void 0&&t.disposableProbe!==!0)throw new ae(se.EraNegotiationFailed,`Version negotiation failed: ${h} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw g.error}}},c;try{c=await s()}catch(u){throw a.detach(),u}return a.release(),c}function QC(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r=="object"&&r!==null&&typeof r.command=="string"?r:void 0}async function eA(e,t,r,n){let o=t.constructor,i=new o({...r,stderr:"ignore"}),a=t.close,s=!1,c,u=new Promise((d,m)=>{c=()=>m(ak())});t.close=async function(){return s=!0,c?.(),a.call(t)};let l;try{let d=Ak(e,{...n,transport:i,transportKind:"stdio",disposableProbe:!0});d.catch(()=>{}),l=await Promise.race([d,u])}finally{await tA(i),t.close=a}if(s)throw ak();return l}function ak(){return new ae(se.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function tA(e){try{let t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function sk(e){let t=e._meta?.[ur];return og.Implementation(t)?t:void 0}function Gd(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Gd(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Gd(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Gd(r,t)}}function Ok(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function rA(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&jn.safeParse(e.discover).success))return e;throw new ae(se.EraNegotiationFailed,"connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }")}async function Nk(e){let{tokenEndpoint:t,audience:r,resource:n,idToken:o,clientId:i,clientSecret:a,scope:s,fetchFn:c=fetch}=e,u=Qd(t),l=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:id-jag",audience:String(r),resource:String(n),subject_token:o,subject_token_type:"urn:ietf:params:oauth:token-type:id_token",client_id:i});a&&l.set("client_secret",a),s&&l.set("scope",s);let d=await c(u,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!d.ok){let v=await d.json().catch(()=>({})),g=Mn.safeParse(v);if(g.success){let{error:h,error_description:f}=g.data;throw new Error(`Token exchange failed: ${h}${f?` - ${f}`:""}`)}throw new Error(`Token exchange failed with status ${d.status}: ${JSON.stringify(v)}`)}let m=os.safeParse(await d.json());if(!m.success)throw new Error(`Invalid token exchange response: ${m.error.message}`);return{jwtAuthGrant:m.data.access_token,expiresIn:m.data.expires_in,scope:m.data.scope}}async function iA(e){let{idpUrl:t,fetchFn:r=fetch,...n}=e,o=await ep(String(t),{fetchFn:r});if(!o?.token_endpoint)throw new Error(`Failed to discover token endpoint for IdP: ${t}`);return Nk({...n,tokenEndpoint:o.token_endpoint,fetchFn:r})}async function aA(e){let{tokenEndpoint:t,jwtAuthGrant:r,clientId:n,clientSecret:o,authMethod:i="client_secret_basic",fetchFn:a=fetch}=e,s=Qd(t),c=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:r}),u=new Headers({"Content-Type":"application/x-www-form-urlencoded"});yk(i,{client_id:n,client_secret:o},u,c);let l=await a(s,{method:"POST",headers:u,body:c.toString()});if(!l.ok){let v=await l.json().catch(()=>({})),g=Mn.safeParse(v);if(g.success){let{error:h,error_description:f}=g.data;throw new Error(`JWT grant exchange failed: ${h}${f?` - ${f}`:""}`)}throw new Error(`JWT grant exchange failed with status ${l.status}: ${JSON.stringify(v)}`)}let d=await l.json(),m=Lo.safeParse(d);if(!m.success)throw new Error(`Invalid token response: ${m.error.message}`);return m.data}function uk(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let n=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",i)};function o(){n(),r.abort(e.reason)}function i(){n(),r.abort(t.reason)}return e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}function yA(e,t){return Ww(e,t??(gA??=new pd))}var di,Xd,lk,fy,Wd,dy,at,ay,sy,CC,AC,OC,NC,Zd,Ik,Pk,jC,MC,DC,WC,GC,my,ck,nA,oA,sA,cA,uA,lA,jk,dA,pA,mA,fA,hA,gA,Mk=q(()=>{Bw();gz();yz();bz();$z();di=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e){super(e),this.name=new.target.name,Ln(this,new.target)}},Xd=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},lk=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},fy=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},Wd=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},dy=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};at=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Ln(this,new.target)}};ay="code",sy="S256";CC=class{_tokens;_clientInfo;_clientMetadata;constructor(e){this._clientInfo={client_id:e.clientId,client_secret:e.clientSecret,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"client-credentials-client",redirect_uris:[],grant_types:["client_credentials"],token_endpoint_auth_method:"client_secret_basic",scope:e.scope}}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for client_credentials flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for client_credentials flow")}prepareTokenRequest(e){let t=new URLSearchParams({grant_type:"client_credentials"});return e&&t.set("scope",e),t}},AC=class{_tokens;_clientInfo;_clientMetadata;addClientAuthentication;constructor(e){this._clientInfo={client_id:e.clientId,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"private-key-jwt-client",redirect_uris:[],grant_types:["client_credentials"],token_endpoint_auth_method:"private_key_jwt",scope:e.scope},this.addClientAuthentication=xk({issuer:e.clientId,subject:e.clientId,privateKey:e.privateKey,alg:e.algorithm,lifetimeSeconds:e.jwtLifetimeSeconds,claims:e.claims})}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for client_credentials flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for client_credentials flow")}prepareTokenRequest(e){let t=new URLSearchParams({grant_type:"client_credentials"});return e&&t.set("scope",e),t}},OC=class{_tokens;_clientInfo;_clientMetadata;addClientAuthentication;constructor(e){this._clientInfo={client_id:e.clientId,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"static-private-key-jwt-client",redirect_uris:[],grant_types:["client_credentials"],token_endpoint_auth_method:"private_key_jwt",scope:e.scope};let t=e.jwtBearerAssertion;this.addClientAuthentication=async(r,n)=>{n.set("client_assertion",t),n.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")}}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for client_credentials flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for client_credentials flow")}prepareTokenRequest(e){let t=new URLSearchParams({grant_type:"client_credentials"});return e&&t.set("scope",e),t}},NC=class{_tokens;_clientInfo;_clientMetadata;_assertionCallback;_fetchFn;_authorizationServerUrl;_resourceUrl;_scope;constructor(e){this._clientInfo={client_id:e.clientId,client_secret:e.clientSecret,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"cross-app-access-client",redirect_uris:[],grant_types:["urn:ietf:params:oauth:grant-type:jwt-bearer"],token_endpoint_auth_method:"client_secret_basic"},this._assertionCallback=e.assertion,this._fetchFn=e.fetchFn??fetch}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for jwt-bearer flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for jwt-bearer flow")}saveAuthorizationServerUrl(e){this._authorizationServerUrl=e}authorizationServerUrl(){return this._authorizationServerUrl}saveResourceUrl(e){this._resourceUrl=e}resourceUrl(){return this._resourceUrl}async prepareTokenRequest(e){let t=this._authorizationServerUrl,r=this._resourceUrl;if(!t)throw new Error("Authorization server URL not available. Ensure auth() has been called first.");if(!r)throw new Error("Resource URL not available \u2014 server may not implement RFC 9728 Protected Resource Metadata (required for Cross-App Access), or auth() has not been called");this._scope=e;let n=await this._assertionCallback({authorizationServerUrl:t,resourceUrl:r,scope:this._scope,fetchFn:this._fetchFn}),o=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:n});return e&&o.set("scope",e),o}},Zd=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),Ik=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(uy(e))}set(e,t){let r=uy(e),n=Zd.has(e.method),o=!this._entries.has(r);if(!n&&o&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let a of this._entries.keys())if(!Zd.has(a.slice(0,a.indexOf("\0")))){this._entries.delete(a),this._cappedSize--;break}}let i=++this._stamp;return this._entries.set(r,{...t,stamp:i}),o&&!n&&this._cappedSize++,i}delete(e){this._entries.delete(uy(e))&&!Zd.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,r=Zd.has(e);for(let n of this._entries.keys())n.startsWith(t)&&(this._entries.delete(n),r||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};Pk=864e5,jC=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},n="",o=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=n,this._now=o}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},n=this._partitionFor("private"),o=await this._store.get({...r,partition:n});if(o!==void 0)return o;let i=this._partitionFor("public");if(i===n)return;let a=await this._store.get({...r,partition:i});return a?.scope==="public"?a:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),n=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(o){this._reportError(o)}if(n!==r)try{await this._store.delete({method:e,params:t,partition:n})}catch(o){this._reportError(o)}}async evictKey(e,t){let r=ly(e,t),n=this._evictionGeneration.get(r);n!==void 0&&this._evictionGeneration.set(r,n+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let r=ly(e,t),n=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,n),n}async write(e,t,r,n){if((this._evictionGeneration.get(ly(e,n?.params))??0)!==r)return;let o=n?.params??"",i=this._partitionFor("private"),a=this._partitionFor("public"),s=(n?.scope??"private")==="public"?a:i;try{await this._store.set({method:e,params:o,partition:s},{value:UC(t),expiresAt:n?.expiresAt,scope:n?.scope})}catch(c){this._reportError(c)}if(a!==i)try{await this._store.delete({method:e,params:o,partition:s===i?a:i})}catch(c){this._reportError(c)}}async read(e,t){let r=await this._probe(e,t);if(!(r?.expiresAt===void 0||!(r.expiresAt>this.now())))try{let n=JSON.parse(r.value);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("cached document is not an object");return{value:n}}catch(n){this._reportError(n),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),n=new Map;if(r!==void 0)for(let o of r.tools)n.set(o.name,o);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let n=this._decodeListTools(r)??{tools:[]},o=new Map;for(let i of n.tools){let a=t(i);a!==void 0&&o.set(i.name,a)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:o}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(r=>r!==null&&typeof r=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};MC=-32022,DC=new Set([-32001,-32020,-32021]);WC="legacy";GC=class Ck{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new Ck(t);t.onmessage=n=>{let o=r._pending;if(o!==void 0&&(qn(n)||Vn(n))&&n.id===o.id){r._pending=void 0,qn(n)?o.resolve({kind:"response",result:n.result}):o.resolve({kind:"response",error:n.error});return}},t.onerror=n=>{r._savedOnError?.(n)},t.onclose=()=>{let n=r._pending;n!==void 0&&(r._pending=void 0,n.resolve({kind:"closed"})),r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(n){throw r.detach(),n}return r}async exchange(t,r){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(o=>{let i=!1,a=c=>{i||(i=!0,clearTimeout(s),this._pending?.id===n&&(this._pending=void 0),o(c))},s=setTimeout(()=>a({kind:"timeout"}),r);this._pending={id:n,resolve:a},this._transport.send(t(n)).catch(c=>a({kind:"send-error",error:c}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,n=!1,o=()=>{if(!n){n=!0;return}t()};r.onclose=o,my.set(r,()=>{r.onclose===o&&(r.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,n=!0;t.start=async function(){if(n){n=!1,t.start=r;return}return r.call(t)}}},my=new WeakMap;ck={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},nA=64,oA=class extends ag{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new ae(se.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new pd,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=Nw(t?.inputRequired),this._cache=new jC(t?.responseCacheStore??new Ik,t?.responseCacheStore!==void 0,r=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??nA,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Ir(this._negotiatedProtocolVersion)&&sn(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?qw({getRequestHandler:r=>this._getRequestHandler(r),buildContext:r=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new ae(se.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=sg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(r,n)=>{let o=Er(this._negotiatedProtocolVersion),i=o.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era"&&(i=o.validateInputRequest("elicitation/create",r)),!i.ok)throw new Me(i.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??"form";let{supportsFormMode:s,supportsUrlMode:c}=Ok(this._capabilities.elicitation);if(a.mode==="form"&&!s)throw new Me(fe.InvalidParams,"Client does not support form-mode elicitation requests");if(a.mode==="url"&&!c)throw new Me(fe.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,n),l=o.validateResult("elicitation/create",u);if(!l.ok&&l.reason==="not-in-era"&&(l=o.validateInputResponse("elicitation/create",u)),!l.ok)throw new Me(l.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,l.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${l.message}`);let d=l.value,m=a.mode==="form"?a.requestedSchema:void 0;if(a.mode==="form"&&d.action==="accept"&&d.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{Gd(m,d.content)}catch{}return d}:e==="sampling/createMessage"?async(r,n)=>{let o=Er(this._negotiatedProtocolVersion),i=o.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era"&&(i=o.validateInputRequest("sampling/createMessage",r)),!i.ok)throw new Me(i.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:a}=i.value,s=await t(r,n),c=!!(a.tools||a.toolChoice),u=o.samplingResultVariant(c,s);if(!u.ok&&u.reason==="not-in-era"&&(u=o.validateInputResponse("sampling/createMessage",s)),!u.ok)throw new Me(u.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new ae(se.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,rA(t.prior),t);let r=BC(this._versionNegotiation,this._supportedProtocolVersionsOption);return r.kind!=="legacy"?this._connectNegotiated(e,r,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;r!==void 0&&e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=Kh(this._supportedProtocolVersions);try{let n=r[0];if(n===void 0)throw new ae(se.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let o=await this.request({method:"initialize",params:{protocolVersion:n,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!r.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=o.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(n){throw this.close(),n}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let o=this._negotiatedProtocolVersion;o!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(o);return}this._resetConnectionState();let n;try{let o=ok(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:nk(),defaultTimeoutMs:r?.timeout??fs},a=o==="stdio"?QC(e):void 0;n=a===void 0?await Ak(t,{...i,transport:e,transportKind:o}):await eA(t,e,a,i)}catch(o){throw await e.close().catch(()=>{}),ik(e),o}if(ik(e),await super.connect(e),n.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=n.discover.capabilities,this._serverVersion=sk(n.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.discover.instructions,this._discoverResult=n.discover,this._negotiatedProtocolVersion=n.version,e.setProtocolVersion&&e.setProtocolVersion(n.version),this._listChangedConfig){let o=this._listChangedConfig,i=this._serverCapabilities,a={...o.tools&&i?.tools?.listChanged&&{tools:o.tools},...o.prompts&&i?.prompts?.listChanged&&{prompts:o.prompts},...o.resources&&i?.resources?.listChanged&&{resources:o.resources}},s=!0;try{this._setupListChangedHandlers(a)}catch(u){s=!1,this.onerror?.(u instanceof Error?u:new Error(String(u)))}let c=s?{...a.tools&&{toolsListChanged:!0},...a.prompts&&{promptsListChanged:!0},...a.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(c).length>0){let u=new AbortController,l=()=>u.abort(r?.signal?.reason);r?.signal?.aborted&&l(),r?.signal?.addEventListener("abort",l);try{this._autoOpenedSubscription=await this.listen(c,{timeout:r?.timeout,signal:u.signal})}catch(d){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),d;this.onerror?.(d instanceof Error?d:new Error(String(d)))}finally{r?.signal?.removeEventListener("abort",l)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let n=t.discover;this._resetConnectionState();let o=this._supportedProtocolVersionsOption,i=(o&&ps(o).length>0?ps(o):Vh).find(a=>n.supportedVersions.includes(a));if(i===void 0)throw new ae(se.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=n,this._serverCapabilities=n.capabilities,this._serverVersion=sk(n),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(a){this.onerror?.(a instanceof Error?a:new Error(String(a)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return Ir(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new ae(se.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new ae(se.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new ae(se.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new ae(se.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new ae(se.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new ae(se.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new ae(se.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new ae(se.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new ae(se.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new ae(se.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},jn,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);return r!==void 0?r:this._listAllPages("prompts/list",e,t,(n,o)=>n.prompts.push(...o.prompts))}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/list",e,t,(n,o)=>n.resources.push(...o.resources))}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/templates/list",e,t,(n,o)=>n.resourceTemplates.push(...o.resourceTemplates))}async _listAllPages(e,t,r,n,o){let i=r?.cacheMode==="bypass",a=this._cache.captureGeneration(e),s=await this.request({method:e,...t&&{params:{...t}}},r),c=s.nextCursor,u=new Set,l=1;for(;c!==void 0&&!u.has(c);){if(this._listMaxPages!==0&&l>=this._listMaxPages)throw new ae(se.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});u.add(c);let d=await this.request({method:e,params:{...t,cursor:c}},r);n(s,d),c=d.nextCursor,l++}return delete s.nextCursor,o?.(s),i||await this._cache.write(e,s,a,this._freshness(s)),s}_freshness(e,t){let r=e,n=typeof r.ttlMs=="number"?r.ttlMs:this._defaultCacheTtlMs,o=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,n),Pk),scope:o,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let n=await this._cache.read(e,t).catch(o=>{this._reportStoreError(o)});if(n!==void 0){if(r?.signal?.aborted){let o=r.signal.reason;throw o instanceof ae?o:new ae(se.RequestTimeout,String(o))}return n.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:tg(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let n=this._cache.captureGeneration("resources/read",e.uri),o=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let i=this._freshness(o,e.uri);i.expiresAt>this._cache.now()?await this._cache.write("resources/read",o,n,i):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return o}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new ae(se.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Ir(r))throw new ae(se.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let S=t.signal.reason;throw S instanceof ae?S:new ae(se.RequestTimeout,String(S))}let n=new AbortController,o=`listen:${this._nextListenId++}`,i="opening",a,s,c,u,l=new Promise((S,_)=>{c=S,u=_}),d,m=new Promise(S=>{d=S}),v=S=>{if(i==="closed")return;let _=i==="opening";if(a!==void 0&&(clearTimeout(a),a=void 0),"ack"in S){i="open",c(S.ack);return}i="closed",s!==void 0&&t?.signal?.removeEventListener("abort",s),this._listenState.delete(o),n.abort(),d(S.cause),_&&u(S.error??new ae(se.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},g=async()=>{n.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:o}}).catch(()=>{})},h=async()=>{i!=="closed"&&(v({cause:"local"}),await g())};this._listenState.set(o,{settle:v});let f=t?.timeout??fs;if(a=setTimeout(()=>{v({cause:"remote",error:new ae(se.RequestTimeout,"subscriptions/listen ack timed out",{timeout:f})}),g().catch(()=>{})},f),t?.signal){let S=t.signal;s=()=>{if(i==="closed")return;let _=S.reason;v({cause:"local",error:_ instanceof Error?_:new Error(String(_??"Aborted"))}),g().catch(()=>{})},S.addEventListener("abort",s,{once:!0})}let y={jsonrpc:"2.0",id:o,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}};try{await this.transport.send(y,{requestSignal:n.signal,onRequestStreamEnd:()=>v({cause:"remote",error:new Error("subscriptions/listen: stream ended")})})}catch(S){v({cause:"remote",error:S instanceof Error?S:new Error(String(S))})}return{honoredFilter:await l,close:h,closed:m}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(ck,e.method)?ck[e.method]:void 0;if(e.method==="notifications/resources/updated"){let n=e.params?.uri;typeof n=="string"&&this._cache.evictKey("resources/read",n)}else if(r!==void 0)for(let n of r)this._cache.evict(n);if(e.method==="notifications/subscriptions/acknowledged"){let n=e.params?._meta?.[xo],o=typeof n=="string"?this._listenState.get(n):void 0;if(o!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);o.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let n=e.params?.requestId,o=typeof n=="string"?this._listenState.get(n):void 0;if(o!==void 0){o.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t=="string"?this._listenState.get(t):void 0;if(r!==void 0){Vn(e)?r.settle({cause:"remote",error:Me.fromError(e.error.code,e.error.message,e.error.data)}):r.settle({cause:"graceful",error:new ae(se.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new ae(se.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&nk()!=="browser",n=async()=>{if(!r)return t;let c;try{c=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(l){this._reportStoreError(l)}if(!c?.valid||c.declarations.length===0)return t;let u=Cw(c.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},o=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,c=>this._compileOutputValidator(c)).catch(c=>{this._reportStoreError(c)}):this._compileOutputValidator(t.toolDefinition),i=()=>{if(o===void 0||o.ok)return;let c=o.compileError,u=(c instanceof Error?c.message:String(c)).slice(0,200);throw new Me(fe.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};i();let a;try{a=await this.request({method:"tools/call",params:e},await n())}catch(c){let u=c instanceof Me&&c.code===Vo;if(!r||!u||t?.toolDefinition!==void 0)throw c;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,l).catch(d=>this._reportStoreError(d)),o=await this._cache.outputValidator(e.name,d=>this._compileOutputValidator(d)).catch(d=>{this._reportStoreError(d)}),i(),a=await this.request({method:"tools/call",params:e},await n())}let s=o!==void 0&&o.ok?o.validator:void 0;if(s){if(a.structuredContent===void 0&&!a.isError)throw new Me(fe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent!==void 0&&!a.isError)try{let c=s(a.structuredContent);if(!c.valid)throw new Me(fe.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)}catch(c){throw c instanceof Me?c:new Me(fe.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)}}return a}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let r=await this._serveFromCache("tools/list",void 0,t);return r!==void 0?r:this._listAllPages("tools/list",e,t,(n,o)=>n.tools.push(...o.tools),n=>this._excludeInvalidXMcpHeaderTools(n))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||ok(this.transport)==="stdio")return;let t=e.tools.filter(r=>{let n=tg(r.inputSchema);return n.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${n.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,r,n){let o=nd(Za,r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=o.data,{onChanged:s}=r,c=async()=>{if(!i){s(null,null);return}try{s(null,await n())}catch(l){s(l instanceof Error?l:new Error(String(l)),null)}},u=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let d=setTimeout(c,a);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};sA=(e,t)=>r=>async(n,o)=>{let i=async()=>{let s=new Headers(o?.headers),c=await e.tokens();return c&&s.set("Authorization",`Bearer ${c.access_token}`),await r(n,{...o,headers:s})},a=await i();if(a.status===401)try{let{resourceMetadataUrl:s,scope:c}=Ar(a),u=await li(e,{serverUrl:t||(typeof n=="string"?new URL(n).origin:n.origin),resourceMetadataUrl:s,scope:c,fetchFn:r});if(u==="REDIRECT")throw new at("Authentication requires user authorization - redirect initiated");if(u!=="AUTHORIZED")throw new at(`Authentication failed with result: ${u}`);a=await i()}catch(s){throw s instanceof at?s:new at(`Failed to re-authenticate: ${s instanceof Error?s.message:String(s)}`)}if(a.status===401)throw new at(`Authentication failed for ${typeof n=="string"?n:n.toString()}`);return a},cA=(e={})=>{let{logger:t,includeRequestHeaders:r=!1,includeResponseHeaders:n=!1,statusLevel:o=0}=e,a=t||(s=>{let{method:c,url:u,status:l,statusText:d,duration:m,requestHeaders:v,responseHeaders:g,error:h}=s,f=h?`HTTP ${c} ${u} failed: ${h.message} (${m}ms)`:`HTTP ${c} ${u} ${l} ${d} (${m}ms)`;if(r&&v){let y=[...v.entries()].map(([S,_])=>`${S}: ${_}`).join(", ");f+=` + Request Headers: {${y}}`}if(n&&g){let y=[...g.entries()].map(([S,_])=>`${S}: ${_}`).join(", ");f+=` + Response Headers: {${y}}`}h||l>=400?console.error(f):console.log(f)});return s=>async(c,u)=>{let l=performance.now(),d=u?.method||"GET",m=typeof c=="string"?c:c.toString(),v=r?new Headers(u?.headers):void 0;try{let g=await s(c,u),h=performance.now()-l;return g.status>=o&&a({method:d,url:m,status:g.status,statusText:g.statusText,duration:h,requestHeaders:v,responseHeaders:n?g.headers:void 0}),g}catch(g){throw a({method:d,url:m,status:0,statusText:"Network Error",duration:performance.now()-l,requestHeaders:v,error:g}),g}}},uA=(...e)=>t=>{let r=t;for(let n of e)r=n(r);return r},lA=e=>t=>(r,n)=>e(t,r,n),jk=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,Ln(this,new.target)}},dA=class{_eventSource;_endpoint;_abortController;_url;_resourceMetadataUrl;_scope;_eventSourceInit;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_protocolVersion;onclose;onerror;onmessage;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,pk(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=mk(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=od(t?.fetch,t?.requestInit)}_last401Response;async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ds(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new Jn(this._url.href,{...this._eventSourceInit,fetch:async(n,o)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(n,{...o,headers:i});if(a.status===401&&(this._last401Response=a,a.headers.has("www-authenticate"))){let{resourceMetadataUrl:s,scope:c}=Ar(a);this._resourceMetadataUrl=s,this._scope=c}return a}}),this._abortController=new AbortController,this._eventSource.onerror=n=>{if(n.code===401&&this._authProvider){if(this._authProvider.onUnauthorized&&this._last401Response){let a=this._last401Response;this._last401Response=void 0,this._eventSource?.close(),this._authProvider.onUnauthorized({response:a,serverUrl:this._url,fetchFn:this._fetchWithInit}).then(()=>this._startOrAuth().then(t,r),s=>{this.onerror?.(s),r(s)});return}let i=new at;r(i),this.onerror?.(i);return}let o=new jk(n.code,n.message,n);r(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{let o=n;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){r(i),this.onerror?.(i),this.close();return}t()}),this._eventSource.onmessage=n=>{let o=n,i;try{i=Bt.parse(JSON.parse(o.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e,t){if(!this._oauthProvider)throw new at("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:n}=await hk(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await li(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:n,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new at("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){return this._send(e,!1)}async _send(e,t){if(!this._endpoint)throw new ae(se.NotConnected,"Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){if(o.status===401&&this._authProvider){if(o.headers.has("www-authenticate")){let{resourceMetadataUrl:a,scope:s}=Ar(o);this._resourceMetadataUrl=a,this._scope=s}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:o,serverUrl:this._url,fetchFn:this._fetchWithInit}),await o.text?.().catch(()=>{}),this._send(e,!0);throw await o.text?.().catch(()=>{}),t?new lr(se.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:o.statusText}):new at}let i=await o.text?.().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.text?.().catch(()=>{})}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}},pA=1,mA={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},fA=new Set(["authorization","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);hA=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,pk(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=mk(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=od(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??mA,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??pA)}async _stepUpAuthorize(e,t){if(this._onInsufficientScope==="throw")throw new dy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new dy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new lr(se.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let r=await this._oauthProvider.tokens(),n=Bd(this._scope,r?.scope,e.scope);this._scope=n;let o=fk(n,r?.scope);return li(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:n,forceReauthorization:o,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ds(this._requestInit?.headers);return new Headers({...e,...r})}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!sn(t))return;let r=t.params?._meta?.[cr];if(typeof r!="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let n=t.params,o=t.method==="resources/read"?typeof n?.uri=="string"?n.uri:void 0:typeof n?.name=="string"?n.name:void 0;o!==void 0&&e.set("mcp-name",rg(o))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!sn(e))return!1;let t=e.params?._meta?.[cr];return typeof t=="string"&&Ir(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:n,requestSignal:o}=e,i=()=>this._abortController?.signal.aborted===!0||o?.aborted===!0;try{let a=await this._commonHeaders(),s=[...a.get("accept")?.split(",").map(d=>d.trim().toLowerCase())??[],"text/event-stream"];a.set("accept",[...new Set(s)].join(", ")),n&&a.set("last-event-id",n);let c=this._abortController?.signal,u=o!==void 0&&c!==void 0?uk(c,o):o??c,l=await(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:a,signal:u});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:m}=Ar(l);this._resourceMetadataUrl=d,this._scope=Bd(this._scope,m)}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit}),await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r);throw await l.text?.().catch(()=>{}),t?new lr(se.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:l.statusText}):new at}if(l.status===403){let{resourceMetadataUrl:d,scope:m,error:v,errorDescription:g}=Ar(l);if(v==="insufficient_scope"){let h=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:m,resourceMetadataUrl:d,errorDescription:g,statusText:l.statusText,text:h},r)!=="AUTHORIZED")throw new at;return this._startOrAuthSse(e,t,r+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}throw new lr(se.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${l.statusText}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(a){throw i()||this.onerror?.(a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let n=this._getNextReconnectionDelay(t),o=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(i=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(a){this.onerror?.(a instanceof Error?a:new Error(String(a)))}}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(o,n,t);this._cancelReconnection=typeof i=="function"?i:void 0}else{let i=setTimeout(o,n);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:a}=t,s=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,c,u=!1,l=!1;(async()=>{try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new vd({onRetry:v=>{this._serverRetryMs=v}})).getReader();for(;;){let{value:v,done:g}=await m.read();if(g)break;if(v.id&&(c=v.id,u=!0,n?.(v.id)),!!v.data&&(!v.event||v.event==="message"))try{let h=Bt.parse(JSON.parse(v.data));(qn(h)||Vn(h))&&(l=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(r||u)&&!l&&this._abortController&&!s()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:a},0):s()||a?.()}catch(m){if(s())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${m}`)),(r||u)&&!l&&this._abortController&&!s())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:a},0)}catch(v){this.onerror?.(new Error(`Failed to reconnect: ${v instanceof Error?v.message:String(v)}`)),a?.()}else a?.()}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new at("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:n}=await hk(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await li(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:n,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new at("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,n=0){try{let{resumptionToken:o,onresumptiontoken:i}=t||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:sn(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(f=>this.onerror?.(f));return}let a=await this._commonHeaders();this._applyBodyDerivedHeaders(a,e);let s=Array.isArray(e)?e.some(f=>rd(f)):rd(e);if(s&&a.delete("mcp-session-id"),t?.headers!==void 0)for(let[f,y]of Object.entries(t.headers))fA.has(f.toLowerCase())||a.set(f,y);a.set("content-type","application/json");let c=[...a.get("accept")?.split(",").map(f=>f.trim().toLowerCase())??[],"application/json","text/event-stream"];a.set("accept",[...new Set(c)].join(", "));let u=this._abortController?.signal,l=t?.requestSignal!==void 0&&u!==void 0?uk(u,t.requestSignal):t?.requestSignal??u,d={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:l},m=await(this._fetch??fetch)(this._url,d);if(s&&m.ok&&(this._sessionId=m.headers.get("mcp-session-id")||void 0),!m.ok){if(m.status===401&&this._authProvider){if(m.headers.has("www-authenticate")){let{resourceMetadataUrl:y,scope:S}=Ar(m);this._resourceMetadataUrl=y,this._scope=Bd(this._scope,S)}if(this._authProvider.onUnauthorized&&!r)return await this._authProvider.onUnauthorized({response:m,serverUrl:this._url,fetchFn:this._fetchWithInit}),await m.text?.().catch(()=>{}),this._send(e,t,!0,n);throw await m.text?.().catch(()=>{}),r?new lr(se.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:m.statusText}):new at}let f=await m.text?.().catch(()=>null);if(m.status===403){let{resourceMetadataUrl:y,scope:S,error:_,errorDescription:$}=Ar(m);if(_==="insufficient_scope"){if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:y,errorDescription:$,statusText:m.statusText,text:f},n)!=="AUTHORIZED")throw new at;return this._send(e,t,r,n+1)}}if(m.status===400&&typeof f=="string"&&this._isModernEnvelopedRequest(e))try{let y=Bt.parse(JSON.parse(f)),S=(Array.isArray(e)?e:[e]).filter(_=>sn(_));if(Vn(y)&&S.some(_=>_.id===y.id)){this.onmessage?.(y);return}}catch{}throw new lr(se.ClientHttpNotImplemented,`Error POSTing to endpoint: ${f}`,{status:m.status,statusText:m.statusText,text:f})}if(m.status===202){await m.text?.().catch(()=>{}),eg(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let v=(Array.isArray(e)?e:[e]).some(f=>"method"in f&&"id"in f&&f.id!==void 0),g=m.headers.get("content-type"),h=cg(g);if(v)if(h==="text/event-stream")this._handleSseStream(m.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h==="application/json"){let f=await m.json(),y=Array.isArray(f)?f.map(S=>Bt.parse(S)):[Bt.parse(f)];for(let S of y)this.onmessage?.(S)}else throw await m.text?.().catch(()=>{}),new ae(se.ClientHttpUnexpectedContent,`Unexpected content type: ${g}`,{contentType:g});else await m.text?.().catch(()=>{})}catch(o){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new lr(se.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}});function Ry(e,t){return{id:e.id,config:e,deploymentId:t,createdAt:new Date,updatedAt:new Date}}function Ur(e,t,r,n){return{id:e,agentId:t,userId:r,transportId:n,messages:[],status:"active",turnCount:0,createdAt:new Date,updatedAt:new Date,metadata:{}}}function Mr(e,t){return{...e,messages:[...e.messages,t],turnCount:t.role==="assistant"?e.turnCount+1:e.turnCount,updatedAt:new Date}}function ho(e,t,r){return{id:e,role:"user",content:t,timestamp:new Date,transportOrigin:r,metadata:{}}}function or(e,t,r){return{id:e,role:"assistant",content:t,timestamp:new Date,transportOrigin:"agent",toolInvocations:r,metadata:{}}}function He(e,t,r,n,o){return{id:e,type:t,timestamp:new Date,agentId:r,sessionId:o,payload:n}}function qi(e){let{config:t,ontology:r,memories:n,messages:o,tools:i,ontologyRenderer:a,transport:s}=e,c=[];c.push(t.systemPrompt),s&&c.push(` + +[Channel: ${s}]`);let u=a.render(r);if(u&&r.entityTypes.length>0&&(c.push(` +--- +`),c.push(u)),n.length>0){c.push(` +--- +# Relevant Context from Memory +`);for(let g of n)c.push(`[${g.entityType}] ${g.content}`)}let l=c.join(` +`),d=Math.ceil(l.length/4),m=o.reduce((g,h)=>g+Math.ceil(h.content.length/4),0),v=i.reduce((g,h)=>g+Math.ceil(JSON.stringify(h.inputSchema).length/4),0);return{systemPrompt:l,messages:o,tools:i,tokenEstimate:d+m+v}}var Kk={"claude-sonnet-4-6":[3,15],"claude-opus-4-6":[15,75],"claude-haiku-4-5-20251001":[.25,1.25],"anthropic.claude-sonnet-4-6-20251022-v1:0":[3,15],"anthropic.claude-opus-4-6-20251022-v1:0":[15,75],"anthropic.claude-haiku-4-5-20251001-v1:0":[.25,1.25]},xy=1.25,Iy=.1;function vr(e,t,r){let n=typeof t=="number"?{inputTokens:t,outputTokens:r??0}:t,o=Kk[e];if(!o)return 0;let[i,a]=o,s=v=>Math.max(0,Number.isFinite(v)?v:0),c=s(n.inputTokens),u=s(n.outputTokens),l=s(n.cacheReadTokens),d=s(n.cacheWriteTokens);return(c*i+u*a+l*i*Iy+d*i*xy)/1e6}var Jk=.003,Fk=.015;function Li(e,t={}){let r="now"in t&&typeof t.now=="function"?{clock:t}:t,n=r.clock??{now:()=>Date.now()},o=r.modelId,i=0,a=0,s=0,c=0,u=0,l=0,d=n.now(),m=v=>Math.max(0,Number.isFinite(v)?v:0);return{recordCall(v){i++;let g=m(v.inputTokens),h=m(v.outputTokens),f=m(v.cacheReadTokens),y=m(v.cacheWriteTokens);s+=g,c+=h,u+=f,l+=y,a+=g+h+f+y},isExhausted(){return this.getStatus().exhausted},getStatus(){let v=n.now()-d,g=o!==void 0?vr(o,{inputTokens:s,outputTokens:c,cacheReadTokens:u,cacheWriteTokens:l}):s*Jk/1e3+c*Fk/1e3,h=!1,f;return e.maxCalls!==void 0&&i>=e.maxCalls?(h=!0,f=`LLM call limit reached (${i}/${e.maxCalls})`):e.maxTokens!==void 0&&a>=e.maxTokens?(h=!0,f=`Token limit reached (${a}/${e.maxTokens})`):e.maxTimeMs!==void 0&&v>=e.maxTimeMs?(h=!0,f=`Time limit reached (${v}ms/${e.maxTimeMs}ms)`):e.maxCostUsd!==void 0&&g>=e.maxCostUsd&&(h=!0,f=`Cost limit reached ($${g.toFixed(4)}/$${e.maxCostUsd})`),{calls:i,tokens:a,timeMs:v,estimatedCostUsd:g,exhausted:h,...f?{exhaustedReason:f}:{}}}}}function Vi(e){return{maxCalls:e}}var Py=100,kn=class{byPhase=new Map;register(t){let r=this.byPhase.get(t.phase)??[];if(r.some(n=>n.name===t.name))throw new Error(`Hook with name "${t.name}" is already registered for phase "${t.phase}"`);r.push(t),this.byPhase.set(t.phase,r)}unregister(t){for(let[r,n]of this.byPhase){let o=n.filter(i=>i.name!==t);o.length!==n.length&&this.byPhase.set(r,o)}}hooksFor(t){return[...this.byPhase.get(t)??[]].sort((o,i)=>(o.priority??Py)-(i.priority??Py))}},_r=class extends Error{hookName;phase;cause;constructor(t,r,n){let o=n instanceof Error?n.message:String(n);super(`Hook "${t}" failed in phase "${r}": ${o}`),this.hookName=t,this.phase=r,this.cause=n,this.name="HookExecutionError"}};function Ki(e){let t=e.onAnnotation??(()=>{});return async function(n,o){let i=e.registry.hooksFor(n),a=o;for(let s of i){let c={phase:n,agent:e.agent,sessionId:e.sessionId,turnId:e.turnId,userContext:e.userContext,payload:a,emit:e.onEvent,annotate:t},u;try{u=await s.run(c)}catch(l){throw new _r(s.name,n,l)}if(u.kind==="short_circuit")return e.onEvent(He(crypto.randomUUID(),"turn.short_circuited",e.agent.id,{hookName:s.name,phase:n,reason:u.reason},e.sessionId)),{payload:a,shortCircuited:!0,correctionRequested:!1,reason:u.reason,finalResponse:u.finalResponse,hookName:s.name};if(u.kind==="request_correction"){if(n!=="pre_capture")throw new _r(s.name,n,new Error(`request_correction outcome is only valid from "pre_capture", got "${n}"`));return{payload:a,shortCircuited:!1,correctionRequested:!0,correctionPrompt:u.correctionPrompt,hookName:s.name}}u.payload&&(a={...a,...u.payload})}return{payload:a,shortCircuited:!1,correctionRequested:!1}}}function ec(e,t){if(t.entityTypes.length===0)return[];let r=[];for(let n of t.entityTypes){let o=n.name,i=new RegExp(`\\b${op(o)}\\b`,"gi"),a=[...e.matchAll(i)];if(a.length!==0)for(let s of a){let c=s.index,u=Math.max(0,c-20),l=Math.min(e.length,c+o.length+200),d=e.slice(u,l),m=Hk(d,n);r.push({text:d.trim(),entityType:o,properties:Object.keys(m).length>0?m:void 0})}}return r}function Hk(e,t){let r={};for(let n of t.properties){let o=[new RegExp(`\\b${op(n.name)}\\s+(?:is|:|=)\\s+(\\S+)`,"i"),new RegExp(`\\b${op(n.name)}\\s+(\\S+)`,"i")];for(let i of o){let a=e.match(i);if(a){let s=a[1].replace(/[.,;!?)]+$/,"");if(s){r[n.name]=s;break}}}}return r}function tc(e,t){let r={valid:[],fixable:[],friction:[]};for(let n of e)Zk(n,t,r);return r}function Zk(e,t,r){let n=Wk(e.entityType,t);if(n.status==="unknown"){r.friction.push({claim:e,frictionType:"unknown_entity",context:`Entity type "${e.entityType}" is not defined in the ontology. Known types: ${t.entityTypes.map(a=>a.name).join(", ")}`});return}if(n.status==="fixable"){r.fixable.push({claim:e,suggestion:`Use "${n.resolved.name}" instead of "${e.entityType}"`});return}let o=n.resolved;if(!e.properties||Object.keys(e.properties).length===0){r.valid.push(e);return}let i=!1;for(let[a,s]of Object.entries(e.properties)){let c=Bk(a,s,o);if(c.status==="fixable"){r.fixable.push({claim:e,suggestion:c.suggestion}),i=!0;break}if(c.status==="unknown_property"){r.friction.push({claim:e,frictionType:"unknown_property",context:`Property "${a}" does not exist on entity type "${o.name}". Known properties: ${o.properties.map(u=>u.name).join(", ")}`,propertyName:a,availableProperties:o.properties.map(u=>u.name)}),i=!0;continue}if(c.status==="invalid_value"){let u=o.properties.find(l=>l.name===a)??o.properties.find(l=>l.name.toLowerCase()===a.toLowerCase());r.friction.push({claim:e,frictionType:"invalid_value",context:c.context,propertyName:a,allowedValues:u?.enumValues??[]}),i=!0;continue}}i||r.valid.push(e)}function Wk(e,t){if(!e)return{status:"exact"};let r=t.entityTypes.find(o=>o.name===e);if(r)return{status:"exact",resolved:r};let n=t.entityTypes.find(o=>o.name.toLowerCase()===e.toLowerCase());if(n)return{status:"exact",resolved:n};for(let o of t.entityTypes){let i=e.toLowerCase(),a=o.name.toLowerCase();if(i.includes(a)||a.includes(i))return{status:"fixable",resolved:o}}for(let o of t.entityTypes)if(Cy(e.toLowerCase(),o.name.toLowerCase())<=2)return{status:"fixable",resolved:o};return{status:"unknown"}}function Bk(e,t,r){let n=r.properties.find(i=>i.name===e);if(n)return Ty(n,t,r);let o=r.properties.find(i=>i.name.toLowerCase()===e.toLowerCase());if(o)return Ty(o,t,r);for(let i of r.properties)if(Cy(e.toLowerCase(),i.name.toLowerCase())<=2)return{status:"fixable",suggestion:`Use property "${i.name}" instead of "${e}" on entity type "${r.name}"`};return{status:"unknown_property"}}function Ty(e,t,r){if(e.type==="enum"&&e.enumValues){let n=t.toLowerCase();if(!e.enumValues.find(i=>i.toLowerCase()===n))return{status:"invalid_value",context:`Property "${e.name}" on "${r.name}" only allows: ${e.enumValues.join(", ")}. Got: "${t}"`}}return{status:"valid"}}function Cy(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=t.length;n++)for(let o=1;o<=e.length;o++)t[n-1]===e[o-1]?r[n][o]=r[n-1][o-1]:r[n][o]=Math.min(r[n-1][o-1]+1,r[n][o-1]+1,r[n-1][o]+1);return r[t.length][e.length]}function op(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ay=.7,Gk=new RegExp(["\\bmight\\b","\\bmaybe\\b","\\bperhaps\\b","\\bpossibly\\b","\\bI\\s+think\\b","\\bI\\s+believe\\b","\\bnot\\s+sure\\b","\\bnot\\s+certain\\b","\\bprobably\\b","\\bunlikely\\b","\\bsomewhat\\b","\\bsort\\s+of\\b","\\bkind\\s+of\\b","\\bappears\\s+to\\b","\\bseems\\s+to\\b","\\bcould\\s+be\\b"].join("|"),"gi"),Xk=.15,Yk=3,Qk=.1;function eE(e){if(!e)return 0;let t=e.match(Gk);return t?Math.min(t.length,Yk):0}function Oy(e){let t=e.properties?Object.keys(e.properties).length:0,r=.5+.1*Math.min(t,5),n=eE(e.text),o=Xk*n,i=r-o;return Math.min(1,Math.max(Qk,i))}function tE(e,t){let r={};if(!e.properties)return r;for(let[n,o]of Object.entries(e.properties)){let i=t.properties.find(a=>a.name===n||a.name.toLowerCase()===n.toLowerCase());if(!i){r[n]=o;continue}if(i.type==="number"){let a=Number(o);r[i.name]=Number.isFinite(a)?a:o}else if(i.type==="boolean"){let a=o.toLowerCase();a==="true"?r[i.name]=!0:a==="false"?r[i.name]=!1:r[i.name]=o}else r[i.name]=o}return r}function Ny(e){let{response:t,ontology:r,agent:n,sessionId:o,turnId:i}=e;if(r.entityTypes.length===0||t.length===0)return{toCapture:[],dropped:[]};let a=n.config.captureConfidenceThreshold??Ay,s=ec(t,r);if(s.length===0)return{toCapture:[],dropped:[]};let{valid:c}=tc(s,r),u=[],l=[],d=new Set;for(let m of c){if(!m.entityType)continue;let v=r.entityTypes.find(k=>k.name===m.entityType);if(!v)continue;let g=Oy(m),h=tE(m,v),f=m.text,y=jy(h,v),S=y?`${v.name}::${y.key}::${Ji(y.value)}`:`${v.name}::__no_key__::${f}`;if(d.has(S))continue;if(d.add(S),g0?{structured:h}:{}});continue}if(v.properties.find(k=>k.required&&!(k.name in h))){l.push({entityType:v.name,content:f,confidence:g,threshold:a,reason:"missing_required_property",...Object.keys(h).length>0?{structured:h}:{}});continue}let $={type:"auto_capture",sessionId:o,turnId:i,author:`memory-capture-service:${n.id}`};u.push({id:crypto.randomUUID(),agentId:n.id,scope:"namespace",scopeId:n.config.memoryNamespaces[0]??"default",entityType:v.name,content:f,structured:h,confidence:g,source:$,status:"active",portable:!1,createdAt:new Date,version:1})}return{toCapture:u,dropped:l}}function jy(e,t){return ip(e,t)[0]??null}function ip(e,t){let r=[];"id"in e&&Fi(e.id)&&r.push({key:"id",value:e.id});let n=Object.keys(e).sort();for(let o of n){if(o==="id")continue;let i=e[o];if(Fi(i)){if(t){let a=t.properties.find(s=>s.name===o||s.name.toLowerCase()===o.toLowerCase());if(a&&a.type==="enum")continue}r.push({key:o,value:i})}}return r}function Fi(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ji(e){return typeof e=="string"?e.toLowerCase():String(e)}async function Uy(e,t,r){let n=r?.entityTypes.find(u=>u.name===e.entityType),o=ip(e.structured,n);if(o.length===0)return{kind:"none"};let i;try{i=await t.getByEntityType(e.agentId,e.entityType)}catch{return{kind:"none"}}let a=i.filter(u=>u.scope===e.scope&&u.scopeId===e.scopeId),s=e.structured.id,c=Fi(s);for(let u of o){let l=Ji(u.value),d=a.filter(v=>{if(v.id===e.id||v.status!=="active")return!1;let g=v.structured[u.key];if(g===void 0||!Fi(g)||Ji(g)!==l)return!1;if(u.key!=="id"&&c){let h=v.structured.id;if(Fi(h)&&Ji(h)!==Ji(s))return!1}return!0});if(d.length===0)continue;let m=[...d].sort((v,g)=>{let h=g.createdAt.getTime()-v.createdAt.getTime();if(h!==0)return h;let f=(g.version??0)-(v.version??0);return f!==0?f:v.id.localeCompare(g.id)});return m.length>=2?{kind:"ambiguous",entries:m}:{kind:"one",entry:m[0]}}return{kind:"none"}}async function Hi(e){let{memory:t,...r}=e,{toCapture:n,dropped:o}=Ny(r),i=[],a=[],s=[],c=r.ontology.entityTypes.map(u=>u.name);for(let u of n)try{let l=await Uy(u,t,r.ontology);switch(await t.store(u),i.push(u),l.kind){case"none":break;case"one":{try{await t.supersede(l.entry.id,u.id)}catch(d){a.push(`supersede(${l.entry.id} \u2192 ${u.id}) failed: ${d instanceof Error?d.message:String(d)}`)}break}case"ambiguous":{let d=l.entries.map(g=>g.id).sort(),m=`conflicting_facts:${r.sessionId}:${r.agent.id}:${u.entityType}:${d.join(",")}`,v;try{v=JSON.stringify({entityType:u.entityType,candidate:u.structured,conflictingEntryIds:d})}catch{v=""}s.push(He(m,"ontology.friction",r.agent.id,{claim:v,attemptedEntityType:u.entityType,availableEntityTypes:c,frictionType:"conflicting_facts",count:l.entries.length,conflictingEntryIds:d},r.sessionId));break}}}catch(l){a.push(`store(${u.id}) failed: ${l instanceof Error?l.message:String(l)}`)}return{captured:i,dropped:o,errors:a,frictionEvents:s}}var My=2;async function ap(e,t,r,n,o){let i=[],a=[],s=0,c=0,u=0,l=0,d=0,m=n.trace===!0,v=[],g=crypto.randomUUID(),h=[],f="init",y=Ki({registry:n.hooks??new kn,agent:e,sessionId:t,turnId:g,onEvent:J=>i.push(J),onAnnotation:(J,te)=>h.push({phase:f,key:J,value:te})}),S=async(J,te)=>{f=J;try{return await y(J,te)}catch(_e){if(!(_e instanceof _r))throw _e;let ke=_e.message;return h.push({phase:J,key:"blocking.hook_exception",value:ke}),i.push({id:crypto.randomUUID(),type:"turn.annotated",agentId:e.id,sessionId:t,timestamp:new Date,payload:{key:"blocking.hook_exception",phase:J,error:ke}}),{payload:te,shortCircuited:!1,correctionRequested:!1}}},_=await n.sessions.get(t);_||(_=Ur(t,e.id,r.metadata.userId??"unknown",r.transportOrigin)),_=Mr(_,r),i.push(He(crypto.randomUUID(),"message.received",e.id,{messageId:r.id},t));let $=await n.ontologyService.compose(e.id),k=await n.memory.recall({agentId:e.id,query:r.content,limit:20}),w=k.entries,b=o??Vi(e.config.maxTurns||10),E=Li(b,{modelId:e.config.modelId}),j=Math.max(b.maxCalls!=null?b.maxCalls*2:100,1),V=0,A=null,L=!1,Z=null;try{let J=await S("pre_turn",{userMessage:r,ontology:$,memories:w,session:_});J.shortCircuited?Z={finalResponse:J.finalResponse??null,reason:J.reason}:($=J.payload.ontology,w=J.payload.memories);let te=[];if(!Z)for(let T of e.config.toolScopes){let D=await n.tools.discoverTools(T);te.push(...D)}let _e=20,ke=_.messages.length>_e?_.messages.slice(-_e):_.messages,Ne=Z?{systemPrompt:"",messages:[],tools:[],tokenEstimate:0}:qi({config:e.config,ontology:$,memories:w,messages:ke,tools:te,ontologyRenderer:n.ontologyRenderer,transport:r.transportOrigin});if(!Z){let T=await S("pre_context",{context:Ne,recall:k,recallQuery:r.content,availableEntityTypes:$.entityTypes.map(D=>D.name)});T.shortCircuited?Z={finalResponse:T.finalResponse??null,reason:T.reason}:Ne=T.payload.context}let be=[...ke];m&&v.push({step:"start",timestamp:Date.now(),data:{sessionMessages:_.messages.length,windowedMessages:ke.length,hardCap:j,budget:b}});let P=0;t:for(;!Z;){A=null;e:for(;V0){let Ee=!1;for(let Ze of Pe.toolCalls){let je=await S("pre_tool",{call:Ze});if(je.shortCircuited){Z={finalResponse:je.finalResponse??null,reason:je.reason},A=Pe,Ee=!0;break}let De=je.payload.call;i.push(He(crypto.randomUUID(),"tool.invoked",e.id,{tool:De.toolName},t));let nt=await n.tools.execute(De),Jt=$.entityTypes.map(rr=>rr.name),yt=await S("post_tool",{call:De,result:nt,availableEntityTypes:Jt}),ut=yt.payload.result;a.push(ut),i.push(He(crypto.randomUUID(),"tool.completed",e.id,{tool:De.toolName,status:ut.status},t));let Ft=De.id;if(be=[...be,{id:crypto.randomUUID(),role:"assistant",content:Pe.content,timestamp:new Date,transportOrigin:"agent",toolInvocations:[{toolName:De.toolName,input:De.input,output:ut.output,durationMs:ut.durationMs,status:ut.status}],metadata:{toolUseId:Ft}},{id:crypto.randomUUID(),role:"tool",content:typeof ut.output=="string"?ut.output:JSON.stringify(ut.output),timestamp:new Date,transportOrigin:"tool",metadata:{toolName:De.toolName,callId:Ft}}],yt.shortCircuited){Z={finalResponse:yt.finalResponse??null,reason:yt.reason},A=Pe,Ee=!0;break}}if(Ee)break e;if(E.isExhausted()){m&&v.push({step:"budget_check",timestamp:Date.now(),data:{exhausted:!0,status:E.getStatus()}}),A=Pe,L=!0;break e}m&&v.push({step:"budget_check",timestamp:Date.now(),data:{exhausted:!1,status:E.getStatus()}})}else{A=Pe;break e}}if(Z)break t;let T=A?.content??(E.getStatus().exhausted||L?"[Agent budget exhausted]":"[Agent reached max turns without completing]"),D=or(crypto.randomUUID(),T,a.map(ne=>({toolName:ne.toolName,input:{},output:ne.output,durationMs:ne.durationMs,status:ne.status}))),oe=await S("pre_capture",{response:D,toolResults:a,ontology:$});if(oe.correctionRequested){if(P({toolName:T.toolName,input:{},output:T.output,durationMs:T.durationMs,status:T.status})));_=Mr(_,O),await n.sessions.save(_),i.push(He(crypto.randomUUID(),"message.sent",e.id,{messageId:O.id},t));let W=[],ce=[];try{let T=await Hi({response:O.content,ontology:$,agent:e,sessionId:t,turnId:g,memory:n.memory});W=T.captured,ce=T.dropped;for(let D of T.errors)h.push({phase:"post_capture",key:"memory.capture_error",value:D});for(let D of T.frictionEvents)i.push(D)}catch(T){h.push({phase:"post_capture",key:"memory.capture_error",value:T instanceof Error?T.message:String(T)})}let $e=$.entityTypes.map(T=>T.name),B;if(W.length>0)for(let T of W)try{let D=await n.memory.getSupersedeChain(T.id);if(D.length===0)continue;let oe=Object.keys(T.structured).sort(),ie=oe.filter(Ee=>Ee!=="id")[0]??oe[0];if(!ie||D.filter(Ee=>ie in Ee.structured).lengthEe.structured[ie]);B={chainAnchor:T.id,entityType:T.entityType,propertyName:ie,currentValue:T.structured[ie],priorValues:Pe};break}catch{continue}let Re=await S("post_capture",{captured:W,availableEntityTypes:$e,droppedCandidates:ce,...B?{recentlyCaptured:B}:{}});Re.shortCircuited&&!Z&&(Z={finalResponse:Re.finalResponse??null,reason:Re.reason});let Fe=vr(e.config.modelId,{inputTokens:s,outputTokens:c,cacheReadTokens:u,cacheWriteTokens:l});m&&v.push({step:"complete",timestamp:Date.now(),data:{budgetExhausted:K,responseLength:O.content.length,totalLLMCalls:V,hardCap:j}});let R={response:O,session:_,memoriesCaptured:W,events:i,toolResults:a,usage:{inputTokens:s,outputTokens:c,llmCalls:d,estimatedCostUSD:Fe},budgetExhausted:K,budgetStatus:{calls:M.calls,tokens:M.tokens,timeMs:M.timeMs,...M.exhaustedReason?{reason:M.exhaustedReason}:{}},...m?{trace:v}:{}};return await S("post_turn",{result:R,availableEntityTypes:$e}),R}catch(J){let te={response:or(crypto.randomUUID(),`[Agent error: ${J instanceof Error?J.message:String(J)}]`,[]),session:_,memoriesCaptured:[],events:i,toolResults:a,usage:{inputTokens:s,outputTokens:c,llmCalls:d,estimatedCostUSD:vr(e.config.modelId,{inputTokens:s,outputTokens:c,cacheReadTokens:u,cacheWriteTokens:l})}};try{await S("post_turn",{result:te,availableEntityTypes:$.entityTypes.map(_e=>_e.name)})}catch{}throw J}}var eO=new RegExp("\\b[A-Za-z0-9]{32,}\\b","g");async function*Dy(e,t,r,n,o,i){let a=[],s=[],c=0,u=0,l=0,d=0,m=0,v=o??Vi(e.config.maxTurns||10),g=Li(v,{modelId:e.config.modelId}),h=Math.max(v.maxCalls!=null?v.maxCalls*2:100,1),f=!1,y=crypto.randomUUID(),S=[],_="init",$=Ki({registry:n.hooks??new kn,agent:e,sessionId:t,turnId:y,onEvent:te=>a.push(te),onAnnotation:(te,_e)=>S.push({phase:_,key:te,value:_e})}),k=async(te,_e)=>{_=te;try{return await $(te,_e)}catch(ke){if(!(ke instanceof _r))throw ke;let Ne=ke.message;return S.push({phase:te,key:"streaming.hook_exception",value:Ne}),a.push(Zt(e.id,t,"streaming.hook_exception",{phase:te,error:Ne})),{payload:_e,shortCircuited:!1,correctionRequested:!1}}},w=r.metadata?.userId??"unknown",b=await n.sessions.get(t);b||(b=Ur(t,e.id,w,r.transportOrigin)),b=Mr(b,r),a.push(He(crypto.randomUUID(),"message.received",e.id,{messageId:r.id},t));let E=await n.ontologyService.compose(e.id),j=await n.memory.recall({agentId:e.id,query:r.content,limit:20}),V=j.entries,A=!1,L,Z=null,J=!1;try{let te=await k("pre_turn",{userMessage:r,ontology:E,memories:V,session:b});te.shortCircuited?(L=te.reason,Z=te.finalResponse??null,yield sp("pre_turn",te.reason,te.finalResponse),J=!0):(E=te.payload.ontology,V=te.payload.memories);let _e=[];if(!J)for(let B of e.config.toolScopes){let Re=await n.tools.discoverTools(B);_e.push(...Re)}let ke=20,Ne=b.messages.length>ke?b.messages.slice(-ke):b.messages,be=J?{systemPrompt:"",messages:[],tools:[],tokenEstimate:0}:qi({config:e.config,ontology:E,memories:V,messages:Ne,tools:_e,ontologyRenderer:n.ontologyRenderer,transport:r.transportOrigin});if(!J){let B=await k("pre_context",{context:be,recall:j,recallQuery:r.content,availableEntityTypes:E.entityTypes.map(Re=>Re.name)});B.shortCircuited?(L=B.reason,Z=B.finalResponse??null,yield sp("pre_context",B.reason,B.finalResponse),J=!0):be=B.payload.context}let P=[...Ne],M="";for(;!J&&m0?"tool_use":"end_turn"};g.recordCall(T.usage);let D=await k("post_llm",{response:T,callNumber:m});c+=T.usage.inputTokens,u+=T.usage.outputTokens,l+=T.usage.cacheReadTokens??0,d+=T.usage.cacheWriteTokens??0;let oe=D.payload.response;if(D.shortCircuited){a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"post_llm",reason:D.reason}));break}if(oe.toolCalls.length===0)break;let ne=E.entityTypes.map(me=>me.name),ie=!1;for(let me of oe.toolCalls){let Pe=await k("pre_tool",{call:me});if(Pe.shortCircuited){a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"pre_tool",reason:Pe.reason})),ie=!0;break}let Ee=Pe.payload.call;a.push(He(crypto.randomUUID(),"tool.invoked",e.id,{tool:Ee.toolName},t));let Ze=await n.tools.execute(Ee),je=await k("post_tool",{call:Ee,result:Ze,availableEntityTypes:ne}),De=je.payload.result;if(s.push(De),a.push(He(crypto.randomUUID(),"tool.completed",e.id,{tool:Ee.toolName,status:De.status},t)),P=[...P,{id:crypto.randomUUID(),role:"assistant",content:Re,timestamp:new Date,transportOrigin:"agent",toolInvocations:[{toolName:Ee.toolName,input:Ee.input,output:De.output,durationMs:De.durationMs,status:De.status}],metadata:{toolUseId:Ee.id}},{id:crypto.randomUUID(),role:"tool",content:typeof De.output=="string"?De.output:JSON.stringify(De.output),timestamp:new Date,transportOrigin:"tool",metadata:{toolName:Ee.toolName,callId:Ee.id}}],je.shortCircuited){a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"post_tool",reason:je.reason})),ie=!0;break}}if(ie)break;if(g.isExhausted()){f=!0;let me=g.getStatus();a.push(Zt(e.id,t,"streaming.budget_exhausted",{reason:me.exhaustedReason,calls:me.calls})),yield` +[Agent budget exhausted${me.exhaustedReason?`: ${me.exhaustedReason}`:""}]`;break}}let K=J?Z??or(crypto.randomUUID(),`[Agent short-circuited${L?`: ${L}`:""}]`,[]):or(crypto.randomUUID(),f&&M.trim().length===0?"[Agent budget exhausted]":M,s.map(B=>({toolName:B.toolName,input:{},output:B.output,durationMs:B.durationMs,status:B.status}))),z=K,I=[],O=[];if(!J){let B=await k("pre_capture",{response:K,toolResults:s,ontology:E});B.correctionRequested?a.push(Zt(e.id,t,"streaming.correction_requested",{hookName:B.hookName,correctionPrompt:B.correctionPrompt})):B.shortCircuited&&a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"pre_capture",reason:B.reason})),z=B.shortCircuited&&B.finalResponse?B.finalResponse:K;try{let T=await Hi({response:z.content,ontology:E,agent:e,sessionId:t,turnId:y,memory:n.memory});I=T.captured,O=T.dropped;for(let D of T.errors)a.push(Zt(e.id,t,"streaming.memory_capture_error",{error:D}));for(let D of T.frictionEvents)a.push(D)}catch(T){a.push(Zt(e.id,t,"streaming.memory_capture_error",{error:T instanceof Error?T.message:String(T)}))}let Re=E.entityTypes.map(T=>T.name),Fe;if(I.length>0)for(let T of I)try{let D=await n.memory.getSupersedeChain(T.id);if(D.length===0)continue;let oe=Object.keys(T.structured).sort(),ie=oe.filter(Ee=>Ee!=="id")[0]??oe[0];if(!ie||D.filter(Ee=>ie in Ee.structured).lengthEe.structured[ie]);Fe={chainAnchor:T.id,entityType:T.entityType,propertyName:ie,currentValue:T.structured[ie],priorValues:Pe};break}catch{continue}let R=await k("post_capture",{captured:I,availableEntityTypes:Re,droppedCandidates:O,...Fe?{recentlyCaptured:Fe}:{}});R.shortCircuited&&a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"post_capture",reason:R.reason}))}b=Mr(b,z),await n.sessions.save(b),a.push(He(crypto.randomUUID(),"message.sent",e.id,{messageId:z.id},t));let W=g.getStatus(),ce=f||W.exhausted,$e={response:z,session:b,memoriesCaptured:I,events:a,toolResults:s,usage:{inputTokens:c,outputTokens:u,llmCalls:m,estimatedCostUSD:vr(e.config.modelId,{inputTokens:c,outputTokens:u,cacheReadTokens:l,cacheWriteTokens:d})},budgetExhausted:ce,budgetStatus:{calls:W.calls,tokens:W.tokens,timeMs:W.timeMs,...W.exhaustedReason?{reason:W.exhaustedReason}:{}}};try{await k("post_turn",{result:$e,availableEntityTypes:E.entityTypes.map(B=>B.name)})}catch{}}catch(te){let _e=g.getStatus(),ke={response:or(crypto.randomUUID(),`[Agent error: ${te instanceof Error?te.message:String(te)}]`,[]),session:b,memoriesCaptured:[],events:a,toolResults:s,usage:{inputTokens:c,outputTokens:u,llmCalls:m,estimatedCostUSD:vr(e.config.modelId,{inputTokens:c,outputTokens:u,cacheReadTokens:l,cacheWriteTokens:d})},budgetExhausted:f||_e.exhausted,budgetStatus:{calls:_e.calls,tokens:_e.tokens,timeMs:_e.timeMs,..._e.exhaustedReason?{reason:_e.exhaustedReason}:{}}};try{await k("post_turn",{result:ke,availableEntityTypes:E.entityTypes.map(Ne=>Ne.name)})}catch{}throw te}}function sp(e,t,r){return r?.content?r.content:`[Agent short-circuited at ${e}${t?`: ${t}`:""}]`}function Zt(e,t,r,n){return{id:crypto.randomUUID(),type:"turn.annotated",agentId:e,sessionId:t,timestamp:new Date,payload:{key:r,...n}}}function Ly(e,t=new Map){let r=new Map(t),n={async compose(a){let s=r.get(a);if(!s)throw new Error(`Agent not found: ${a}`);let c=s.config.ontologyScopes;return e.ontologyRepo.compose(c)},render(a){return qy(a)},async validate(a,s){let c=r.values().next().value;if(!c)return!0;let u=await e.ontologyRepo.compose(c.config.ontologyScopes);return e.ontologyRepo.validateEntry(a,s,u).valid}},o={render:qy};return{async handleMessage({agentId:a,sessionId:s,message:c,budget:u}){let l=r.get(a);if(!l)throw new Error(`Agent not found: ${a}`);let d=await ap(l,s,c,{llm:e.llm,tools:e.toolExecutor,memory:e.memory,sessions:e.sessions,ontologyService:n,ontologyRenderer:o,transport:e.transport??nE,embedding:e.embedding},u);return{message:d.response,session:d.session,memoriesCaptured:d.memoriesCaptured,delegations:[],usage:d.usage}},handleMessageStream({agentId:a,sessionId:s,message:c,budget:u,hooks:l,signal:d}){let m=r.get(a);if(!m)throw new Error(`Agent not found: ${a}`);return Dy(m,s,c,{llm:e.llm,tools:e.toolExecutor,memory:e.memory,sessions:e.sessions,ontologyService:n,ontologyRenderer:o,embedding:e.embedding,...l?{hooks:l}:{}},u,d)},async startSession({agentId:a,userId:s,transportId:c}){let u=Ur(crypto.randomUUID(),a,s,c);return await e.sessions.save(u),u},async getAgent(a){return r.get(a)??null},registry:{async getAgent(a){return r.get(a)??null},async listAgents(){return Array.from(r.values())},async registerAgent(a,s){let c=Ry(a,s);return r.set(c.id,c),c}}}}function qy(e){if(e.entityTypes.length===0)return"";let t=["# Domain Ontology"];for(let r of e.entityTypes){let n=r.properties.map(a=>a.name).join(", "),o=e.relationships.filter(a=>a.fromType===r.name).map(a=>`${a.name}\u2192${a.toType}`).join(", "),i=`## ${r.name}: [${n}]`;o&&(i+=` | ${o}`),r.description&&r.description!==r.name&&(i+=` +${r.description}`),t.push(i)}return t.join(` +`)}var nE={async send(){},async stream(){}};function Vy(e){let t=[];for(let r of e)if(r.role==="user")t.push({role:"user",content:r.content});else if(r.role==="assistant")if(r.toolInvocations&&r.toolInvocations.length>0){let n=[];r.content&&n.push({type:"text",text:r.content});let o=r.metadata?.toolUseId||r.toolInvocations[0].toolName+"_"+Math.random().toString(36).slice(2);for(let i of r.toolInvocations)n.push({type:"tool_use",id:o,name:i.toolName,input:i.input});t.push({role:"assistant",content:n})}else t.push({role:"assistant",content:r.content});else if(r.role==="tool"){let n=r.metadata?.toolName||"unknown",o=r.metadata?.callId||n+"_"+Date.now();t.push({role:"user",content:[{type:"tool_result",tool_use_id:o,content:r.content}]})}return t}function Ky(e){return e.map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema}))}var rc=class{config;constructor(t){this.config=t}async complete(t){let r={model:t.model||this.config.defaultModel||"claude-sonnet-4-6",max_tokens:t.maxTokens||this.config.maxTokens||4096,system:t.systemPrompt,messages:Vy(t.messages)};t.temperature!==void 0&&(r.temperature=t.temperature),t.tools&&t.tools.length>0&&(r.tools=Ky(t.tools));let n=this.config.baseUrl||"https://api.anthropic.com",o=await fetch(`${n}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify(r)});if(!o.ok){let c=await o.text();throw new Error(`Anthropic API error: ${o.status} ${c}`)}let i=await o.json(),a="",s=[];for(let c of i.content||[])c.type==="text"?a+=c.text:c.type==="tool_use"&&s.push({id:c.id,toolName:c.name,input:c.input,timestamp:new Date});return{content:a,toolCalls:s,usage:{inputTokens:i.usage?.input_tokens||0,outputTokens:i.usage?.output_tokens||0},stopReason:i.stop_reason==="tool_use"?"tool_use":i.stop_reason==="max_tokens"?"max_tokens":"end_turn"}}async*stream(t){let r={model:t.model||this.config.defaultModel||"claude-sonnet-4-6",max_tokens:t.maxTokens||this.config.maxTokens||4096,system:t.systemPrompt,messages:Vy(t.messages),stream:!0};t.temperature!==void 0&&(r.temperature=t.temperature),t.tools&&t.tools.length>0&&(r.tools=Ky(t.tools));let n=this.config.baseUrl||"https://api.anthropic.com",o=await fetch(`${n}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify(r),signal:t.signal});if(!o.ok){let f=await o.text();throw new Error(`Anthropic streaming error: ${o.status} ${f}`)}let i=o.body?.getReader();if(!i)throw new Error("No response body for streaming");let a=new TextDecoder,s="",c=0,u=0,l=0,d=0,m=!1,v=new Map,g=f=>typeof f!="number"||!Number.isFinite(f)||f<0?null:f,h=()=>{if(!m)return{type:"done"};let f={inputTokens:c,outputTokens:u};return l>0&&(f.cacheReadTokens=l),d>0&&(f.cacheWriteTokens=d),{type:"done",usage:f}};for(;;){let{done:f,value:y}=await i.read();if(f)break;s+=a.decode(y,{stream:!0});let S=s.split(` +`);s=S.pop()||"";for(let _ of S){if(!_.startsWith("data: "))continue;let $=_.slice(6).trim();if($==="[DONE]"){yield h();return}try{let k=JSON.parse($);if(k.type==="message_start"){let w=k.message?.usage;if(w){let b=g(w.input_tokens),E=g(w.output_tokens),j=g(w.cache_read_input_tokens),V=g(w.cache_creation_input_tokens);(b!==null||E!==null||j!==null||V!==null)&&(m=!0,b!==null&&(c=b),E!==null&&(u=E),j!==null&&(l=j),V!==null&&(d=V))}}else if(k.type==="content_block_delta"){if(k.delta?.type==="text_delta")yield{type:"text",content:k.delta.text};else if(k.delta?.type==="input_json_delta"){let w=k.index,b=w!==void 0?v.get(w):void 0;b&&typeof k.delta.partial_json=="string"&&(b.jsonBuffer+=k.delta.partial_json)}}else if(k.type==="content_block_start"){if(k.content_block?.type==="tool_use"){let w=k.index;w!==void 0&&v.set(w,{id:k.content_block.id,toolName:k.content_block.name,jsonBuffer:""})}}else if(k.type==="content_block_stop"){let w=k.index,b=w!==void 0?v.get(w):void 0;if(b){let E={};if(b.jsonBuffer.trim().length>0)try{let j=JSON.parse(b.jsonBuffer);j!==null&&typeof j=="object"&&!Array.isArray(j)&&(E=j)}catch{}yield{type:"tool_call",toolCall:{id:b.id,toolName:b.toolName,input:E,timestamp:new Date}},v.delete(w)}}else if(k.type==="message_delta"){let w=k.usage;if(w){let b=g(w.output_tokens);b!==null&&(m=!0,u=b)}}else if(k.type==="message_stop"){yield h();return}}catch{}}}if(s.length>0)for(let f of s.split(` +`)){if(!f.startsWith("data: "))continue;let y=f.slice(6).trim();if(!(y==="[DONE]"||y.length===0))try{let S=JSON.parse(y);if(S.type==="message_delta"){let _=S.usage;if(_){let $=g(_.output_tokens);$!==null&&(m=!0,u=$)}}}catch{}}yield h()}};var nc=class{callCount=0;async embed(t){this.callCount++;let r=new Array(8).fill(0);for(let o=0;oo+i*i,0));return n>0?r.map(o=>o/n):r}async embedBatch(t){return Promise.all(t.map(r=>this.embed(r)))}getCallCount(){return this.callCount}};var oc=class{entries=[];events=[];async store(t){this.entries.push(t),this.events.push({id:crypto.randomUUID(),entryId:t.id,action:"created",newValue:t.content,author:t.source.author,timestamp:new Date})}async recall(t){let r=t.limit??10,n=t.query.toLowerCase(),o=this.entries.filter(a=>a.agentId!==t.agentId||a.status!=="active"||t.scope&&a.scope!==t.scope||t.scopeId&&a.scopeId!==t.scopeId||t.entityType&&a.entityType!==t.entityType?!1:a.content.toLowerCase().includes(n)).slice(0,r),i=o.length;return{entries:o,source:i>0?"text":"none",vectorCapable:!1,vectorMatchCount:0,textMatchCount:i}}async supersede(t,r){let n=this.entries.find(o=>o.id===t);if(n){let o=this.entries.indexOf(n);this.entries[o]={...n,status:"superseded",supersededBy:r},this.events.push({id:crypto.randomUUID(),entryId:t,action:"superseded",previousValue:n.content,author:"system",timestamp:new Date})}}async getEventLog(t){return this.events.filter(r=>r.entryId===t)}async getByEntityType(t,r){return this.entries.filter(n=>n.agentId===t&&n.entityType===r&&n.status==="active")}async getSupersedeChain(t){let n=[],o=new Set,i=t;o.add(i);let a=this.entries.find(s=>s.id===t);if(a===void 0)return[];for(;n.length<50;){let s=this.entries.filter(u=>u.supersededBy===i&&u.agentId===a.agentId&&u.scope===a.scope&&u.scopeId===a.scopeId&&u.status==="superseded").sort((u,l)=>l.createdAt.getTime()-u.createdAt.getTime());if(s.length===0)break;let c=s[0];if(o.has(c.id))break;o.add(c.id),n.push(c),i=c.id}return n}getAll(){return[...this.entries]}getAllEvents(){return[...this.events]}clear(){this.entries=[],this.events=[]}};var ic=class{sessions=new Map;async get(t){return this.sessions.get(t)??null}async save(t){this.sessions.set(t.id,t)}async findByUser(t,r,n){let o=Array.from(this.sessions.values()).filter(i=>i.userId===t&&i.agentId===r).sort((i,a)=>a.createdAt.getTime()-i.createdAt.getTime());return n?o.slice(0,n):o}async findByUserLightweight(t,r,n){let o=Array.from(this.sessions.values()).filter(a=>a.userId===t&&a.agentId===r).sort((a,s)=>s.updatedAt.getTime()-a.updatedAt.getTime());return(n?o.slice(0,n):o).map(a=>{let s=a.messages.find(u=>u.role==="user"),c=a.messages.length>0?a.messages[a.messages.length-1]:void 0;return{id:a.id,agentId:a.agentId,userId:a.userId,status:a.status,turnCount:a.turnCount,messageCount:a.messages.length,createdAt:a.createdAt,updatedAt:a.updatedAt,firstMessage:s?s.content.substring(0,100):void 0,lastMessage:c?c.content.substring(0,100):void 0}})}clear(){this.sessions.clear()}getAll(){return Array.from(this.sessions.values())}};function Jy(e){let t=new Map,r=[];for(let o of e){for(let i of o.entityTypes){let a=t.get(i.name);if(a){let s=new Set(a.properties.map(u=>u.name)),c=i.properties.filter(u=>!s.has(u.name));t.set(i.name,{...a,properties:[...a.properties,...c],description:i.description||a.description})}else t.set(i.name,i)}r.push(...o.relationships)}let n=new Map;for(let o of r)n.set(o.id,o);return{layers:e,entityTypes:Array.from(t.values()),relationships:Array.from(n.values()),version:e.map(o=>`${o.name}@${o.version}`).join("+")}}function Fy(e,t,r){let n=[],o=[],i=r.entityTypes.find(a=>a.name===e);if(!i)return{valid:!1,errors:[{field:"entityType",message:`Unknown entity type: ${e}`,code:"unknown_entity"}],warnings:[]};for(let a of i.properties)a.required&&!(a.name in t)&&n.push({field:a.name,message:`Required property missing: ${a.name}`,code:"missing_required"});for(let[a,s]of Object.entries(t)){let c=i.properties.find(u=>u.name===a);if(!c){o.push(`Property "${a}" not defined in ontology for ${e}`);continue}c.type==="enum"&&c.enumValues&&s!==void 0&&(c.enumValues.includes(String(s))||n.push({field:a,message:`Invalid value "${s}" for enum ${a}. Expected one of: ${c.enumValues.join(", ")}`,code:"invalid_enum"})),s!=null&&(oE(s,c.type)||n.push({field:a,message:`Expected ${c.type} for ${a}, got ${typeof s}`,code:"invalid_type"}))}return{valid:n.length===0,errors:n,warnings:o}}function oE(e,t){switch(t){case"string":case"enum":return typeof e=="string";case"number":return typeof e=="number";case"boolean":return typeof e=="boolean";case"date":return typeof e=="string"||e instanceof Date;case"reference":return typeof e=="string";default:return!0}}var ac=class{layers=new Map;async getLayer(t){return this.layers.get(t)??null}async getLayersByScope(t){return Array.from(this.layers.values()).filter(r=>r.scope===t)}async compose(t){let r=t.map(n=>this.layers.get(n)).filter(n=>n!=null);return Jy(r)}validateEntry(t,r,n){let o=Fy(t,r,n);return{valid:o.valid,errors:o.errors.map(i=>i.message)}}addLayer(t){this.layers.set(t.id,t)}clear(){this.layers.clear()}};function Hy(e,t){let r=[],n=[];for(let[o,i]of Object.entries(t.entities||{})){let a=[];if(i.properties)for(let c of i.properties)a.push({name:c,type:"string",required:!1,description:""});for(let[c,u]of Object.entries(i))Array.isArray(u)&&c!=="properties"&&c!=="belongs_to"&&c!=="has_many"&&c!=="connects"&&u.every(l=>typeof l=="string")&&a.push({name:c,type:"enum",enumValues:u,required:!1,description:`${c} for ${o}`});r.push({id:`${e}:${o}`,layerId:e,name:o,properties:a,description:i.description||o});let s=i.belongs_to?Array.isArray(i.belongs_to)?i.belongs_to:[i.belongs_to]:[];for(let c of s)n.push({id:`${e}:${o}:belongs_to:${c}`,layerId:e,name:"belongs_to",fromType:o,toType:c,cardinality:"many_to_many",description:`${o} belongs to ${c}`});for(let c of i.has_many||[])n.push({id:`${e}:${o}:has_many:${c}`,layerId:e,name:"has_many",fromType:o,toType:c,cardinality:"one_to_many",description:`${o} has many ${c}`});for(let c of i.connects||[])n.push({id:`${e}:${o}:connects:${c}`,layerId:e,name:"connects",fromType:o,toType:c,cardinality:"many_to_many",description:`${o} connects to ${c}`})}return{id:e,name:t.name,scope:t.scope,version:1,entityTypes:r,relationships:n,createdAt:new Date,updatedAt:new Date}}function Sy(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}var tp=e=>typeof e=="string"?e.toLowerCase():"",js=class{servers;scopePrefix;mode;clientFactory;clients=new Map;connecting=new Map;toolCache=new Map;routes=new Map;constructor(t){this.servers=new Map(t.servers.map(r=>[r.id,r])),this.scopePrefix=t.scopePrefix??"mcp",this.mode=t.mode??"direct",this.clientFactory=t.clientFactory??vA}serverForScope(t){let r=`${this.scopePrefix}:`;return t.startsWith(r)?this.servers.get(t.slice(r.length))??null:null}async getClient(t){let r=this.clients.get(t.id);if(r)return r;let n=this.connecting.get(t.id);if(n)return n;let o=(async()=>{let i=this.clientFactory(t);return await i.connect(),this.clients.set(t.id,i),this.connecting.delete(t.id),i})().catch(i=>{throw this.connecting.delete(t.id),i});return this.connecting.set(t.id,o),o}async fetchRawTools(t){let r=this.toolCache.get(t.id);if(r)return r;let i=(await(await this.getClient(t)).listTools()).tools??[];return this.toolCache.set(t.id,i),i}async discoverTools(t){let r=this.serverForScope(t);return r?this.mode==="proxy"?this.discoverProxy(r,t):this.discoverDirect(r,t):[]}discoverProxy(t,r){let n=Sy(`${t.id}__list_tools`),o=Sy(`${t.id}__call_tool`);return this.routes.set(n,{serverId:t.id,proxy:"list"}),this.routes.set(o,{serverId:t.id,proxy:"call"}),[{name:n,description:`List or search the tools available from the "${t.id}" MCP server. Returns each tool's name, description, and input schema. Call this to discover what "${t.id}" can do before using ${o}.`,inputSchema:{type:"object",properties:{query:{type:"string",description:"Optional filter over tool name/description."}},additionalProperties:!1},source:r,requiresApproval:!1,permissionScope:`${r}:list`},{name:o,description:`Invoke a tool on the "${t.id}" MCP server. Use ${n} first to find the exact tool name and its required arguments.`,inputSchema:{type:"object",properties:{tool:{type:"string",description:`Tool name from ${n}.`},arguments:{type:"object",description:"Arguments object matching that tool's input schema."}},required:["tool"],additionalProperties:!1},source:r,requiresApproval:!1,permissionScope:`${r}:call`}]}async discoverDirect(t,r){let n;try{n=await this.fetchRawTools(t)}catch(a){return console.log(`mcp-client: discover failed for ${t.id}:`,a instanceof Error?a.message:String(a)),[]}let o=[],i=new Set;for(let a of n){let s=Sy(`${t.id}__${a.name}`);if(i.has(s)){let c=s.slice(0,61),u=1;for(;i.has(`${c}_${u}`);)u++;s=`${c}_${u}`}i.add(s),this.routes.set(s,{serverId:t.id,toolName:a.name}),o.push({name:s,description:a.description??`${a.name} (via ${t.id})`,inputSchema:a.inputSchema??{type:"object",properties:{}},source:r,requiresApproval:!1,permissionScope:`${r}:call`})}return o}async execute(t){let r=Date.now(),n=(s,c,u)=>({callId:t.id,toolName:t.toolName,output:s,status:c,...u?{error:u}:{},durationMs:Date.now()-r,timestamp:new Date}),o=this.routes.get(t.toolName);if(!o)return n(null,"error",`unknown MCP tool: ${t.toolName}`);let i=this.servers.get(o.serverId);if(!i)return n(null,"error",`unknown MCP server: ${o.serverId}`);let a=t.input??{};try{if(o.proxy==="list"){let v=typeof a.query=="string"?a.query:"",g=(await this.fetchRawTools(i)).filter(h=>!v||tp(h.name).includes(tp(v))||tp(h.description).includes(tp(v))).slice(0,40).map(h=>({tool:h.name,description:h.description??"",inputSchema:h.inputSchema??{type:"object"}}));return n({server:i.id,count:g.length,tools:g},"success")}let s=o.proxy==="call"?typeof a.tool=="string"?a.tool:"":o.toolName??"";if(!s)return n(null,"error",`no tool name provided for ${t.toolName}`);let c=o.proxy==="call"?a.arguments??{}:a,l=await(await this.getClient(i)).callTool({name:s,arguments:c}),m=(l.content??[]).filter(v=>v.type==="text"&&typeof v.text=="string").map(v=>v.text).join(` +`).trim()||l.content||null;return n(m,l.isError?"error":"success")}catch(s){return n(null,"error",s instanceof Error?s.message:String(s))}}async close(){for(let t of this.clients.values())try{await t.close?.()}catch{}this.clients.clear()}};function vA(e){let t=null,r=async()=>{let{Client:n,StreamableHTTPClientTransport:o}=await Promise.resolve().then(()=>(Mk(),Uk)),i=new n({name:"freya-mcp-client",version:"0.1.0"}),a=new o(new URL(e.url),e.headers?{requestInit:{headers:e.headers}}:void 0);return await i.connect(a),{listTools:()=>i.listTools(),callTool:s=>i.callTool(s),close:()=>i.close()}};return{async connect(){t=r(),await t},async listTools(){return t||(t=r()),(await t).listTools()},async callTool(n){return t||(t=r()),(await t).callTool(n)},async close(){t&&await(await t).close()}}}var $y="frigg-web",by="netlify-web",_A={name:"frigg",scope:"domain",entities:{Platform:{description:"A third-party software product Frigg integrates with (e.g. HubSpot, Salesforce, Attio).",properties:["name","vendor"]},ApiModule:{description:"A prebuilt Frigg connector for a platform API, installed with `frigg install ` and drawn from the api-module-library.",properties:["name","provider","authType"],category:["ai","analytics","commerce","communication","crm","devtools","finance","hr","marketing","other","productivity","storage","support"],complexity:["Low","Medium","High"],status:["Active","Beta","Planned"],belongs_to:"Platform"},Integration:{description:"A running integration a developer builds by extending IntegrationBase, wiring API modules to events (USER_ACTION, CRON, QUEUE, WEBHOOK).",properties:["name","useCase"],connects:["ApiModule","Primitive"]},Primitive:{description:"A Frigg building block exposed to developers and their agents: an Endpoint, a Queue, a Provider-native backend, or a Fenestra in-app UI experience.",properties:["name"],kind:["Endpoint","Queue","ProviderNative","Fenestra"]},Capability:{description:"A typed declaration of what a module or integration can do, pointing at a spec and its implementation (the mcp-tool / agent-tooling surface).",properties:["name","spec"],belongs_to:"ApiModule"},Adr:{description:'A Frigg architecture decision record shaping the roadmap, tracked on the "next" branch and surfaced at /roadmap/.',properties:["num","title","theme"],status:["Accepted","Proposed","Superseded","Draft"]},Visitor:{description:"A person chatting with the assistant on the site.",properties:["name","stack","interest"]}}},ro={adrs:[],apis:[],categories:[],builtCount:0},pi=e=>typeof e=="string"?e.toLowerCase():"",to=(e,t)=>!t||pi(e).includes(pi(t)),wy=class{async discoverTools(t){return t!=="roadmap"?[]:[{name:"catalog_stats",description:'Frigg roadmap catalog summary: number of ADRs, number of API modules, how many are already built, and the list of API categories. Call this first for any "how many / what categories" question.',inputSchema:{type:"object",properties:{},additionalProperties:!1},source:"roadmap",requiresApproval:!1,permissionScope:"roadmap:read"},{name:"search_adrs",description:"Search Frigg architecture decision records (ADRs). Filter by free-text query (matches title/summary/theme) and/or status (e.g. Accepted, Proposed). Returns matching ADRs with number, title, status, theme, one-line summary, and URL.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Free-text filter over title/summary/theme"},status:{type:"string",description:'Exact status filter, e.g. "Accepted"'}},additionalProperties:!1},source:"roadmap",requiresApproval:!1,permissionScope:"roadmap:read"},{name:"search_apis",description:"Search the Frigg API module catalog (224 integrations). Filter by free-text query (matches name/provider/description/tags), category, or built=true to only return modules that already exist in api-module-library. Returns a capped list plus the total match count so you can point people to /roadmap/ for the full set.",inputSchema:{type:"object",properties:{query:{type:"string"},category:{type:"string",description:"One of the catalog categories"},built:{type:"boolean",description:"If true, only modules already built"}},additionalProperties:!1},source:"roadmap",requiresApproval:!1,permissionScope:"roadmap:read"}]}async execute(t){let r=Date.now(),n=(o,i="success",a)=>({callId:t.id,toolName:t.toolName,output:o,status:i,error:a,durationMs:Date.now()-r,timestamp:new Date});try{let o=t.input||{};if(t.toolName==="catalog_stats")return n({adrCount:ro.adrs.length,apiCount:ro.apis.length,builtCount:ro.builtCount,categories:ro.categories});if(t.toolName==="search_adrs"){let i=ro.adrs.filter(a=>(to(a.title,o.query)||to(a.summary,o.query)||to(a.theme,o.query))&&(!o.status||pi(a.status)===pi(o.status)));return n({total:i.length,adrs:i.slice(0,12).map(a=>({num:a.num,title:a.title,status:a.status,theme:a.theme,summary:a.summary,url:a.url}))})}if(t.toolName==="search_apis"){let i=ro.apis.filter(a=>(to(a.name,o.query)||to(a.provider,o.query)||to(a.description,o.query)||Array.isArray(a.tags)&&a.tags.some(s=>to(s,o.query)))&&(!o.category||pi(a.category)===pi(o.category))&&(o.built===void 0||!!a.built==!!o.built));return n({total:i.length,showing:Math.min(i.length,15),apis:i.slice(0,15).map(a=>({slug:a.slug,name:a.name,provider:a.provider,category:a.category,status:a.status,complexity:a.complexity,built:!!a.built,library:a.library}))})}return n(null,"error",`unknown tool: ${t.toolName}`)}catch(o){return n(null,"error",o&&o.message?o.message:String(o))}}};function SA(){let e=[];process.env.CONTEXT7_API_KEY&&e.push({id:"frigg-docs",url:process.env.CONTEXT7_MCP_URL||"https://mcp.context7.com/mcp",headers:{CONTEXT7_API_KEY:process.env.CONTEXT7_API_KEY}});let t=process.env.GITHUB_MCP_TOKEN;return t&&e.push({id:"frigg-repo",url:process.env.GITHUB_MCP_URL||"https://api.githubcopilot.com/mcp/",headers:{Authorization:`Bearer ${t}`}}),e}var zy=class{constructor(t){this.executors=t,this.owner=new Map}async discoverTools(t){for(let r of this.executors){let n=await r.discoverTools(t);if(n&&n.length){for(let o of n)this.owner.set(o.name,r);return n}}return[]}async execute(t){let r=this.owner.get(t.toolName);return r?r.execute(t):{callId:t.id,toolName:t.toolName,output:null,status:"error",error:`no executor for tool: ${t.toolName}`,durationMs:0,timestamp:new Date}}},rp=null,ky=null,Dk=!1,qk=[];function bA(){if(rp)return rp;ky=new ic;let e=process.env.ANTHROPIC_API_KEY||"",t=process.env.ANTHROPIC_BASE_URL||void 0,r=[new wy],n=SA();n.length&&(r.push(new js({servers:n,mode:"proxy"})),qk=n.map(i=>`mcp:${i.id}`));let o=new zy(r);return rp=Ly({llm:new rc({apiKey:e,baseUrl:t,defaultModel:process.env.ASSISTANT_MODEL||"claude-opus-4-8",maxTokens:900}),toolExecutor:o,memory:new oc,ontologyRepo:(()=>{let i=new ac;return i.addLayer(Hy("frigg",_A)),i})(),sessions:ky,embedding:new nc}),rp}async function $A(e,t,r){Dk||(await e.registry.registerAgent({id:$y,name:"Freya",type:"shared",systemPrompt:t,ontologyScopes:["frigg"],memoryNamespaces:["default"],toolScopes:["roadmap",...qk],routines:[],delegationTargets:[],modelId:r||process.env.ASSISTANT_MODEL||"claude-opus-4-8",maxTurns:6},"friggframework-org"),Dk=!0)}async function EV({systemPrompt:e,model:t,messages:r,data:n}){if(n){let l=n.apis||{};ro={adrs:n.adrs&&n.adrs.adrs||n.adrs||[],apis:l.apis||(Array.isArray(l)?l:[]),categories:l.categories||[],builtCount:l.builtCount||0}}let o=bA();await $A(o,e,t);let i=r.slice(0,-1),a=r[r.length-1],s=crypto.randomUUID(),c=Ur(s,$y,"web-visitor",by);for(let l of i){let d=l.role==="assistant"?or(crypto.randomUUID(),l.content):ho(crypto.randomUUID(),l.content,by);c=Mr(c,d)}await ky.save(c);let u=await o.handleMessage({agentId:$y,sessionId:s,message:ho(crypto.randomUUID(),a.content,by)});return u&&u.message&&u.message.content||""}export{EV as runTurn}; diff --git a/website/tools/freya-vendor/build.mjs b/website/tools/freya-vendor/build.mjs index 76cb72dee..5ae5e46bf 100644 --- a/website/tools/freya-vendor/build.mjs +++ b/website/tools/freya-vendor/build.mjs @@ -81,6 +81,10 @@ await esbuild.build({ platform: 'node', format: 'esm', target: 'node18', + // Minify — the vendored bundle is a generated artifact (not read/diffed by + // hand, and Sonar-excluded), and the MCP SDK + zod + jose it inlines are + // large. Minifying roughly halves the shipped size with no behavior change. + minify: true, // Resolve bare @freyaframework/* specifiers against the Freya checkout. nodePaths: [freyaModules], // Lazily-imported optional deps the assistant path never touches.