@ogment-ai/cli 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -0
- package/dist/cli.js +1003 -929
- package/package.json +13 -20
- package/dist/cli.js.map +0 -1
package/dist/cli.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":["process","commander","isRecord","isPlainObject","isRecord","isRecord","isPlainObject","isPlainObject","initializer","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","parse","errors.$ZodRealError","parseAsync","errors.$ZodError","safeParse","safeParseAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","duration","_emoji","date","time","datetime","string","number","boolean","_null","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","util.aborted","core.$ZodAsyncError","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","regexes.null","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","_null","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","describe","meta","process","process","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","util.jsonStringifyReplacer","core.$constructor","safeParse","util.mergeDefs","core.clone","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","checks.overwrite","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","number","core._number","core._int","processors.booleanProcessor","core._boolean","processors.nullProcessor","core._null","processors.anyProcessor","core._any","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.recordProcessor","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._custom","core._refine","core._superRefine","core.describe","core.meta","core._coercedNumber","schemas.ZodNumber","z.object","z.string","z.record","z.string","z.unknown","z\n .object","z\n .object","z\n .object","z.string","z.boolean","z.number","z.array","z\n .object","z.string","z.number","z.literal","z.discriminatedUnion","z.object","z.string","#envelopeBuilder","#stderr","#stdout","#mode","#debug","toEndpointUrl","z4mini.safeParse","z.custom","z.union","z.string","z.number","z.looseObject","z.null","z.object","z\n .object","z.literal","z.unknown","z.array","z.enum","z.intersection","z.boolean","z.record","z.preprocess","z\n .looseObject","z\n .looseObject","z\n .object","z.optional","z.iso.datetime","z.discriminatedUnion","Ajv","z\n .url","z.NEVER","z.looseObject","z.string","z.array","z.boolean","z.object","z\n .object","z.coerce.number","z.literal","z.any","z.number","isRecord"],"sources":["../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js","../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js","../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js","../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js","../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js","../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js","../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js","../../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/esm.mjs","../src/shared/error-codes.ts","../../../node_modules/.pnpm/better-result@2.7.0/node_modules/better-result/dist/index.mjs","../src/shared/recovery.ts","../src/shared/errors.ts","../src/shared/exit-codes.ts","../src/commands/auth.ts","../src/shared/guards.ts","../src/shared/error-presentation.ts","../src/commands/server-context.ts","../src/commands/catalog.ts","../src/commands/invoke.ts","../src/commands/status.ts","../src/shared/schema-example.ts","../src/cli/commands.ts","../src/cli/execute.ts","../src/cli/parse-errors.ts","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js","../src/shared/constants.ts","../../../packages/shared/src/cli/common.ts","../../../packages/shared/src/cli/account.ts","../../../packages/shared/src/cli/auth.ts","../../../packages/shared/src/cli/endpoints.ts","../src/shared/schemas.ts","../src/infra/credentials.ts","../src/infra/env.ts","../src/infra/http.ts","../src/output/envelope.ts","../src/output/manager.ts","../src/services/account.ts","../src/services/auth.ts","../src/services/info.ts","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js","../../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json","../../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js","../../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js","../../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json","../../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js","../../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js","../../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js","../../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.2_hono@4.12.2_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js","../src/services/mcp-error-mapping.ts","../src/services/mcp.ts","../src/cli/runtime.ts","../src/cli/program.ts","../src/cli/run.ts","../src/cli.ts"],"sourcesContent":["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n","const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripColor(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n\n/**\n * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.\n *\n * @param {string} str\n * @returns {string}\n * @package\n */\n\nfunction stripColor(str) {\n // eslint-disable-next-line no-control-regex\n const sgrPattern = /\\x1b\\[\\d*(;\\d*)*m/g;\n return str.replace(sgrPattern, '');\n}\n\nexports.Help = Help;\nexports.stripColor = stripColor;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n","const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help, stripColor } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripColor(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n if (this._savedState === null) {\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * @returns {boolean | undefined}\n * @package\n */\nfunction useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n\nexports.Command = Command;\nexports.useColor = useColor; // exporting for tests\n","const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n","import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n","export const ERROR_CATEGORY = {\n auth: 'auth',\n authorization: 'authorization',\n contractMismatch: 'contract_mismatch',\n internal: 'internal',\n notFound: 'not_found',\n rateLimit: 'rate_limit',\n remote: 'remote',\n transport: 'transport',\n validation: 'validation',\n} as const;\n\nexport type ErrorCategory =\n (typeof ERROR_CATEGORY)[keyof typeof ERROR_CATEGORY];\n\nexport const ERROR_CODE = {\n authDeviceExpired: 'AUTH_DEVICE_EXPIRED',\n authDevicePending: 'AUTH_DEVICE_PENDING',\n authInvalidCredentials: 'AUTH_INVALID_CREDENTIALS',\n authRequired: 'AUTH_REQUIRED',\n contractVersionUnsupported: 'CONTRACT_VERSION_UNSUPPORTED',\n internalUnexpected: 'INTERNAL_UNEXPECTED',\n remoteRateLimited: 'REMOTE_RATE_LIMITED',\n remoteUnavailable: 'REMOTE_UNAVAILABLE',\n toolInputSchemaViolation: 'TOOL_INPUT_SCHEMA_VIOLATION',\n toolNotFound: 'TOOL_NOT_FOUND',\n transportRequestFailed: 'TRANSPORT_REQUEST_FAILED',\n validationInvalidInput: 'VALIDATION_INVALID_INPUT',\n} as const;\n\nexport type StaticErrorCode = (typeof ERROR_CODE)[keyof typeof ERROR_CODE];\nexport type HttpStatusErrorCode = `HTTP_${number}`;\nexport type McpNumericErrorCode = `MCP_${number}`;\nexport type ErrorCode =\n | StaticErrorCode\n | HttpStatusErrorCode\n | McpNumericErrorCode;\n\nconst staticErrorCodes = new Set<string>(Object.values(ERROR_CODE));\n\nexport const isStaticErrorCode = (code: ErrorCode): code is StaticErrorCode => {\n return staticErrorCodes.has(code);\n};\n","//#region src/dual.ts\n/**\n* Creates data-first/data-last dual function.\n*\n* @template DataLast Curried (data-last) signature.\n* @template DataFirst Uncurried (data-first) signature.\n* @param arity Number of args for data-first form.\n* @param body Implementation function.\n* @returns Function supporting both calling conventions.\n*\n* @example\n* const add: {\n* (a: number, b: number): number;\n* (b: number): (a: number) => number;\n* } = dual(2, (a: number, b: number) => a + b);\n*\n* add(1, 2); // 3 (data-first)\n* add(2)(1); // 3 (data-last)\n*/\nfunction dual(arity, body) {\n\tif (arity === 2) return ((...args) => {\n\t\tif (args.length >= 2) return body(args[0], args[1]);\n\t\treturn (self) => body(self, args[0]);\n\t});\n\tif (arity === 3) return ((...args) => {\n\t\tif (args.length >= 3) return body(args[0], args[1], args[2]);\n\t\treturn (self) => body(self, args[0], args[1]);\n\t});\n\tif (arity === 4) return ((...args) => {\n\t\tif (args.length >= 4) return body(args[0], args[1], args[2], args[3]);\n\t\treturn (self) => body(self, args[0], args[1], args[2]);\n\t});\n\treturn ((...args) => {\n\t\tif (args.length >= arity) return body(...args);\n\t\treturn (self) => body(self, ...args);\n\t});\n}\n\n//#endregion\n//#region src/error.ts\n/** Serialize cause for JSON output */\nconst serializeCause = (cause) => {\n\tif (cause instanceof Error) return {\n\t\tname: cause.name,\n\t\tmessage: cause.message,\n\t\tstack: cause.stack\n\t};\n\treturn cause;\n};\n/** Type guard for any tagged error */\nconst isAnyTaggedError = (value) => {\n\treturn value instanceof Error && \"_tag\" in value && typeof value._tag === \"string\";\n};\n/**\n* Factory for tagged error classes.\n*\n* @example\n* class NotFoundError extends TaggedError(\"NotFoundError\")<{\n* id: string;\n* message: string;\n* }>() {}\n*\n* const err = new NotFoundError({ id: \"123\", message: \"Not found: 123\" });\n* err._tag // \"NotFoundError\"\n* err.id // \"123\"\n* err.message // \"Not found: 123\"\n*\n* // Check if any tagged error\n* TaggedError.is(err) // true\n*/\nconst TaggedError = Object.assign((tag) => () => {\n\tclass Base extends Error {\n\t\t_tag = tag;\n\t\t/** Type guard for this error class */\n\t\tstatic is(value) {\n\t\t\treturn value instanceof Base;\n\t\t}\n\t\tconstructor(args) {\n\t\t\tconst message = args && \"message\" in args && typeof args.message === \"string\" ? args.message : void 0;\n\t\t\tconst cause = args && \"cause\" in args ? args.cause : void 0;\n\t\t\tsuper(message, cause !== void 0 ? { cause } : void 0);\n\t\t\tif (args) Object.assign(this, args);\n\t\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t\t\tthis.name = tag;\n\t\t\tif (cause instanceof Error && cause.stack) {\n\t\t\t\tconst indented = cause.stack.replace(/\\n/g, \"\\n \");\n\t\t\t\tthis.stack = `${this.stack}\\nCaused by: ${indented}`;\n\t\t\t}\n\t\t}\n\t\ttoJSON() {\n\t\t\treturn {\n\t\t\t\t...this,\n\t\t\t\t_tag: this._tag,\n\t\t\t\tname: this.name,\n\t\t\t\tmessage: this.message,\n\t\t\t\tcause: serializeCause(this.cause),\n\t\t\t\tstack: this.stack\n\t\t\t};\n\t\t}\n\t}\n\treturn Base;\n}, { is: isAnyTaggedError });\n/**\n* Exhaustive pattern match on tagged error union.\n*\n* @example\n* // Data-first\n* matchError(err, {\n* NotFoundError: (e) => `Missing: ${e.id}`,\n* ValidationError: (e) => `Invalid: ${e.field}`,\n* });\n*\n* // Data-last (pipeable)\n* pipe(err, matchError({\n* NotFoundError: (e) => `Missing: ${e.id}`,\n* ValidationError: (e) => `Invalid: ${e.field}`,\n* }));\n*/\nconst matchError = dual(2, (err$1, handlers) => {\n\tconst handler = handlers[err$1._tag];\n\treturn handler(err$1);\n});\n/**\n* Partial pattern match with fallback for unhandled tags.\n*\n* @example\n* matchErrorPartial(err, {\n* NotFoundError: (e) => `Missing: ${e.id}`,\n* }, (e) => `Unknown: ${e.message}`);\n*/\nconst matchErrorPartial = dual(3, (err$1, handlers, fallback) => {\n\tconst handler = handlers[err$1._tag];\n\tif (typeof handler === \"function\") return handler(err$1);\n\treturn fallback(err$1);\n});\n/**\n* Type guard for tagged error instances.\n*\n* @example\n* if (isTaggedError(value)) { value._tag }\n*/\nconst isTaggedError = isAnyTaggedError;\n/**\n* Wraps exceptions caught by Result.try/tryPromise.\n* Custom constructor derives message from cause.\n*/\nvar UnhandledException = class extends TaggedError(\"UnhandledException\")() {\n\tconstructor(args) {\n\t\tconst message = args.cause instanceof Error ? `Unhandled exception: ${args.cause.message}` : `Unhandled exception: ${String(args.cause)}`;\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tcause: args.cause\n\t\t});\n\t}\n};\n/**\n* Unrecoverable error — user code threw inside Result operations.\n*\n* @example\n* // Panic in generator cleanup:\n* Result.gen(function* () {\n* try {\n* yield* Result.err(\"expected error\");\n* } finally {\n* throw new Error(\"cleanup failed\"); // Panic!\n* }\n* });\n*\n* // Panic in combinator:\n* Result.ok(1).map(() => { throw new Error(\"oops\"); }); // Panic!\n*/\nvar Panic = class extends TaggedError(\"Panic\")() {};\n/**\n* Returned when Result.deserialize receives invalid input.\n*\n* @example\n* const result = Result.deserialize(invalidData);\n* if (Result.isError(result) && ResultDeserializationError.is(result.error)) {\n* console.log(\"Invalid input:\", result.error.value);\n* }\n*/\nvar ResultDeserializationError = class extends TaggedError(\"ResultDeserializationError\")() {\n\tconstructor(args) {\n\t\tsuper({\n\t\t\tmessage: `Failed to deserialize value as Result: expected { status: \"ok\", value } or { status: \"error\", error }`,\n\t\t\tvalue: args.value\n\t\t});\n\t}\n};\n/**\n* Type guard for Panic instances.\n*\n* @example\n* if (isPanic(value)) { value.cause }\n*/\nconst isPanic = (value) => {\n\treturn value instanceof Panic;\n};\n/**\n* Throw an unrecoverable Panic.\n*\n* @example\n* panic(\"something went wrong\", cause);\n*/\nconst panic = (message, cause) => {\n\tthrow new Panic({\n\t\tmessage,\n\t\tcause\n\t});\n};\n\n//#endregion\n//#region src/result.ts\n/** Executes fn, panics if it throws. */\nconst tryOrPanic = (fn, message) => {\n\ttry {\n\t\treturn fn();\n\t} catch (cause) {\n\t\tthrow panic(message, cause);\n\t}\n};\n/** Async version of tryOrPanic. */\nconst tryOrPanicAsync = async (fn, message) => {\n\ttry {\n\t\treturn await fn();\n\t} catch (cause) {\n\t\tthrow panic(message, cause);\n\t}\n};\n/**\n* Successful result variant.\n*\n* @template A Success value type.\n* @template E Error type (phantom - for type unification).\n*\n* @example\n* const result = new Ok(42);\n* result.value // 42\n* result.status // \"ok\"\n*/\nvar Ok = class Ok {\n\tstatus = \"ok\";\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n\t/** Returns true, narrowing Result to Ok. */\n\tisOk() {\n\t\treturn true;\n\t}\n\t/** Returns false, narrowing Result to Err. */\n\tisErr() {\n\t\treturn false;\n\t}\n\t/**\n\t* Transforms success value.\n\t*\n\t* @template B Transformed type.\n\t* @param fn Transformation function.\n\t* @returns Ok with transformed value.\n\t* @throws {Panic} If fn throws.\n\t*\n\t* @example\n\t* ok(2).map(x => x * 2) // Ok(4)\n\t*/\n\tmap(fn) {\n\t\treturn tryOrPanic(() => new Ok(fn(this.value)), \"map callback threw\");\n\t}\n\t/**\n\t* No-op on Ok, returns self with new phantom error type.\n\t*\n\t* @template E2 New error type.\n\t* @param _fn Ignored.\n\t* @returns Self with updated phantom E type.\n\t*/\n\tmapError(_fn) {\n\t\treturn this;\n\t}\n\t/**\n\t* Chains Result-returning function.\n\t*\n\t* @template B New success type.\n\t* @template E2 New error type.\n\t* @param fn Function returning Result.\n\t* @returns Result from fn.\n\t* @throws {Panic} If fn throws.\n\t*\n\t* @example\n\t* ok(2).andThen(x => x > 0 ? ok(x) : err(\"negative\")) // Ok(2)\n\t*/\n\tandThen(fn) {\n\t\treturn tryOrPanic(() => fn(this.value), \"andThen callback threw\");\n\t}\n\t/**\n\t* Chains async Result-returning function.\n\t*\n\t* @template B New success type.\n\t* @template E2 New error type.\n\t* @param fn Async function returning Result.\n\t* @returns Promise of Result from fn.\n\t* @throws {Panic} If fn throws synchronously or rejects.\n\t*\n\t* @example\n\t* await ok(1).andThenAsync(async x => ok(await fetchData(x)))\n\t*/\n\tandThenAsync(fn) {\n\t\treturn tryOrPanicAsync(() => fn(this.value), \"andThenAsync callback threw\");\n\t}\n\t/**\n\t* Pattern matches on Result.\n\t*\n\t* @template T Return type.\n\t* @param handlers Ok and err handlers.\n\t* @returns Result of ok handler.\n\t* @throws {Panic} If handler throws.\n\t*\n\t* @example\n\t* ok(2).match({ ok: x => x * 2, err: () => 0 }) // 4\n\t*/\n\tmatch(handlers) {\n\t\treturn tryOrPanic(() => handlers.ok(this.value), \"match ok handler threw\");\n\t}\n\t/**\n\t* Extracts value.\n\t*\n\t* @param _message Ignored.\n\t* @returns The value.\n\t*\n\t* @example\n\t* ok(42).unwrap() // 42\n\t*/\n\tunwrap(_message) {\n\t\treturn this.value;\n\t}\n\t/**\n\t* Returns value, ignoring fallback.\n\t*\n\t* @template B Fallback type.\n\t* @param _fallback Ignored.\n\t* @returns The value.\n\t*\n\t* @example\n\t* ok(42).unwrapOr(0) // 42\n\t*/\n\tunwrapOr(_fallback) {\n\t\treturn this.value;\n\t}\n\t/**\n\t* Runs side effect, returns self.\n\t*\n\t* @param fn Side effect function.\n\t* @returns Self.\n\t* @throws {Panic} If fn throws.\n\t*\n\t* @example\n\t* ok(2).tap(console.log).map(x => x * 2) // logs 2, returns Ok(4)\n\t*/\n\ttap(fn) {\n\t\treturn tryOrPanic(() => {\n\t\t\tfn(this.value);\n\t\t\treturn this;\n\t\t}, \"tap callback threw\");\n\t}\n\t/**\n\t* Runs async side effect, returns self.\n\t*\n\t* @param fn Async side effect function.\n\t* @returns Promise of self.\n\t* @throws {Panic} If fn throws synchronously or rejects.\n\t*\n\t* @example\n\t* await ok(2).tapAsync(async x => await log(x))\n\t*/\n\ttapAsync(fn) {\n\t\treturn tryOrPanicAsync(async () => {\n\t\t\tawait fn(this.value);\n\t\t\treturn this;\n\t\t}, \"tapAsync callback threw\");\n\t}\n\t/**\n\t* Makes Ok yieldable in Result.gen blocks.\n\t* Immediately returns the value without yielding.\n\t* Yield type Err<never, E> matches Err's for proper union inference.\n\t*/\n\t*[Symbol.iterator]() {\n\t\treturn this.value;\n\t}\n};\n/**\n* Error result variant.\n*\n* @template T Success type (phantom - for type unification with Ok).\n* @template E Error value type.\n*\n* @example\n* const result = new Err(\"failed\");\n* result.error // \"failed\"\n* result.status // \"error\"\n*/\nvar Err = class Err {\n\tstatus = \"error\";\n\tconstructor(error) {\n\t\tthis.error = error;\n\t}\n\t/** Returns false, narrowing Result to Ok. */\n\tisOk() {\n\t\treturn false;\n\t}\n\t/** Returns true, narrowing Result to Err. */\n\tisErr() {\n\t\treturn true;\n\t}\n\t/**\n\t* No-op on Err, returns self with new phantom T.\n\t*\n\t* @template U New phantom success type.\n\t* @param _fn Ignored.\n\t* @returns Self.\n\t*/\n\tmap(_fn) {\n\t\treturn this;\n\t}\n\t/**\n\t* Transforms error value.\n\t*\n\t* @template E2 Transformed error type.\n\t* @param fn Transformation function.\n\t* @returns Err with transformed error.\n\t* @throws {Panic} If fn throws.\n\t*\n\t* @example\n\t* err(\"fail\").mapError(e => new Error(e)) // Err(Error(\"fail\"))\n\t*/\n\tmapError(fn) {\n\t\treturn tryOrPanic(() => new Err(fn(this.error)), \"mapError callback threw\");\n\t}\n\t/**\n\t* No-op on Err, returns self with widened error type.\n\t*\n\t* @template U New phantom success type.\n\t* @template E2 Additional error type.\n\t* @param _fn Ignored.\n\t* @returns Self.\n\t*/\n\tandThen(_fn) {\n\t\treturn this;\n\t}\n\t/**\n\t* No-op on Err, returns Promise of self with widened error type.\n\t*\n\t* @template U New phantom success type.\n\t* @template E2 Additional error type.\n\t* @param _fn Ignored.\n\t* @returns Promise of self.\n\t*/\n\tandThenAsync(_fn) {\n\t\treturn Promise.resolve(this);\n\t}\n\t/**\n\t* Pattern matches on Result.\n\t*\n\t* @template R Return type.\n\t* @param handlers Ok and err handlers.\n\t* @returns Result of err handler.\n\t* @throws {Panic} If handler throws.\n\t*\n\t* @example\n\t* err(\"fail\").match({ ok: x => x, err: e => e.length }) // 4\n\t*/\n\tmatch(handlers) {\n\t\treturn tryOrPanic(() => handlers.err(this.error), \"match err handler threw\");\n\t}\n\t/**\n\t* Throws error with optional message.\n\t*\n\t* @param message Error message.\n\t* @throws Always throws.\n\t*\n\t* @example\n\t* err(\"fail\").unwrap() // throws Error\n\t* err(\"fail\").unwrap(\"custom\") // throws Error(\"custom\")\n\t*/\n\tunwrap(message) {\n\t\treturn panic(message ?? `Unwrap called on Err: ${String(this.error)}`, this.error);\n\t}\n\t/**\n\t* Returns fallback value.\n\t*\n\t* @template U Fallback type.\n\t* @param fallback Fallback value.\n\t* @returns Fallback.\n\t*\n\t* @example\n\t* err(\"fail\").unwrapOr(42) // 42\n\t*/\n\tunwrapOr(fallback) {\n\t\treturn fallback;\n\t}\n\t/**\n\t* No-op on Err, returns self.\n\t*\n\t* @param _fn Ignored.\n\t* @returns Self.\n\t*/\n\ttap(_fn) {\n\t\treturn this;\n\t}\n\t/**\n\t* No-op on Err, returns Promise of self.\n\t*\n\t* @param _fn Ignored.\n\t* @returns Promise of self.\n\t*/\n\ttapAsync(_fn) {\n\t\treturn Promise.resolve(this);\n\t}\n\t/**\n\t* Makes Err yieldable in Result.gen blocks.\n\t* Yields Err<never, E> for proper union inference across multiple yields.\n\t*/\n\t*[Symbol.iterator]() {\n\t\tyield this;\n\t\treturn panic(\"Unreachable: Err yielded in Result.gen but generator continued\", this.error);\n\t}\n};\nfunction ok(value) {\n\treturn new Ok(value);\n}\nconst isOk = (result) => {\n\treturn result.status === \"ok\";\n};\nconst err = (error) => new Err(error);\nconst isError = (result) => {\n\treturn result.status === \"error\";\n};\nconst tryFn = (options, config) => {\n\tconst execute = () => {\n\t\tif (typeof options === \"function\") try {\n\t\t\treturn ok(options());\n\t\t} catch (cause) {\n\t\t\treturn err(new UnhandledException({ cause }));\n\t\t}\n\t\ttry {\n\t\t\treturn ok(options.try());\n\t\t} catch (originalCause) {\n\t\t\ttry {\n\t\t\t\treturn err(options.catch(originalCause));\n\t\t\t} catch (catchHandlerError) {\n\t\t\t\tthrow panic(\"Result.try catch handler threw\", catchHandlerError);\n\t\t\t}\n\t\t}\n\t};\n\tconst times = config?.retry?.times ?? 0;\n\tlet result = execute();\n\tfor (let retry = 0; retry < times && result.status === \"error\"; retry++) result = execute();\n\treturn result;\n};\nconst tryPromise = async (options, config) => {\n\tconst execute = async () => {\n\t\tif (typeof options === \"function\") try {\n\t\t\treturn ok(await options());\n\t\t} catch (cause) {\n\t\t\treturn err(new UnhandledException({ cause }));\n\t\t}\n\t\ttry {\n\t\t\treturn ok(await options.try());\n\t\t} catch (originalCause) {\n\t\t\ttry {\n\t\t\t\treturn err(await options.catch(originalCause));\n\t\t\t} catch (catchHandlerError) {\n\t\t\t\tthrow panic(\"Result.tryPromise catch handler threw\", catchHandlerError);\n\t\t\t}\n\t\t}\n\t};\n\tconst retry = config?.retry;\n\tif (!retry) return execute();\n\tconst getDelay = (retryAttempt) => {\n\t\tswitch (retry.backoff) {\n\t\t\tcase \"constant\": return retry.delayMs;\n\t\t\tcase \"linear\": return retry.delayMs * (retryAttempt + 1);\n\t\t\tcase \"exponential\": return retry.delayMs * 2 ** retryAttempt;\n\t\t}\n\t};\n\tconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\tlet result = await execute();\n\tconst shouldRetryFn = retry.shouldRetry ?? (() => true);\n\tfor (let attempt = 0; attempt < retry.times; attempt++) {\n\t\tif (result.status !== \"error\") break;\n\t\tconst error = result.error;\n\t\tif (!tryOrPanic(() => shouldRetryFn(error), \"shouldRetry predicate threw\")) break;\n\t\tawait sleep(getDelay(attempt));\n\t\tresult = await execute();\n\t}\n\treturn result;\n};\nconst map = dual(2, (result, fn) => {\n\treturn result.map(fn);\n});\nconst mapError = dual(2, (result, fn) => {\n\treturn result.mapError(fn);\n});\nconst andThen = dual(2, (result, fn) => {\n\treturn result.andThen(fn);\n});\nconst andThenAsync = dual(2, (result, fn) => {\n\treturn result.andThenAsync(fn);\n});\nconst match = dual(2, (result, handlers) => {\n\treturn result.match(handlers);\n});\nconst tap = dual(2, (result, fn) => {\n\treturn result.tap(fn);\n});\nconst tapAsync = dual(2, (result, fn) => {\n\treturn result.tapAsync(fn);\n});\nconst unwrap = (result, message) => {\n\treturn result.unwrap(message);\n};\n/** Validates that a value is a Result instance. Throws with helpful message if not. */\nfunction assertIsResult(value) {\n\tif (value !== null && typeof value === \"object\" && \"status\" in value && (value.status === \"ok\" || value.status === \"error\")) return;\n\treturn panic(\"Result.gen body must return Result.ok() or Result.err(), got: \" + (value === null ? \"null\" : typeof value === \"object\" ? JSON.stringify(value) : String(value)));\n}\nconst unwrapOr = dual(2, (result, fallback) => {\n\treturn result.unwrapOr(fallback);\n});\nconst gen = ((body, thisArg) => {\n\tconst iterator = body.call(thisArg);\n\tif (Symbol.asyncIterator in iterator) return (async () => {\n\t\tconst asyncIter = iterator;\n\t\tlet state$1;\n\t\ttry {\n\t\t\tstate$1 = await asyncIter.next();\n\t\t} catch (cause) {\n\t\t\tthrow panic(\"generator body threw\", cause);\n\t\t}\n\t\tassertIsResult(state$1.value);\n\t\tif (!state$1.done) try {\n\t\t\tawait asyncIter.return?.(void 0);\n\t\t} catch (cause) {\n\t\t\tthrow panic(\"generator cleanup threw\", cause);\n\t\t}\n\t\treturn state$1.value;\n\t})();\n\tconst syncIter = iterator;\n\tlet state;\n\ttry {\n\t\tstate = syncIter.next();\n\t} catch (cause) {\n\t\tthrow panic(\"generator body threw\", cause);\n\t}\n\tassertIsResult(state.value);\n\tif (!state.done) try {\n\t\tsyncIter.return?.(void 0);\n\t} catch (cause) {\n\t\tthrow panic(\"generator cleanup threw\", cause);\n\t}\n\treturn state.value;\n});\nasync function* resultAwait(promise) {\n\treturn yield* await promise;\n}\nfunction isSerializedResult(obj) {\n\treturn obj !== null && typeof obj === \"object\" && \"status\" in obj && (obj.status === \"ok\" && \"value\" in obj || obj.status === \"error\" && \"error\" in obj);\n}\nconst serialize = (result) => {\n\treturn result.status === \"ok\" ? {\n\t\tstatus: \"ok\",\n\t\tvalue: result.value\n\t} : {\n\t\tstatus: \"error\",\n\t\terror: result.error\n\t};\n};\nconst deserialize = (value) => {\n\tif (isSerializedResult(value)) return value.status === \"ok\" ? new Ok(value.value) : new Err(value.error);\n\treturn err(new ResultDeserializationError({ value }));\n};\n/**\n* @deprecated Use `Result.deserialize` instead. Will be removed in 3.0.\n*/\nconst hydrate = (value) => {\n\treturn deserialize(value);\n};\nconst partition = (results) => {\n\tconst oks = [];\n\tconst errs = [];\n\tfor (const r of results) if (r.status === \"ok\") oks.push(r.value);\n\telse errs.push(r.error);\n\treturn [oks, errs];\n};\n/**\n* Flattens nested Result into single Result.\n*\n* @example\n* const nested: Result<Result<number, E1>, E2> = Result.ok(Result.ok(42));\n* const flat: Result<number, E1 | E2> = Result.flatten(nested); // Ok(42)\n*/\nconst flatten = (result) => {\n\tif (result.status === \"ok\") return result.value;\n\treturn result;\n};\n/**\n* Utilities for creating and handling Result types.\n*\n* @example\n* const result = Result.try(() => JSON.parse(str));\n* const value = result.map(x => x.id).unwrapOr(\"default\");\n*/\nconst Result = {\n\tok,\n\tisOk,\n\terr,\n\tisError,\n\ttry: tryFn,\n\ttryPromise,\n\tmap,\n\tmapError,\n\tandThen,\n\tandThenAsync,\n\tmatch,\n\ttap,\n\ttapAsync,\n\tunwrap,\n\tunwrapOr,\n\tgen,\n\tawait: resultAwait,\n\tserialize,\n\tdeserialize,\n\thydrate,\n\tpartition,\n\tflatten\n};\n\n//#endregion\nexport { Err, Ok, Panic, Result, ResultDeserializationError, TaggedError, UnhandledException, isPanic, isTaggedError, matchError, matchErrorPartial, panic };\n//# sourceMappingURL=index.mjs.map","import type { CliNextAction } from './types.js';\n\nimport {\n ERROR_CODE,\n type ErrorCode,\n isStaticErrorCode,\n type StaticErrorCode,\n} from './error-codes.js';\n\nexport type RecoveryOverride = Partial<CliNextAction>;\n\ninterface RecoveryTemplate {\n command: string;\n reason: string;\n title: string;\n when: string | null;\n}\n\nconst defaultRecoveryByCode: Record<StaticErrorCode, RecoveryTemplate> = {\n [ERROR_CODE.authDeviceExpired]: {\n command: 'ogment auth login',\n reason: 'Device code expired; restart login to continue.',\n title: 'Restart login',\n when: 'immediate',\n },\n [ERROR_CODE.authDevicePending]: {\n command: 'ogment auth status',\n reason:\n 'Authorization is pending; check whether credentials are now available.',\n title: 'Check auth status',\n when: 'immediate',\n },\n [ERROR_CODE.authInvalidCredentials]: {\n command: 'ogment auth logout',\n reason:\n 'Credentials are invalid; clear local state before re-authenticating.',\n title: 'Reset auth state',\n when: 'immediate',\n },\n [ERROR_CODE.authRequired]: {\n command: 'ogment auth login',\n reason:\n 'Authentication is required before catalog or invoke commands can run.',\n title: 'Authenticate',\n when: 'immediate',\n },\n [ERROR_CODE.contractVersionUnsupported]: {\n command: 'ogment --version',\n reason:\n 'Contract mismatch detected; verify CLI version and upgrade before retrying.',\n title: 'Inspect CLI version',\n when: 'immediate',\n },\n [ERROR_CODE.internalUnexpected]: {\n command: 'ogment status',\n reason:\n 'Unexpected failure detected; run diagnostics before retrying the workflow.',\n title: 'Inspect diagnostics',\n when: 'immediate',\n },\n [ERROR_CODE.remoteRateLimited]: {\n command: 'ogment status',\n reason: 'Remote rate limit detected; check diagnostics before retrying.',\n title: 'Inspect diagnostics',\n when: 'immediate',\n },\n [ERROR_CODE.remoteUnavailable]: {\n command: 'ogment status',\n reason:\n 'Remote service is unavailable; check connectivity and endpoint health.',\n title: 'Inspect diagnostics',\n when: 'immediate',\n },\n [ERROR_CODE.toolInputSchemaViolation]: {\n command: 'ogment catalog',\n reason:\n 'Tool contract did not validate; inspect available servers and tool metadata.',\n title: 'Inspect catalog',\n when: 'immediate',\n },\n [ERROR_CODE.toolNotFound]: {\n command: 'ogment catalog',\n reason: 'Requested tool could not be found; rediscover servers and tools.',\n title: 'Rediscover tools',\n when: 'immediate',\n },\n [ERROR_CODE.transportRequestFailed]: {\n command: 'ogment status',\n reason: 'Transport request failed; inspect connectivity diagnostics.',\n title: 'Inspect diagnostics',\n when: 'immediate',\n },\n [ERROR_CODE.validationInvalidInput]: {\n command: 'ogment --help',\n reason: 'Input validation failed; inspect canonical command syntax.',\n title: 'Show command help',\n when: 'immediate',\n },\n};\n\nconst dynamicRecoveryForCode = (\n code: ErrorCode,\n): RecoveryTemplate | undefined => {\n if (code.startsWith('HTTP_')) {\n return {\n command: 'ogment status',\n reason: `HTTP error ${code} detected; inspect diagnostics and remote connectivity.`,\n title: 'Inspect diagnostics',\n when: 'immediate',\n };\n }\n\n if (code.startsWith('MCP_')) {\n return {\n command: 'ogment status',\n reason: `MCP error ${code} detected; inspect diagnostics and remote server state.`,\n title: 'Inspect diagnostics',\n when: 'immediate',\n };\n }\n\n return undefined;\n};\n\nconst hasPlaceholderTokens = (command: string): boolean => {\n return command.includes('<') || command.includes('>');\n};\n\nconst sanitizedCommand = (command: string | undefined): string | undefined => {\n if (typeof command !== 'string') {\n return undefined;\n }\n\n if (hasPlaceholderTokens(command)) {\n return undefined;\n }\n\n return command;\n};\n\nexport const normalizeRecovery = (\n code: ErrorCode,\n override?: RecoveryOverride,\n): CliNextAction | undefined => {\n const fallback =\n (isStaticErrorCode(code) ? defaultRecoveryByCode[code] : undefined) ??\n dynamicRecoveryForCode(code);\n if (fallback === undefined) {\n return undefined;\n }\n const overrideCommand = sanitizedCommand(override?.command);\n const command = overrideCommand ?? fallback.command;\n const usesCustomCommand =\n overrideCommand !== undefined && overrideCommand !== fallback.command;\n\n return {\n command,\n id: override?.id ?? `recover_${code.toLowerCase()}`,\n reason:\n override?.reason ??\n (usesCustomCommand\n ? `Suggested recovery for error ${code}.`\n : fallback.reason),\n title:\n override?.title ??\n (usesCustomCommand ? 'Run suggested command' : fallback.title),\n when: override?.when ?? fallback.when,\n };\n};\n","import { TaggedError } from 'better-result';\n\nimport type {\n CliNextAction,\n RemoteErrorDiagnostics,\n RemoteErrorSource,\n} from './types.js';\n\nimport {\n ERROR_CATEGORY,\n ERROR_CODE,\n type ErrorCategory,\n type ErrorCode,\n} from './error-codes.js';\nimport { normalizeRecovery, type RecoveryOverride } from './recovery.js';\n\ntype AuthErrorCode =\n | typeof ERROR_CODE.authDeviceExpired\n | typeof ERROR_CODE.authDevicePending\n | typeof ERROR_CODE.authInvalidCredentials\n | typeof ERROR_CODE.authRequired;\n\ntype RemoteErrorCode =\n | typeof ERROR_CODE.remoteRateLimited\n | typeof ERROR_CODE.remoteUnavailable\n | typeof ERROR_CODE.transportRequestFailed\n | `HTTP_${number}`\n | `MCP_${number}`;\n\ntype ValidationErrorCode =\n | typeof ERROR_CODE.toolInputSchemaViolation\n | typeof ERROR_CODE.validationInvalidInput;\n\ntype ContractMismatchErrorCode = typeof ERROR_CODE.contractVersionUnsupported;\n\ninterface BaseAppErrorFields {\n category: ErrorCategory;\n code: ErrorCode;\n recovery: CliNextAction | undefined;\n retryable: boolean;\n}\n\nconst ValidationErrorBase = TaggedError('ValidationError')<{\n details?: string;\n message: string;\n}>();\n\ninterface ValidationErrorPayload {\n code?: ValidationErrorCode;\n details?: string;\n message: string;\n recovery?: RecoveryOverride;\n}\n\nexport class ValidationError\n extends ValidationErrorBase\n implements BaseAppErrorFields\n{\n readonly category = ERROR_CATEGORY.validation;\n readonly code: ValidationErrorCode;\n readonly recovery: CliNextAction | undefined;\n readonly retryable = false;\n\n public constructor(payload: ValidationErrorPayload) {\n super({\n message: payload.message,\n ...(payload.details === undefined ? {} : { details: payload.details }),\n });\n\n this.code = payload.code ?? ERROR_CODE.validationInvalidInput;\n this.recovery = normalizeRecovery(this.code, payload.recovery);\n }\n}\n\nconst AuthErrorBase = TaggedError('AuthError')<{\n details?: string;\n message: string;\n}>();\n\ninterface AuthErrorPayload {\n code?: AuthErrorCode;\n details?: string;\n message: string;\n recovery?: RecoveryOverride;\n retryable?: boolean;\n}\n\nexport class AuthError extends AuthErrorBase implements BaseAppErrorFields {\n readonly category = ERROR_CATEGORY.auth;\n readonly code: AuthErrorCode;\n readonly recovery: CliNextAction | undefined;\n readonly retryable: boolean;\n\n public constructor(payload: AuthErrorPayload) {\n super({\n message: payload.message,\n ...(payload.details === undefined ? {} : { details: payload.details }),\n });\n\n this.code = payload.code ?? ERROR_CODE.authRequired;\n this.recovery = normalizeRecovery(this.code, payload.recovery);\n this.retryable =\n payload.retryable ?? this.code === ERROR_CODE.authDeviceExpired;\n }\n}\n\nconst NotFoundErrorBase = TaggedError('NotFoundError')<{\n message: string;\n resource: string;\n}>();\n\ninterface NotFoundErrorPayload {\n code?: typeof ERROR_CODE.toolNotFound;\n message: string;\n recovery?: RecoveryOverride;\n resource: string;\n}\n\nexport class NotFoundError\n extends NotFoundErrorBase\n implements BaseAppErrorFields\n{\n readonly category = ERROR_CATEGORY.notFound;\n readonly code: typeof ERROR_CODE.toolNotFound;\n readonly recovery: CliNextAction | undefined;\n readonly retryable = false;\n\n public constructor(payload: NotFoundErrorPayload) {\n super({\n message: payload.message,\n resource: payload.resource,\n });\n\n this.code = payload.code ?? ERROR_CODE.toolNotFound;\n this.recovery = normalizeRecovery(this.code, payload.recovery);\n }\n}\n\nconst RemoteRequestErrorBase = TaggedError('RemoteRequestError')<{\n body?: string;\n message: string;\n mcpCode?: number;\n mcpData?: unknown;\n operation?: string;\n raw?: unknown;\n source: RemoteErrorSource;\n status?: number;\n}>();\n\ninterface RemoteRequestErrorPayload {\n body?: string;\n code?: RemoteErrorCode;\n diagnostics?: Partial<RemoteErrorDiagnostics>;\n httpStatus?: number;\n mcpCode?: number;\n mcpData?: unknown;\n message: string;\n operation?: string;\n raw?: unknown;\n recovery?: RecoveryOverride;\n retryable?: boolean;\n source?: RemoteErrorSource;\n status?: number;\n}\n\nconst parseHttpCode = (code: RemoteErrorCode): number | undefined => {\n if (!code.startsWith('HTTP_')) {\n return undefined;\n }\n\n const parsed = Number.parseInt(code.slice('HTTP_'.length), 10);\n if (!Number.isFinite(parsed)) {\n return undefined;\n }\n\n return parsed;\n};\n\nconst resolveRemoteErrorCode = (\n payload: RemoteRequestErrorPayload,\n diagnostics: RemoteErrorDiagnostics,\n): RemoteErrorCode => {\n if (payload.code !== undefined) {\n return payload.code;\n }\n\n if (typeof diagnostics.httpStatus === 'number') {\n return `HTTP_${diagnostics.httpStatus}`;\n }\n\n if (typeof diagnostics.mcpCode === 'number') {\n return `MCP_${diagnostics.mcpCode}`;\n }\n\n return ERROR_CODE.transportRequestFailed;\n};\n\nconst resolveRemoteDiagnostics = (\n payload: RemoteRequestErrorPayload,\n): RemoteErrorDiagnostics => {\n const source = payload.source ?? payload.diagnostics?.source ?? 'network';\n return {\n httpStatus:\n payload.httpStatus ?? payload.status ?? payload.diagnostics?.httpStatus,\n mcpCode: payload.mcpCode ?? payload.diagnostics?.mcpCode,\n mcpData: payload.mcpData ?? payload.diagnostics?.mcpData,\n operation: payload.operation ?? payload.diagnostics?.operation,\n raw: payload.raw ?? payload.diagnostics?.raw,\n source,\n };\n};\n\nconst resolveRetryableRemoteError = (\n diagnostics: RemoteErrorDiagnostics,\n code: RemoteErrorCode,\n): boolean => {\n const httpStatus = diagnostics.httpStatus ?? parseHttpCode(code);\n if (typeof httpStatus === 'number') {\n return httpStatus === 429 || httpStatus >= 500;\n }\n\n if (typeof diagnostics.mcpCode === 'number') {\n return diagnostics.mcpCode === -32_001;\n }\n\n return diagnostics.source === 'network';\n};\n\nconst resolveRemoteCategory = (\n code: RemoteErrorCode,\n diagnostics: RemoteErrorDiagnostics,\n): ErrorCategory => {\n const httpStatus = diagnostics.httpStatus ?? parseHttpCode(code);\n if (code === ERROR_CODE.remoteRateLimited || httpStatus === 429) {\n return ERROR_CATEGORY.rateLimit;\n }\n\n return ERROR_CATEGORY.remote;\n};\n\nexport class RemoteRequestError\n extends RemoteRequestErrorBase\n implements BaseAppErrorFields\n{\n readonly category: ErrorCategory;\n readonly code: RemoteErrorCode;\n readonly diagnostics: RemoteErrorDiagnostics;\n readonly httpStatus: number | undefined;\n readonly recovery: CliNextAction | undefined;\n readonly retryable: boolean;\n\n public constructor(payload: RemoteRequestErrorPayload) {\n const diagnostics = resolveRemoteDiagnostics(payload);\n const code = resolveRemoteErrorCode(payload, diagnostics);\n const status = diagnostics.httpStatus;\n super({\n message: payload.message,\n ...(payload.body === undefined ? {} : { body: payload.body }),\n ...(status === undefined ? {} : { status }),\n source: diagnostics.source,\n ...(diagnostics.mcpCode === undefined\n ? {}\n : { mcpCode: diagnostics.mcpCode }),\n ...(diagnostics.mcpData === undefined\n ? {}\n : { mcpData: diagnostics.mcpData }),\n ...(diagnostics.operation === undefined\n ? {}\n : { operation: diagnostics.operation }),\n ...(diagnostics.raw === undefined ? {} : { raw: diagnostics.raw }),\n });\n\n this.code = code;\n this.category = resolveRemoteCategory(code, diagnostics);\n this.diagnostics = diagnostics;\n this.httpStatus = diagnostics.httpStatus;\n this.recovery = normalizeRecovery(this.code, payload.recovery);\n this.retryable =\n payload.retryable ?? resolveRetryableRemoteError(diagnostics, code);\n }\n}\n\nconst ContractMismatchErrorBase = TaggedError('ContractMismatchError')<{\n details?: string;\n message: string;\n}>();\n\ninterface ContractMismatchErrorPayload {\n code?: ContractMismatchErrorCode;\n details?: string;\n message: string;\n recovery?: RecoveryOverride;\n}\n\nexport class ContractMismatchError\n extends ContractMismatchErrorBase\n implements BaseAppErrorFields\n{\n readonly category = ERROR_CATEGORY.contractMismatch;\n readonly code: ContractMismatchErrorCode;\n readonly recovery: CliNextAction | undefined;\n readonly retryable = false;\n\n public constructor(payload: ContractMismatchErrorPayload) {\n super({\n message: payload.message,\n ...(payload.details === undefined ? {} : { details: payload.details }),\n });\n\n this.code = payload.code ?? ERROR_CODE.contractVersionUnsupported;\n this.recovery = normalizeRecovery(this.code, payload.recovery);\n }\n}\n\nconst UnexpectedErrorBase = TaggedError('UnexpectedError')<{\n cause?: unknown;\n message: string;\n}>();\n\ninterface UnexpectedErrorPayload {\n cause?: unknown;\n code?: typeof ERROR_CODE.internalUnexpected;\n message: string;\n recovery?: RecoveryOverride;\n}\n\nexport class UnexpectedError\n extends UnexpectedErrorBase\n implements BaseAppErrorFields\n{\n readonly category = ERROR_CATEGORY.internal;\n readonly code: typeof ERROR_CODE.internalUnexpected;\n readonly recovery: CliNextAction | undefined;\n readonly retryable = false;\n\n public constructor(payload: UnexpectedErrorPayload) {\n super({\n message: payload.message,\n ...(payload.cause === undefined ? {} : { cause: payload.cause }),\n });\n\n this.code = payload.code ?? ERROR_CODE.internalUnexpected;\n this.recovery = normalizeRecovery(this.code, payload.recovery);\n }\n}\n\nexport type AppError =\n | AuthError\n | ContractMismatchError\n | NotFoundError\n | RemoteRequestError\n | UnexpectedError\n | ValidationError;\n\nexport interface AppErrorMeta {\n category: ErrorCategory;\n code: ErrorCode;\n recovery: CliNextAction | undefined;\n retryable: boolean;\n}\n\nconst withIfDefined = <T extends Record<string, unknown>>(\n base: T,\n key: string,\n value: unknown,\n): T & Record<string, unknown> => {\n if (value === undefined) {\n return base;\n }\n\n return {\n ...base,\n [key]: value,\n };\n};\n\nconst hasDetails = (error: AppError): error is AuthError | ValidationError => {\n return error._tag === 'AuthError' || error._tag === 'ValidationError';\n};\n\nexport const appErrorMeta = (error: AppError): AppErrorMeta => {\n return {\n category: error.category,\n code: error.code,\n recovery: error.recovery,\n retryable: error.retryable,\n };\n};\n\nexport const appErrorDiagnostics = (\n error: AppError,\n): Record<string, unknown> => {\n if (error._tag === 'RemoteRequestError') {\n let diagnostics: Record<string, unknown> = {\n source: error.source,\n };\n\n diagnostics = withIfDefined(diagnostics, 'httpStatus', error.httpStatus);\n diagnostics = withIfDefined(diagnostics, 'mcpCode', error.mcpCode);\n diagnostics = withIfDefined(diagnostics, 'mcpData', error.mcpData);\n diagnostics = withIfDefined(diagnostics, 'operation', error.operation);\n diagnostics = withIfDefined(diagnostics, 'raw', error.raw);\n diagnostics = withIfDefined(diagnostics, 'body', error.body);\n\n return diagnostics;\n }\n\n if (error._tag === 'NotFoundError') {\n return {\n resource: error.resource,\n };\n }\n\n if (error._tag === 'UnexpectedError') {\n if (error.cause === undefined) {\n return {};\n }\n return {\n cause: error.cause,\n };\n }\n\n if (\n hasDetails(error) &&\n typeof error.details === 'string' &&\n error.details.length > 0\n ) {\n return {\n details: error.details,\n };\n }\n\n return {};\n};\n\nexport const appErrorTitle = (error: AppError): string => {\n if (error._tag === 'UnexpectedError') {\n return 'Unexpected CLI error';\n }\n\n if (error._tag === 'ContractMismatchError') {\n return 'Contract version unsupported';\n }\n\n return error.message;\n};\n\nexport const formatAppError = (error: AppError): string => {\n if (error._tag === 'NotFoundError') {\n return `${error.message} (${error.resource})`;\n }\n\n if (\n error._tag === 'RemoteRequestError' &&\n typeof error.httpStatus === 'number'\n ) {\n return `${error.message} (status ${error.httpStatus})`;\n }\n\n if (\n hasDetails(error) &&\n typeof error.details === 'string' &&\n error.details.length > 0\n ) {\n return `${error.message}: ${error.details}`;\n }\n\n return error.message;\n};\n","import type { AppError } from './errors.js';\n\nimport { ERROR_CATEGORY, ERROR_CODE } from './error-codes.js';\nimport { appErrorMeta } from './errors.js';\n\nexport const EXIT_CODE = {\n authFailed: 4,\n authRequired: 3,\n contractMismatch: 8,\n internal: 9,\n notFound: 5,\n rateLimit: 6,\n remote: 7,\n success: 0,\n validation: 2,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODE)[keyof typeof EXIT_CODE];\n\nexport const exitCodeForError = (error: AppError): ExitCode => {\n const { category, code } = appErrorMeta(error);\n\n switch (category) {\n case ERROR_CATEGORY.auth: {\n if (code === ERROR_CODE.authRequired) {\n return EXIT_CODE.authRequired;\n }\n return EXIT_CODE.authFailed;\n }\n case ERROR_CATEGORY.notFound: {\n return EXIT_CODE.notFound;\n }\n case ERROR_CATEGORY.rateLimit: {\n return EXIT_CODE.rateLimit;\n }\n case ERROR_CATEGORY.remote:\n case ERROR_CATEGORY.transport:\n case ERROR_CATEGORY.authorization: {\n return EXIT_CODE.remote;\n }\n case ERROR_CATEGORY.contractMismatch: {\n return EXIT_CODE.contractMismatch;\n }\n case ERROR_CATEGORY.validation: {\n return EXIT_CODE.validation;\n }\n case ERROR_CATEGORY.internal: {\n return EXIT_CODE.internal;\n }\n }\n};\n","import type { Result as ResultType } from 'better-result';\n\nimport type {\n LoginPendingInfo,\n LoginOptions,\n LoginError,\n} from '../services/auth.js';\nimport type { UnexpectedError } from '../shared/errors.js';\nimport type {\n AuthStatusSuccess,\n LoginSuccess,\n LogoutSuccess,\n} from '../shared/types.js';\nimport type { CommandContext } from './context.js';\n\ninterface DeviceAuthLoginCommandOptions {\n mode: 'device';\n onPending?: (info: LoginPendingInfo) => void;\n}\n\ninterface ApiKeyAuthLoginCommandOptions {\n apiKey: string;\n mode: 'apiKey';\n}\n\nexport type AuthLoginCommandOptions =\n | ApiKeyAuthLoginCommandOptions\n | DeviceAuthLoginCommandOptions;\n\nexport const runAuthLoginCommand = async (\n context: CommandContext,\n options: AuthLoginCommandOptions,\n): Promise<ResultType<LoginSuccess, LoginError>> => {\n const loginOptions: LoginOptions = (() => {\n if (options.mode === 'apiKey') {\n return {\n apiKey: options.apiKey,\n mode: 'apiKey',\n };\n }\n\n return {\n mode: 'device',\n ...(options.onPending === undefined\n ? {}\n : { onPending: options.onPending }),\n };\n })();\n\n return context.services.auth.login(loginOptions);\n};\n\nexport const runAuthStatusCommand = async (\n context: CommandContext,\n): Promise<ResultType<AuthStatusSuccess, UnexpectedError>> => {\n return context.services.auth.status(context.apiKeyOverride);\n};\n\nexport const runAuthLogoutCommand = async (\n context: CommandContext,\n): Promise<ResultType<LogoutSuccess, UnexpectedError>> => {\n return context.services.auth.logout();\n};\n","import { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\nimport type { ZodTypeAny, output } from 'zod';\n\nimport type { RecoveryOverride } from './recovery.js';\n\nimport { ValidationError } from './errors.js';\n\nconst formatIssues = (\n issues: readonly { path: PropertyKey[]; message: string }[],\n): string => {\n return issues\n .map((issue) => {\n if (issue.path.length === 0) {\n return issue.message;\n }\n\n const path = issue.path\n .filter(\n (value): value is number | string =>\n typeof value === 'number' || typeof value === 'string',\n )\n .join('.');\n return `${path}: ${issue.message}`;\n })\n .join('; ');\n};\n\nexport const parseWithSchema = <TSchema extends ZodTypeAny>(\n schema: TSchema,\n payload: unknown,\n context: string,\n options: {\n code?: ValidationError['code'];\n recovery?: RecoveryOverride;\n } = {},\n): ResultType<output<TSchema>, ValidationError> => {\n const parsed = schema.safeParse(payload);\n\n if (!parsed.success) {\n return Result.err(\n new ValidationError({\n details: formatIssues(parsed.error.issues),\n message: `Invalid ${context}`,\n ...(options.code === undefined ? {} : { code: options.code }),\n ...(options.recovery === undefined\n ? {}\n : { recovery: options.recovery }),\n }),\n );\n }\n\n return Result.ok(parsed.data);\n};\n\nexport const parseJsonUnknown = (\n raw: string,\n context: string,\n): ResultType<unknown, ValidationError> => {\n return Result.try({\n catch: () =>\n new ValidationError({\n details: raw,\n message: `Invalid JSON in ${context}`,\n }),\n try: () => {\n const parsed: unknown = JSON.parse(raw);\n return parsed;\n },\n });\n};\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null;\n};\n\nexport const isPlainObject = (\n value: unknown,\n): value is Record<string, unknown> => {\n return isRecord(value) && !Array.isArray(value);\n};\n","import type { CliRuntimeErrorPayload } from './types.js';\n\nimport {\n appErrorDiagnostics,\n appErrorMeta,\n appErrorTitle,\n formatAppError,\n type AppError,\n type RemoteRequestError,\n} from './errors.js';\nimport { isRecord } from './guards.js';\n\ninterface PresentAppErrorOptions {\n contextDiagnostics?: Record<string, unknown>;\n includeDebug: boolean;\n}\n\nconst toHttpCode = (status: number): `HTTP_${number}` => {\n return `HTTP_${status}`;\n};\n\nconst toMcpCode = (code: number): `MCP_${number}` => {\n return `MCP_${code}`;\n};\n\nconst sanitizeRemoteMessage = (value: string): string | undefined => {\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n return undefined;\n }\n\n if (/^[\\w]+Error$/u.test(trimmed)) {\n return undefined;\n }\n\n const normalized = trimmed.replace(/^[\\w]+Error:\\s*/u, '').trim();\n return normalized.length > 0 ? normalized : undefined;\n};\n\nconst extractMessageFromRecord = (\n record: Record<string, unknown>,\n): string | undefined => {\n if (typeof record['message'] === 'string') {\n return sanitizeRemoteMessage(record['message']);\n }\n\n const nested = record['error'];\n if (isRecord(nested) && typeof nested['message'] === 'string') {\n return sanitizeRemoteMessage(nested['message']);\n }\n\n return undefined;\n};\n\nconst extractMessageFromBody = (\n body: string | undefined,\n): string | undefined => {\n if (typeof body !== 'string' || body.length === 0) {\n return undefined;\n }\n\n const parsed = (() => {\n try {\n const value: unknown = JSON.parse(body);\n return value;\n } catch {\n return null;\n }\n })();\n\n if (isRecord(parsed)) {\n const fromParsed = extractMessageFromRecord(parsed);\n if (fromParsed !== undefined) {\n return fromParsed;\n }\n }\n\n return sanitizeRemoteMessage(body);\n};\n\nconst extractRemoteUserMessage = (\n error: RemoteRequestError,\n): string | undefined => {\n if (error.source !== 'mcp_transport_http' && error.source !== 'mcp_jsonrpc') {\n return undefined;\n }\n\n if (isRecord(error.raw)) {\n const fromRaw = extractMessageFromRecord(error.raw);\n if (fromRaw !== undefined) {\n return fromRaw;\n }\n }\n\n const fromBody = extractMessageFromBody(error.body);\n if (fromBody !== undefined) {\n return fromBody;\n }\n\n if (typeof error.mcpData === 'string') {\n const fromData = sanitizeRemoteMessage(error.mcpData);\n if (fromData !== undefined) {\n return fromData;\n }\n }\n\n return undefined;\n};\n\nconst resolvePrimaryCode = (error: AppError): string => {\n const meta = appErrorMeta(error);\n if (error._tag === 'RemoteRequestError') {\n if (typeof error.httpStatus === 'number') {\n return toHttpCode(error.httpStatus);\n }\n\n if (typeof error.mcpCode === 'number') {\n return toMcpCode(error.mcpCode);\n }\n }\n\n return String(meta.code);\n};\n\nconst resolveRelatedCodes = (\n error: AppError,\n primaryCode: string,\n): string[] | undefined => {\n if (error._tag !== 'RemoteRequestError') {\n return undefined;\n }\n\n const relatedCodes = [\n ...(typeof error.httpStatus === 'number'\n ? [toHttpCode(error.httpStatus)]\n : []),\n ...(typeof error.mcpCode === 'number' ? [toMcpCode(error.mcpCode)] : []),\n ].filter((code, index, array) => {\n return code !== primaryCode && array.indexOf(code) === index;\n });\n\n return relatedCodes.length > 0 ? relatedCodes : undefined;\n};\n\nconst defaultDiagnostics = (error: AppError): Record<string, unknown> => {\n if (error._tag !== 'RemoteRequestError') {\n return {};\n }\n\n return {\n source: error.source,\n ...(error.operation === undefined ? {} : { operation: error.operation }),\n };\n};\n\nconst resolveDetail = (error: AppError): string => {\n if (error._tag === 'RemoteRequestError') {\n const userMessage = extractRemoteUserMessage(error);\n if (userMessage !== undefined) {\n return userMessage;\n }\n }\n\n return formatAppError(error);\n};\n\nexport const presentRuntimeErrorPayload = (\n error: AppError,\n options: PresentAppErrorOptions,\n): CliRuntimeErrorPayload => {\n const meta = appErrorMeta(error);\n const primaryCode = resolvePrimaryCode(error);\n const relatedCodes = resolveRelatedCodes(error, primaryCode);\n const diagnostics: Record<string, unknown> = options.includeDebug\n ? {\n tag: error._tag,\n ...appErrorDiagnostics(error),\n }\n : {\n ...defaultDiagnostics(error),\n };\n\n if (options.contextDiagnostics !== undefined) {\n Object.assign(diagnostics, options.contextDiagnostics);\n }\n\n return {\n category: meta.category,\n code: primaryCode,\n detail: resolveDetail(error),\n diagnostics,\n ...(relatedCodes === undefined ? {} : { related_codes: relatedCodes }),\n retryable: meta.retryable,\n title: appErrorTitle(error),\n };\n};\n\nexport const presentCatalogFailureError = (\n error: AppError,\n options: PresentAppErrorOptions,\n): {\n code: string;\n detail: string;\n diagnostics: Record<string, unknown>;\n related_codes?: string[];\n retryable: boolean;\n title: string;\n} => {\n const payload = presentRuntimeErrorPayload(error, options);\n return {\n code: payload.code,\n detail: payload.detail,\n diagnostics: payload.diagnostics,\n ...(payload.related_codes === undefined\n ? {}\n : { related_codes: payload.related_codes }),\n retryable: payload.retryable,\n title: payload.title,\n };\n};\n","import { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type { FetchAccountError } from '../services/account.js';\nimport type { ResolveApiKeyError } from '../services/auth.js';\nimport type { ServerWithOrg } from '../shared/types.js';\nimport type { CommandContext } from './context.js';\n\nimport { NotFoundError } from '../shared/errors.js';\n\nexport interface ResolvedServerState {\n apiKey: string;\n servers: ServerWithOrg[];\n}\n\nexport type ResolveServerStateError = FetchAccountError | ResolveApiKeyError;\n\nexport const resolveServerState = async (\n context: CommandContext,\n): Promise<ResultType<ResolvedServerState, ResolveServerStateError>> => {\n const apiKeyResult = await context.services.auth.resolveApiKey(\n context.apiKeyOverride,\n );\n if (Result.isError(apiKeyResult)) {\n return apiKeyResult;\n }\n\n const serversResult = await context.services.account.listServers(\n apiKeyResult.value,\n );\n if (Result.isError(serversResult)) {\n return serversResult;\n }\n\n return Result.ok({\n apiKey: apiKeyResult.value,\n servers: serversResult.value,\n });\n};\n\nexport const findServerByPath = (\n servers: readonly ServerWithOrg[],\n path: string,\n): ResultType<ServerWithOrg, NotFoundError> => {\n const server = servers.find((item) => item.path === path);\n\n if (server === undefined) {\n return Result.err(\n new NotFoundError({\n message: `Server \"${path}\" not found`,\n resource: path,\n }),\n );\n }\n\n return Result.ok(server);\n};\n","import { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type { McpServiceError } from '../services/mcp.js';\nimport type {\n CatalogServerFailure,\n CatalogServerSummary,\n CatalogSummarySuccess,\n CatalogToolDetailsSuccess,\n CatalogToolsSuccess,\n McpToolSummary,\n} from '../shared/types.js';\nimport type { CommandContext } from './context.js';\n\nimport { ERROR_CODE } from '../shared/error-codes.js';\nimport { presentCatalogFailureError } from '../shared/error-presentation.js';\nimport { NotFoundError, ValidationError } from '../shared/errors.js';\nimport {\n findServerByPath,\n resolveServerState,\n type ResolveServerStateError,\n} from './server-context.js';\n\nconst toServerSummary = (\n server: {\n description: string | null;\n name: string;\n orgSlug: string;\n path: string;\n },\n toolCount: number,\n): CatalogServerSummary => {\n return {\n capabilities: [],\n description: server.description,\n name: server.name,\n orgSlug: server.orgSlug,\n serverId: server.path,\n toolCount,\n version: null,\n };\n};\n\nconst toToolSummaries = (\n tools: readonly McpToolSummary[],\n): CatalogToolsSuccess['tools'] => {\n return tools.map((tool) => {\n return {\n description: tool.description,\n name: tool.name,\n };\n });\n};\n\nexport interface CatalogCommandOptions {\n cursor?: string | undefined;\n includeDebug?: boolean | undefined;\n limit?: number | undefined;\n serverId?: string | undefined;\n}\n\nexport interface CatalogToolsCommandOptions {\n serverId: string;\n}\n\nexport interface CatalogToolDetailsCommandOptions {\n serverId: string;\n toolName: string;\n}\n\nexport interface CatalogSummaryPage {\n failures: CatalogServerFailure[];\n nextCursor: string | null;\n servers: CatalogSummarySuccess['servers'];\n}\n\nexport type CatalogCommandError =\n | McpServiceError\n | NotFoundError\n | ResolveServerStateError\n | ValidationError;\n\nexport type CatalogToolsCommandError =\n | McpServiceError\n | NotFoundError\n | ResolveServerStateError;\n\nexport type CatalogToolDetailsCommandError =\n | McpServiceError\n | NotFoundError\n | ResolveServerStateError;\n\nconst listServerTools = async (\n context: CommandContext,\n apiKey: string,\n server: { orgSlug: string; path: string },\n): Promise<ResultType<McpToolSummary[], McpServiceError>> => {\n return context.services.mcp.listTools(\n {\n orgSlug: server.orgSlug,\n serverPath: server.path,\n },\n apiKey,\n );\n};\n\nconst TOOL_COUNT_CONCURRENCY = 4;\n\nconst toCatalogServerFailure = (\n server: { orgSlug: string; path: string },\n error: McpServiceError,\n includeDebug: boolean,\n): CatalogServerFailure => {\n return {\n error: presentCatalogFailureError(error, {\n includeDebug,\n }),\n orgSlug: server.orgSlug,\n serverId: server.path,\n };\n};\n\nconst mapWithConcurrency = async <TInput, TOutput>(\n items: readonly TInput[],\n concurrency: number,\n mapItem: (item: TInput, index: number) => Promise<TOutput>,\n): Promise<TOutput[]> => {\n if (items.length === 0) {\n return [];\n }\n\n const results: TOutput[] = [];\n results.length = items.length;\n let nextIndex = 0;\n\n const worker = async () => {\n while (true) {\n const currentIndex = nextIndex;\n nextIndex += 1;\n\n if (currentIndex >= items.length) {\n return;\n }\n\n const item = items[currentIndex];\n if (item === undefined) {\n return;\n }\n\n results[currentIndex] = await mapItem(item, currentIndex);\n }\n };\n\n const workerCount = Math.min(concurrency, items.length);\n await Promise.all(Array.from({ length: workerCount }, async () => worker()));\n\n return results;\n};\n\nexport const runCatalogCommand = async (\n context: CommandContext,\n options: CatalogCommandOptions,\n): Promise<ResultType<CatalogSummaryPage, CatalogCommandError>> => {\n const stateResult = await resolveServerState(context);\n if (Result.isError(stateResult)) {\n return stateResult;\n }\n\n let targetServers = stateResult.value.servers;\n if (options.serverId !== undefined) {\n const serverResult = findServerByPath(\n stateResult.value.servers,\n options.serverId,\n );\n if (Result.isError(serverResult)) {\n return serverResult;\n }\n\n targetServers = [serverResult.value];\n }\n\n const serverSummaries = await mapWithConcurrency(\n targetServers,\n TOOL_COUNT_CONCURRENCY,\n async (server) => {\n const toolsResult = await listServerTools(\n context,\n stateResult.value.apiKey,\n server,\n );\n return {\n server,\n toolsResult,\n };\n },\n );\n\n const summaries: CatalogServerSummary[] = [];\n const failures: CatalogServerFailure[] = [];\n for (const serverSummary of serverSummaries) {\n if (Result.isError(serverSummary.toolsResult)) {\n if (options.serverId !== undefined) {\n return serverSummary.toolsResult;\n }\n\n failures.push(\n toCatalogServerFailure(\n serverSummary.server,\n serverSummary.toolsResult.error,\n options.includeDebug === true,\n ),\n );\n continue;\n }\n\n summaries.push(\n toServerSummary(\n serverSummary.server,\n serverSummary.toolsResult.value.length,\n ),\n );\n }\n\n if (options.serverId !== undefined) {\n return Result.ok({\n failures: [],\n nextCursor: null,\n servers: summaries,\n });\n }\n\n const limit = Math.max(1, options.limit ?? 20);\n let startIndex = 0;\n\n if (options.cursor !== undefined) {\n const cursorIndex = summaries.findIndex(\n (server) => server.serverId === options.cursor,\n );\n if (cursorIndex === -1) {\n return Result.err(\n new ValidationError({\n code: ERROR_CODE.validationInvalidInput,\n message: `Invalid --cursor value: \"${options.cursor}\"`,\n recovery: { command: 'ogment catalog' },\n }),\n );\n }\n startIndex = cursorIndex + 1;\n }\n\n const servers = summaries.slice(startIndex, startIndex + limit);\n const hasMore = startIndex + limit < summaries.length;\n const nextCursor = hasMore ? (servers.at(-1)?.serverId ?? null) : null;\n\n return Result.ok({\n failures,\n nextCursor,\n servers,\n });\n};\n\nexport const runCatalogToolsCommand = async (\n context: CommandContext,\n options: CatalogToolsCommandOptions,\n): Promise<ResultType<CatalogToolsSuccess, CatalogToolsCommandError>> => {\n const stateResult = await resolveServerState(context);\n if (Result.isError(stateResult)) {\n return stateResult;\n }\n\n const serverResult = findServerByPath(\n stateResult.value.servers,\n options.serverId,\n );\n if (Result.isError(serverResult)) {\n return serverResult;\n }\n\n const toolsResult = await listServerTools(\n context,\n stateResult.value.apiKey,\n serverResult.value,\n );\n if (Result.isError(toolsResult)) {\n return toolsResult;\n }\n\n return Result.ok({\n server: toServerSummary(serverResult.value, toolsResult.value.length),\n tools: toToolSummaries(toolsResult.value),\n });\n};\n\nexport const runCatalogToolDetailsCommand = async (\n context: CommandContext,\n options: CatalogToolDetailsCommandOptions,\n): Promise<\n ResultType<CatalogToolDetailsSuccess, CatalogToolDetailsCommandError>\n> => {\n const stateResult = await resolveServerState(context);\n if (Result.isError(stateResult)) {\n return stateResult;\n }\n\n const serverResult = findServerByPath(\n stateResult.value.servers,\n options.serverId,\n );\n if (Result.isError(serverResult)) {\n return serverResult;\n }\n\n const toolsResult = await listServerTools(\n context,\n stateResult.value.apiKey,\n serverResult.value,\n );\n if (Result.isError(toolsResult)) {\n return toolsResult;\n }\n\n const tool = toolsResult.value.find((item) => item.name === options.toolName);\n if (tool === undefined) {\n return Result.err(\n new NotFoundError({\n message: `Tool \"${options.toolName}\" not found`,\n resource: options.toolName,\n }),\n );\n }\n\n return Result.ok({\n description: tool.description,\n inputSchema: tool.inputSchema,\n name: tool.name,\n outputSchema: tool.outputSchema ?? null,\n server: toServerSummary(serverResult.value, toolsResult.value.length),\n });\n};\n","import { readFile } from 'node:fs/promises';\n\nimport { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type { McpServiceError } from '../services/mcp.js';\nimport type { InvokeSuccess } from '../shared/types.js';\nimport type { CommandContext } from './context.js';\n\nimport {\n NotFoundError,\n RemoteRequestError,\n UnexpectedError,\n ValidationError,\n} from '../shared/errors.js';\nimport { isPlainObject, isRecord, parseJsonUnknown } from '../shared/guards.js';\nimport {\n findServerByPath,\n resolveServerState,\n type ResolveServerStateError,\n} from './server-context.js';\n\nexport interface InvokeCommandOptions {\n input: string | undefined;\n target: string;\n}\n\ninterface InvokeCommandDeps {\n readStdin?: () => Promise<ResultType<string, UnexpectedError>>;\n}\n\nexport type InvokeCommandError =\n | McpServiceError\n | NotFoundError\n | ResolveServerStateError\n | UnexpectedError\n | ValidationError;\n\ninterface ParsedTarget {\n serverId: string;\n toolName: string;\n}\n\nconst mapInputFileReadError = (\n inputFile: string,\n cause: unknown,\n): UnexpectedError | ValidationError => {\n const code =\n isRecord(cause) && typeof cause['code'] === 'string'\n ? cause['code']\n : undefined;\n\n if (code === 'ENOENT') {\n return new ValidationError({\n message: `Input file not found: ${inputFile}`,\n });\n }\n\n if (code === 'EACCES' || code === 'EPERM') {\n return new ValidationError({\n message: `Input file is not readable: ${inputFile}`,\n });\n }\n\n if (code === 'EISDIR') {\n return new ValidationError({\n message: `Input path must be a file: ${inputFile}`,\n });\n }\n\n return new UnexpectedError({\n cause,\n message: `Failed to read input file: ${inputFile}`,\n });\n};\n\nconst parseToolErrorDetails = (\n payload: unknown,\n): {\n mcpCode?: number;\n mcpData?: unknown;\n message?: string;\n} => {\n if (typeof payload === 'string') {\n const trimmed = payload.trim();\n if (trimmed.length === 0) {\n return {};\n }\n\n const parseJsonDetails = (\n raw: string,\n ):\n | {\n mcpCode?: number;\n mcpData?: unknown;\n message?: string;\n }\n | undefined => {\n const parsed = parseJsonUnknown(raw, 'tool error payload');\n if (Result.isError(parsed)) {\n return undefined;\n }\n\n const details = parseToolErrorDetails(parsed.value);\n if (\n details.message !== undefined ||\n details.mcpCode !== undefined ||\n details.mcpData !== undefined\n ) {\n return details;\n }\n\n return undefined;\n };\n\n const fromFullJson = parseJsonDetails(trimmed);\n if (fromFullJson !== undefined) {\n return fromFullJson;\n }\n\n const firstBraceIndex = trimmed.indexOf('{');\n if (firstBraceIndex > 0) {\n const fromEmbeddedJson = parseJsonDetails(trimmed.slice(firstBraceIndex));\n if (fromEmbeddedJson !== undefined) {\n return fromEmbeddedJson;\n }\n }\n\n return {\n message: trimmed,\n };\n }\n\n if (typeof payload !== 'object' || payload === null) {\n return {};\n }\n\n if (!isRecord(payload)) {\n return {};\n }\n\n const record = payload;\n const directCode = record['code'];\n const directMessage = record['message'];\n if (typeof directCode === 'number' || typeof directMessage === 'string') {\n return {\n ...(typeof directCode === 'number' ? { mcpCode: directCode } : {}),\n ...(typeof directMessage === 'string' ? { message: directMessage } : {}),\n ...(Object.hasOwn(record, 'data') ? { mcpData: record['data'] } : {}),\n };\n }\n\n const nestedError = record['error'];\n if (!isRecord(nestedError)) {\n return {};\n }\n\n const nestedRecord = nestedError;\n return {\n ...(typeof nestedRecord['code'] === 'number'\n ? { mcpCode: nestedRecord['code'] }\n : {}),\n ...(typeof nestedRecord['message'] === 'string'\n ? { message: nestedRecord['message'] }\n : {}),\n ...(Object.hasOwn(nestedRecord, 'data')\n ? { mcpData: nestedRecord['data'] }\n : {}),\n };\n};\n\nconst parseTarget = (\n target: string,\n): ResultType<ParsedTarget, ValidationError> => {\n const separatorIndex = target.lastIndexOf('/');\n\n if (separatorIndex <= 0 || separatorIndex >= target.length - 1) {\n return Result.err(\n new ValidationError({\n details: target,\n message: 'Invoke target must be in format <server-id>/<tool-name>',\n }),\n );\n }\n\n const serverId = target.slice(0, separatorIndex);\n const toolName = target.slice(separatorIndex + 1);\n\n return Result.ok({\n serverId,\n toolName,\n });\n};\n\nconst parseInputObject = (\n raw: string,\n context: string,\n): ResultType<Record<string, unknown>, ValidationError> => {\n const parsed = parseJsonUnknown(raw, context);\n\n if (Result.isError(parsed)) {\n return parsed;\n }\n\n if (!isPlainObject(parsed.value)) {\n return Result.err(\n new ValidationError({\n message: 'Invoke input must be a JSON object',\n }),\n );\n }\n\n return Result.ok(parsed.value);\n};\n\nconst readStdin = async (): Promise<ResultType<string, UnexpectedError>> => {\n return Result.tryPromise({\n catch: (cause) =>\n new UnexpectedError({\n cause,\n message: 'Failed to read stdin',\n }),\n try: async () => {\n return new Promise<string>((resolve, reject) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk: Buffer | string) => {\n data += chunk.toString();\n });\n process.stdin.on('end', () => {\n resolve(data);\n });\n process.stdin.on('error', (error) => {\n reject(error);\n });\n });\n },\n });\n};\n\nconst parseInvokeArgs = async (\n options: Pick<InvokeCommandOptions, 'input'>,\n deps: InvokeCommandDeps,\n): Promise<\n ResultType<Record<string, unknown>, UnexpectedError | ValidationError>\n> => {\n if (options.input === undefined) {\n return Result.ok({});\n }\n\n if (options.input === '-') {\n const stdinResult = await (deps.readStdin ?? readStdin)();\n if (Result.isError(stdinResult)) {\n return stdinResult;\n }\n\n return parseInputObject(stdinResult.value, '--input (-)');\n }\n\n if (options.input.startsWith('@')) {\n const inputFile = options.input.slice(1);\n if (inputFile.length === 0) {\n return Result.err(\n new ValidationError({\n details: options.input,\n message:\n 'Invalid --input value. Use @<path>, -, or an inline JSON object.',\n }),\n );\n }\n\n const fileReadResult = await Result.tryPromise({\n catch: (cause) => mapInputFileReadError(inputFile, cause),\n try: async () => readFile(inputFile, 'utf8'),\n });\n\n if (Result.isError(fileReadResult)) {\n return fileReadResult;\n }\n\n return parseInputObject(fileReadResult.value, '--input (@file)');\n }\n\n return parseInputObject(options.input, '--input');\n};\n\nexport const runInvokeCommand = async (\n context: CommandContext,\n options: InvokeCommandOptions,\n deps: InvokeCommandDeps = {},\n): Promise<ResultType<InvokeSuccess, InvokeCommandError>> => {\n const targetResult = parseTarget(options.target);\n if (Result.isError(targetResult)) {\n return targetResult;\n }\n\n const argsResult = await parseInvokeArgs(options, deps);\n if (Result.isError(argsResult)) {\n return argsResult;\n }\n\n const stateResult = await resolveServerState(context);\n if (Result.isError(stateResult)) {\n return stateResult;\n }\n\n const serverResult = findServerByPath(\n stateResult.value.servers,\n targetResult.value.serverId,\n );\n if (Result.isError(serverResult)) {\n return serverResult;\n }\n\n const mcpTarget = {\n orgSlug: serverResult.value.orgSlug,\n serverPath: serverResult.value.path,\n };\n\n const callResult = await context.services.mcp.callTool(\n mcpTarget,\n stateResult.value.apiKey,\n targetResult.value.toolName,\n argsResult.value,\n );\n\n if (Result.isError(callResult)) {\n if (callResult.error._tag === 'RemoteRequestError') {\n const toolsResult = await context.services.mcp.listTools(\n mcpTarget,\n stateResult.value.apiKey,\n );\n if (Result.isOk(toolsResult)) {\n const toolExists = toolsResult.value.some(\n (tool) => tool.name === targetResult.value.toolName,\n );\n if (!toolExists) {\n return Result.err(\n new NotFoundError({\n message: `Tool \"${targetResult.value.toolName}\" not found`,\n resource: targetResult.value.toolName,\n }),\n );\n }\n }\n }\n\n return callResult;\n }\n\n if (callResult.value.isError) {\n const details = parseToolErrorDetails(callResult.value.structuredContent);\n return Result.err(\n new RemoteRequestError({\n ...(details.mcpCode === undefined ? {} : { mcpCode: details.mcpCode }),\n ...(details.mcpData === undefined ? {} : { mcpData: details.mcpData }),\n message: details.message ?? 'MCP tool call returned an error result',\n operation: 'tools/call',\n raw: callResult.value.structuredContent,\n retryable: false,\n source: 'mcp_jsonrpc',\n }),\n );\n }\n\n return Result.ok({\n result: callResult.value.structuredContent,\n serverId: targetResult.value.serverId,\n toolName: targetResult.value.toolName,\n });\n};\n","import { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type { InfoService } from '../services/info.js';\nimport type { InfoPayload } from '../shared/types.js';\n\nexport interface StatusCommandOptions {\n apiKeyOverride: string | undefined;\n}\n\ninterface RunStatusCommandDeps {\n infoService: InfoService;\n}\n\nexport const runStatusCommand = async (\n options: StatusCommandOptions,\n deps: RunStatusCommandDeps,\n): Promise<ResultType<InfoPayload, never>> => {\n const payload = await deps.infoService.collect(options.apiKeyOverride);\n return Result.ok(payload);\n};\n","const MAX_EXAMPLE_DEPTH = 6;\nexport const EXAMPLE_PLACEHOLDER = ' ... ';\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\nconst asStringArray = (value: unknown): string[] => {\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.filter((item): item is string => typeof item === 'string');\n};\n\nconst firstKnown = (value: unknown): unknown => {\n if (Array.isArray(value) && value.length > 0) {\n return value[0];\n }\n\n return undefined;\n};\n\nconst deriveType = (schema: Record<string, unknown>): string | undefined => {\n const typeValue = schema['type'];\n if (typeof typeValue === 'string') {\n return typeValue;\n }\n\n if (Array.isArray(typeValue)) {\n const firstType = typeValue.find(\n (entry): entry is string => typeof entry === 'string',\n );\n return firstType;\n }\n\n if (isRecord(schema['properties'])) {\n return 'object';\n }\n\n if (schema['items'] !== undefined) {\n return 'array';\n }\n\n return undefined;\n};\n\nconst baseScalarExample = (typeName: string): unknown => {\n switch (typeName) {\n case 'string': {\n return EXAMPLE_PLACEHOLDER;\n }\n case 'integer': {\n return EXAMPLE_PLACEHOLDER;\n }\n case 'number': {\n return EXAMPLE_PLACEHOLDER;\n }\n case 'boolean': {\n return EXAMPLE_PLACEHOLDER;\n }\n case 'null': {\n return EXAMPLE_PLACEHOLDER;\n }\n default: {\n return EXAMPLE_PLACEHOLDER;\n }\n }\n};\n\nconst buildExample = (value: unknown, depth: number): unknown => {\n if (!isRecord(value)) {\n return {};\n }\n\n if (depth > MAX_EXAMPLE_DEPTH) {\n return {};\n }\n\n const oneOfCandidate = firstKnown(value['oneOf']);\n if (oneOfCandidate !== undefined) {\n return buildExample(oneOfCandidate, depth + 1);\n }\n\n const anyOfCandidate = firstKnown(value['anyOf']);\n if (anyOfCandidate !== undefined) {\n return buildExample(anyOfCandidate, depth + 1);\n }\n\n const allOfCandidate = firstKnown(value['allOf']);\n if (allOfCandidate !== undefined) {\n return buildExample(allOfCandidate, depth + 1);\n }\n\n const typeName = deriveType(value);\n if (typeName === 'object') {\n const result: Record<string, unknown> = {};\n const properties = isRecord(value['properties']) ? value['properties'] : {};\n const required = asStringArray(value['required']);\n\n for (const propertyName of required) {\n const propertySchema = properties[propertyName];\n if (propertySchema !== undefined) {\n result[propertyName] = buildExample(propertySchema, depth + 1);\n }\n }\n\n if (required.length === 0 && isRecord(value['additionalProperties'])) {\n result['example'] = buildExample(\n value['additionalProperties'],\n depth + 1,\n );\n }\n\n return result;\n }\n\n if (typeName === 'array') {\n if (value['items'] === undefined) {\n return [EXAMPLE_PLACEHOLDER];\n }\n\n return [buildExample(value['items'], depth + 1)];\n }\n\n if (typeName === undefined) {\n return depth === 0 ? {} : EXAMPLE_PLACEHOLDER;\n }\n\n return baseScalarExample(typeName);\n};\n\nexport const buildJsonSchemaExample = (\n schema: Record<string, unknown>,\n): unknown => {\n return buildExample(schema, 0);\n};\n","export interface CatalogSummaryCommandOptions {\n cursor?: string | undefined;\n limit?: number | undefined;\n}\n\nexport const cliCommands = {\n auth: {\n help: (): string => 'ogment auth --help',\n login: (): string => 'ogment auth login',\n loginWithApiKeyRedacted: (): string =>\n 'ogment auth login --api-key <redacted>',\n logout: (): string => 'ogment auth logout',\n status: (): string => 'ogment auth status',\n },\n catalog: {\n command: (): string => 'ogment catalog',\n server: (serverId: string): string => `ogment catalog ${serverId}`,\n summary: (options: CatalogSummaryCommandOptions): string => {\n return [\n 'ogment catalog',\n ...(options.cursor === undefined ? [] : [`--cursor ${options.cursor}`]),\n ...(options.limit === undefined ? [] : [`--limit ${options.limit}`]),\n ].join(' ');\n },\n tool: (\n serverId: string,\n toolName: string,\n options: { example: boolean },\n ): string => {\n return [\n 'ogment catalog',\n serverId,\n toolName,\n ...(options.example ? ['--example'] : []),\n ].join(' ');\n },\n },\n helpForScope: (scope: string | null): string => {\n if (scope === null) {\n return 'ogment --help';\n }\n\n return `ogment ${scope} --help`;\n },\n invoke: {\n command: (target: string): string => `ogment invoke ${target}`,\n inlineJson: (target: string): string =>\n `ogment invoke ${target} --input <json>`,\n stdin: (target: string): string => `ogment invoke ${target} --input -`,\n withInputValue: (target: string, value: string): string => {\n return `ogment invoke ${target} --input ${value}`;\n },\n },\n root: {\n command: (): string => 'ogment',\n commandsSurface: (): string[] => {\n return [\n 'auth login',\n 'auth status',\n 'auth logout',\n 'catalog',\n 'catalog <server-id>',\n 'catalog <server-id> <tool-name>',\n 'invoke <server-id>/<tool-name>',\n 'status',\n ];\n },\n help: (): string => 'ogment --help',\n },\n status: {\n command: (): string => 'ogment status',\n },\n} as const;\n","import { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type {\n AuthStatusSuccess,\n CatalogSummarySuccess,\n CatalogToolDetailsSuccess,\n CatalogToolsSuccess,\n CliNextAction,\n InfoPayload,\n InvokeSuccess,\n LoginSuccess,\n} from '../shared/types.js';\nimport type {\n AuthLoginInvocation,\n CatalogInvocation,\n CliInvocation,\n InvokeInvocation,\n} from './invocations.js';\nimport type { Runtime } from './runtime.js';\n\nimport {\n runAuthLoginCommand,\n runAuthLogoutCommand,\n runAuthStatusCommand,\n type AuthLoginCommandOptions,\n} from '../commands/auth.js';\nimport {\n runCatalogCommand,\n runCatalogToolDetailsCommand,\n runCatalogToolsCommand,\n} from '../commands/catalog.js';\nimport { runInvokeCommand } from '../commands/invoke.js';\nimport { runStatusCommand } from '../commands/status.js';\nimport {\n type AppError,\n AuthError,\n ContractMismatchError,\n NotFoundError,\n RemoteRequestError,\n UnexpectedError,\n ValidationError,\n} from '../shared/errors.js';\nimport { type ExitCode, exitCodeForError } from '../shared/exit-codes.js';\nimport {\n buildJsonSchemaExample,\n EXAMPLE_PLACEHOLDER,\n} from '../shared/schema-example.js';\nimport { cliCommands } from './commands.js';\n\ninterface EnvelopeContext {\n command: string;\n entity?: Record<string, unknown> | null;\n}\n\ntype LoginFlowMode = 'api_key' | 'device';\n\ninterface AuthLoginPendingOutput {\n event: 'auth_login.pending';\n loggedIn: false;\n verification: {\n userCode: string;\n verificationUri: string;\n };\n}\n\ninterface AuthLoginCompletedOutput extends LoginSuccess {\n event: 'auth_login.completed';\n}\n\nexport class CliExitError extends Error {\n readonly exitCode: ExitCode;\n\n public constructor(exitCode: ExitCode) {\n super('CLI exit');\n this.exitCode = exitCode;\n }\n}\n\nconst throwCommandError = (error: AppError): never => {\n throw new CliExitError(exitCodeForError(error));\n};\n\nconst nextAction = (\n id: string,\n title: string,\n command: string,\n reason: string,\n when: string | null = null,\n): CliNextAction => {\n return {\n command,\n id,\n reason,\n title,\n when,\n };\n};\n\nconst ensureSuccess = <T, E extends AppError>(\n result: ResultType<T, E>,\n runtime: Runtime,\n context: EnvelopeContext,\n): T => {\n if (Result.isError(result)) {\n runtime.output.error(result.error, {\n command: context.command,\n entity: context.entity ?? null,\n });\n throwCommandError(result.error);\n }\n\n return result.unwrap();\n};\n\nconst nextActionsForLogin = (\n payload: LoginSuccess,\n mode: LoginFlowMode,\n): CliNextAction[] => {\n return [\n nextAction(\n 'check_auth_status',\n 'Check auth status',\n cliCommands.auth.status(),\n `Verify persisted credentials after ${mode} login for ${payload.agentName}.`,\n 'immediate',\n ),\n nextAction(\n 'discover_servers',\n 'Discover servers',\n cliCommands.catalog.command(),\n `Logged in as ${payload.agentName} via ${mode}; discover available servers.`,\n 'after_auth',\n ),\n ];\n};\n\nconst nextActionsForAuthStatus = (\n payload: AuthStatusSuccess,\n): CliNextAction[] => {\n if (!payload.loggedIn) {\n return [\n nextAction(\n 'login',\n 'Authenticate',\n cliCommands.auth.login(),\n 'No API key is configured locally; login is required.',\n 'immediate',\n ),\n ];\n }\n\n return [\n nextAction(\n 'discover_servers',\n 'Discover servers',\n cliCommands.catalog.command(),\n `Authenticated via ${payload.apiKeySource}; discover servers next.`,\n 'after_auth',\n ),\n ];\n};\n\ninterface CatalogSummaryActionsContext {\n limit: number | null;\n nextCursor: string | null;\n}\n\nconst nextActionsForCatalogSummary = (\n payload: CatalogSummarySuccess,\n context: CatalogSummaryActionsContext,\n): CliNextAction[] => {\n const actions: CliNextAction[] = [];\n const targetServer = payload.servers.find((server) => server.toolCount > 0);\n if (targetServer !== undefined) {\n actions.push(\n nextAction(\n 'inspect_tools',\n 'Inspect tools',\n cliCommands.catalog.server(targetServer.serverId),\n `${targetServer.serverId} has ${targetServer.toolCount} available tools.`,\n 'if_tool_count_gt_0',\n ),\n );\n }\n\n if (context.nextCursor !== null) {\n actions.push(\n nextAction(\n 'next_catalog_page',\n 'Load next page',\n cliCommands.catalog.summary({\n cursor: context.nextCursor,\n limit: context.limit ?? undefined,\n }),\n `More servers are available after cursor ${context.nextCursor}.`,\n 'if_more_servers',\n ),\n );\n }\n\n return actions;\n};\n\nconst nextActionsForCatalogTools = (\n payload: CatalogToolsSuccess,\n): CliNextAction[] => {\n const firstTool = payload.tools[0];\n if (firstTool === undefined) {\n return [];\n }\n\n return [\n nextAction(\n 'inspect_tool',\n 'Inspect tool details',\n cliCommands.catalog.tool(payload.server.serverId, firstTool.name, {\n example: false,\n }),\n `Inspect schema for ${payload.server.serverId}/${firstTool.name} before invoking.`,\n 'if_tools_available',\n ),\n ];\n};\n\nconst toInlineJsonTemplateArgument = (value: unknown): string => {\n const placeholderLiteral = JSON.stringify(EXAMPLE_PLACEHOLDER);\n const serialized = JSON.stringify(value).replaceAll(\n placeholderLiteral,\n ' ... ',\n );\n const escaped = serialized.replaceAll(\"'\", String.raw`'\\''`);\n return `'${escaped}'`;\n};\n\nconst nextActionsForCatalogToolDetails = (\n payload: CatalogToolDetailsSuccess,\n exampleInput: unknown,\n): CliNextAction[] => {\n const inputArgument = toInlineJsonTemplateArgument(exampleInput);\n return [\n nextAction(\n 'invoke_tool',\n 'Invoke this tool',\n cliCommands.invoke.withInputValue(\n `${payload.server.serverId}/${payload.name}`,\n inputArgument,\n ),\n `Replace every ... placeholder with real JSON values, then invoke ${payload.server.serverId}/${payload.name}.`,\n 'after_tool_inspection',\n ),\n ];\n};\n\nconst nextActionsForInvoke = (payload: InvokeSuccess): CliNextAction[] => {\n return [\n nextAction(\n 'inspect_tool',\n 'Inspect tool schema',\n cliCommands.catalog.tool(payload.serverId, payload.toolName, {\n example: false,\n }),\n `Review ${payload.serverId}/${payload.toolName} schema for the next invocation.`,\n 'after_invoke',\n ),\n ];\n};\n\nconst nextActionsForStatus = (payload: InfoPayload): CliNextAction[] => {\n if (!payload.auth.apiKeyPresent) {\n return [\n nextAction(\n 'login',\n 'Authenticate',\n cliCommands.auth.login(),\n 'Status detected no API key; authenticate first.',\n 'immediate',\n ),\n ];\n }\n\n return [\n nextAction(\n 'discover_servers',\n 'Discover servers',\n cliCommands.catalog.command(),\n `Connectivity is ${payload.summary.status}; discover available servers.`,\n 'after_status',\n ),\n ];\n};\n\nconst runLoginFlow = async (\n runtime: Runtime,\n mode: LoginFlowMode,\n apiKey?: string,\n): Promise<void> => {\n const loginInvocation: {\n commandOptions: AuthLoginCommandOptions;\n invokedCommand: string;\n } = (() => {\n if (mode === 'api_key') {\n return {\n commandOptions: {\n apiKey: apiKey ?? '',\n mode: 'apiKey',\n },\n invokedCommand: cliCommands.auth.loginWithApiKeyRedacted(),\n };\n }\n\n const deviceCommand = cliCommands.auth.login();\n return {\n commandOptions: {\n mode: 'device',\n onPending: ({ userCode, verificationUri }) => {\n const pendingNextActions = [\n nextAction(\n 'check_login_status',\n 'Check login status',\n cliCommands.auth.status(),\n `Approve ${userCode} at ${verificationUri}, then verify local auth state.`,\n 'immediate',\n ),\n nextAction(\n 'restart_device_login',\n 'Restart login',\n cliCommands.auth.login(),\n `Restart login if code ${userCode} expires before approval.`,\n 'if_expired',\n ),\n ];\n\n runtime.output.success(\n {\n event: 'auth_login.pending',\n loggedIn: false,\n verification: {\n userCode,\n verificationUri,\n },\n } satisfies AuthLoginPendingOutput,\n {\n command: deviceCommand,\n entity: {\n event: 'auth_login.pending',\n mode,\n verification: {\n userCode,\n verificationUri,\n },\n },\n nextActions: pendingNextActions,\n },\n );\n },\n },\n invokedCommand: deviceCommand,\n };\n })();\n const { commandOptions, invokedCommand } = loginInvocation;\n\n const result = await runAuthLoginCommand(runtime.context, commandOptions);\n const data = ensureSuccess(result, runtime, {\n command: invokedCommand,\n entity: {\n mode,\n },\n });\n\n const outputData: AuthLoginCompletedOutput = {\n ...data,\n event: 'auth_login.completed',\n };\n\n runtime.output.success(outputData, {\n command: invokedCommand,\n entity: {\n agentName: data.agentName,\n event: 'auth_login.completed',\n loggedIn: data.loggedIn,\n mode,\n outcome: data.outcome,\n },\n nextActions: nextActionsForLogin(data, mode),\n });\n};\n\nconst executeAuthLoginInvocation = async (\n runtime: Runtime,\n invocation: AuthLoginInvocation,\n): Promise<void> => {\n if (invocation.apiKey !== undefined) {\n await runLoginFlow(runtime, 'api_key', invocation.apiKey);\n return;\n }\n\n await runLoginFlow(runtime, 'device');\n};\n\nconst executeAuthStatusInvocation = async (runtime: Runtime): Promise<void> => {\n const command = cliCommands.auth.status();\n const result = await runAuthStatusCommand(runtime.context);\n const data = ensureSuccess(result, runtime, {\n command,\n });\n\n runtime.output.success(data, {\n command,\n entity: {\n apiKeySource: data.apiKeySource,\n loggedIn: data.loggedIn,\n },\n nextActions: nextActionsForAuthStatus(data),\n });\n};\n\nconst executeAuthLogoutInvocation = async (runtime: Runtime): Promise<void> => {\n const command = cliCommands.auth.logout();\n const result = await runAuthLogoutCommand(runtime.context);\n const data = ensureSuccess(result, runtime, {\n command,\n });\n\n runtime.output.success(data, {\n command,\n entity: {\n localCredentialsDeleted: data.localCredentialsDeleted,\n revoked: data.revoked,\n },\n nextActions: [\n nextAction(\n 'login',\n 'Authenticate again',\n cliCommands.auth.login(),\n 'Logout completed; authenticate again before further tool calls.',\n 'after_logout',\n ),\n ],\n });\n};\n\nconst executeCatalogInvocation = async (\n runtime: Runtime,\n invocation: CatalogInvocation,\n): Promise<void> => {\n const parsedLimit = invocation.limit;\n\n if (invocation.serverId === undefined) {\n if (invocation.example) {\n throw new ValidationError({\n details: '--example without <server-id> <tool-name>',\n message:\n 'Invalid catalog options. --example requires <server-id> <tool-name>.',\n recovery: { command: cliCommands.catalog.command() },\n });\n }\n\n const command = cliCommands.catalog.summary({\n cursor: invocation.cursor,\n limit: parsedLimit,\n });\n\n const result = await runCatalogCommand(runtime.context, {\n cursor: invocation.cursor,\n includeDebug: runtime.output.debug,\n limit: parsedLimit,\n });\n const data = ensureSuccess(result, runtime, {\n command,\n entity: {\n cursor: invocation.cursor ?? null,\n limit: parsedLimit ?? null,\n },\n });\n\n const outputData: CatalogSummarySuccess = {\n failures: data.failures,\n servers: data.servers,\n };\n\n runtime.output.success(outputData, {\n command,\n entity: {\n cursor: invocation.cursor ?? null,\n failedServerCount: data.failures.length,\n limit: parsedLimit ?? null,\n serverCount: data.servers.length,\n },\n nextActions: nextActionsForCatalogSummary(outputData, {\n limit: parsedLimit ?? null,\n nextCursor: data.nextCursor,\n }),\n pagination: {\n nextCursor: data.nextCursor,\n },\n });\n return;\n }\n\n if (invocation.toolName === undefined) {\n if (invocation.cursor !== undefined || parsedLimit !== undefined) {\n throw new ValidationError({\n details:\n `${invocation.cursor === undefined ? '' : `--cursor ${invocation.cursor} `}${\n parsedLimit === undefined ? '' : `--limit ${parsedLimit}`\n }`.trim(),\n message:\n 'Invalid catalog options. --cursor and --limit are only valid for `ogment catalog`.',\n recovery: { command: cliCommands.catalog.command() },\n });\n }\n\n if (invocation.example) {\n throw new ValidationError({\n details: `--example without tool name for ${invocation.serverId}`,\n message: 'Invalid catalog options. --example requires <tool-name>.',\n recovery: { command: cliCommands.catalog.server(invocation.serverId) },\n });\n }\n\n const serverId = invocation.serverId;\n const command = cliCommands.catalog.server(serverId);\n const result = await runCatalogToolsCommand(runtime.context, { serverId });\n const data = ensureSuccess(result, runtime, {\n command,\n entity: {\n serverId,\n },\n });\n\n runtime.output.success(data, {\n command,\n entity: {\n serverId: data.server.serverId,\n toolCount: data.tools.length,\n },\n nextActions: nextActionsForCatalogTools(data),\n });\n return;\n }\n\n if (invocation.cursor !== undefined || parsedLimit !== undefined) {\n throw new ValidationError({\n details:\n `${invocation.cursor === undefined ? '' : `--cursor ${invocation.cursor} `}${\n parsedLimit === undefined ? '' : `--limit ${parsedLimit}`\n }`.trim(),\n message:\n 'Invalid catalog options. --cursor and --limit are only valid for `ogment catalog`.',\n recovery: {\n command: cliCommands.catalog.tool(\n invocation.serverId,\n invocation.toolName,\n {\n example: invocation.example,\n },\n ),\n },\n });\n }\n\n const serverId = invocation.serverId;\n const toolName = invocation.toolName;\n const command = cliCommands.catalog.tool(serverId, toolName, {\n example: invocation.example,\n });\n const result = await runCatalogToolDetailsCommand(runtime.context, {\n serverId,\n toolName,\n });\n const data = ensureSuccess(result, runtime, {\n command,\n entity: {\n serverId,\n toolName,\n },\n });\n\n const exampleInput = buildJsonSchemaExample(data.inputSchema);\n const outputData = invocation.example ? { ...data, exampleInput } : data;\n\n runtime.output.success(outputData, {\n command,\n entity: {\n serverId: data.server.serverId,\n toolName: data.name,\n },\n nextActions: nextActionsForCatalogToolDetails(data, exampleInput),\n });\n};\n\nconst executeInvokeInvocation = async (\n runtime: Runtime,\n invocation: InvokeInvocation,\n): Promise<void> => {\n let inputSource = 'none';\n let command = cliCommands.invoke.command(invocation.target);\n\n if (invocation.input !== undefined) {\n if (invocation.input === '-') {\n inputSource = 'stdin';\n command = cliCommands.invoke.stdin(invocation.target);\n } else if (invocation.input.startsWith('@')) {\n inputSource = 'file';\n command = cliCommands.invoke.withInputValue(\n invocation.target,\n invocation.input,\n );\n } else {\n inputSource = 'inline_json';\n command = cliCommands.invoke.inlineJson(invocation.target);\n }\n }\n\n const result = await runInvokeCommand(runtime.context, {\n input: invocation.input,\n target: invocation.target,\n });\n const data = ensureSuccess(result, runtime, {\n command,\n entity: {\n inputSource,\n target: invocation.target,\n },\n });\n\n runtime.output.success(data, {\n command,\n entity: {\n inputSource,\n serverId: data.serverId,\n toolName: data.toolName,\n },\n nextActions: nextActionsForInvoke(data),\n });\n};\n\nconst executeStatusInvocation = async (runtime: Runtime): Promise<void> => {\n const command = cliCommands.status.command();\n if (runtime.infoService === undefined) {\n throw new UnexpectedError({\n message: 'Info service is not configured',\n });\n }\n\n const result = await runStatusCommand(\n {\n apiKeyOverride: runtime.context.apiKeyOverride,\n },\n {\n infoService: runtime.infoService,\n },\n );\n const data = ensureSuccess(result, runtime, {\n command,\n });\n\n runtime.output.success(data, {\n command,\n entity: {\n summaryStatus: data.summary.status,\n },\n nextActions: nextActionsForStatus(data),\n });\n};\n\nconst executeRootInvocation = (runtime: Runtime): void => {\n runtime.output.success(\n {\n commands: cliCommands.root.commandsSurface(),\n },\n {\n command: cliCommands.root.command(),\n entity: null,\n nextActions: [\n nextAction(\n 'login',\n 'Authenticate',\n cliCommands.auth.login(),\n 'Authenticate first so catalog and invoke commands can run.',\n 'immediate',\n ),\n nextAction(\n 'catalog',\n 'Discover servers',\n cliCommands.catalog.command(),\n 'List accessible servers and tool counts.',\n 'after_auth',\n ),\n ],\n },\n );\n};\n\ntype InvocationHandlerMap = {\n [K in CliInvocation['kind']]: (\n runtime: Runtime,\n invocation: Extract<CliInvocation, { kind: K }>,\n ) => Promise<void>;\n};\n\nconst invocationHandlers: InvocationHandlerMap = {\n auth_login: executeAuthLoginInvocation,\n auth_logout: async (runtime) => executeAuthLogoutInvocation(runtime),\n auth_status: async (runtime) => executeAuthStatusInvocation(runtime),\n catalog: executeCatalogInvocation,\n invoke: executeInvokeInvocation,\n root: async (runtime) => {\n executeRootInvocation(runtime);\n },\n status: async (runtime) => executeStatusInvocation(runtime),\n};\n\nexport const executeInvocation = async (\n runtime: Runtime,\n invocation: CliInvocation,\n): Promise<void> => {\n switch (invocation.kind) {\n case 'auth_login':\n await invocationHandlers.auth_login(runtime, invocation);\n return;\n case 'auth_logout':\n await invocationHandlers.auth_logout(runtime, invocation);\n return;\n case 'auth_status':\n await invocationHandlers.auth_status(runtime, invocation);\n return;\n case 'catalog':\n await invocationHandlers.catalog(runtime, invocation);\n return;\n case 'invoke':\n await invocationHandlers.invoke(runtime, invocation);\n return;\n case 'root':\n await invocationHandlers.root(runtime, invocation);\n return;\n case 'status':\n await invocationHandlers.status(runtime, invocation);\n return;\n }\n};\n\nexport const normalizeCliRuntimeError = (error: unknown): AppError => {\n if (\n error instanceof AuthError ||\n error instanceof ContractMismatchError ||\n error instanceof NotFoundError ||\n error instanceof RemoteRequestError ||\n error instanceof UnexpectedError ||\n error instanceof ValidationError\n ) {\n return error;\n }\n\n if (error instanceof Error) {\n return new UnexpectedError({\n cause: error,\n message: error.message,\n });\n }\n\n return new UnexpectedError({\n cause: error,\n message: 'Unexpected CLI failure',\n });\n};\n","import type { CommanderError } from 'commander';\n\nimport type {\n CliNextAction,\n CliParseErrorKind,\n CliParseErrorPayload,\n} from '../shared/types.js';\n\nimport { cliCommands } from './commands.js';\n\nexport interface CommanderParseState {\n stderrChunks: string[];\n stdoutChunks: string[];\n}\n\nexport interface ParseCliErrorResult {\n nextActions: CliNextAction[];\n payload: CliParseErrorPayload;\n}\n\ninterface ParseCliErrorOptions {\n includeDebug?: boolean;\n}\n\nconst usageLinePattern = /^Usage:\\s+ogment(?:\\s+(.*))?$/;\n\nconst scopeFromUsageLine = (line: string): string | null => {\n const match = usageLinePattern.exec(line);\n if (match === null) {\n return null;\n }\n\n const suffix = match[1]?.trim();\n if (suffix === undefined || suffix.length === 0) {\n return null;\n }\n\n const scopeTokens: string[] = [];\n const tokens = suffix.split(/\\s+/);\n for (const token of tokens) {\n if (\n token.startsWith('[') ||\n token.startsWith('<') ||\n token.startsWith('-')\n ) {\n break;\n }\n scopeTokens.push(token);\n }\n\n if (scopeTokens.length === 0) {\n return null;\n }\n\n return scopeTokens.join(' ');\n};\n\nconst scopeFromOutput = (output: string): string | null => {\n const lines = output.split(/\\r?\\n/);\n for (const line of lines) {\n const scope = scopeFromUsageLine(line.trim());\n if (scope !== null) {\n return scope;\n }\n }\n\n return null;\n};\n\nconst inferCommandScope = (parseState: CommanderParseState): string | null => {\n const stderrScope = scopeFromOutput(parseState.stderrChunks.join(''));\n if (stderrScope !== null) {\n return stderrScope;\n }\n\n return scopeFromOutput(parseState.stdoutChunks.join(''));\n};\n\nconst detailForParseError = (\n error: CommanderError,\n scope: string | null,\n): string => {\n if (error.message !== '(outputHelp)') {\n return error.message;\n }\n\n if (scope === null) {\n return 'Missing or incomplete command.';\n }\n\n return `Missing or incomplete command for \\`${scope}\\`.`;\n};\n\nconst nextActionForParseError = (\n scope: string | null,\n helpCommand: string,\n): CliNextAction => {\n return {\n command: helpCommand,\n id: 'recover_cli_parse_error',\n reason:\n scope === null\n ? 'Input parsing failed; inspect canonical command syntax.'\n : `Input parsing failed for \\`${scope}\\`; inspect command syntax.`,\n title: 'Show command help',\n when: 'immediate',\n };\n};\n\nconst parseActionsForScope = (\n scope: string | null,\n helpAction: CliNextAction,\n): CliNextAction[] => {\n if (scope === 'auth') {\n return [\n {\n command: cliCommands.auth.login(),\n id: 'auth_login',\n reason: 'Authenticate with device flow.',\n title: 'Auth login',\n when: 'immediate',\n },\n {\n command: cliCommands.auth.status(),\n id: 'auth_status',\n reason: 'Check current local authentication state.',\n title: 'Auth status',\n when: 'immediate',\n },\n helpAction,\n ];\n }\n\n if (scope === 'catalog') {\n return [\n {\n command: cliCommands.catalog.command(),\n id: 'catalog_summary',\n reason: 'List available servers and follow progressive discovery.',\n title: 'Catalog servers',\n when: 'immediate',\n },\n helpAction,\n ];\n }\n\n if (scope === 'invoke') {\n return [\n {\n command: cliCommands.catalog.command(),\n id: 'invoke_prepare',\n reason: 'Discover servers and tools before invoking a target command.',\n title: 'Discover tools',\n when: 'immediate',\n },\n helpAction,\n ];\n }\n\n if (scope === null) {\n return [helpAction];\n }\n\n return [helpAction];\n};\n\nconst parseErrorKind = (error: CommanderError): CliParseErrorKind => {\n switch (error.code) {\n case 'commander.missingArgument': {\n return 'missing_argument';\n }\n case 'commander.optionMissingArgument':\n case 'commander.missingMandatoryOptionValue': {\n return 'missing_option_value';\n }\n case 'commander.help': {\n return 'missing_subcommand';\n }\n case 'commander.invalidArgument': {\n return 'invalid_argument';\n }\n case 'commander.conflictingOption': {\n return 'conflicting_option';\n }\n case 'commander.excessArguments': {\n return 'excess_arguments';\n }\n case 'commander.unknownCommand': {\n return 'unknown_command';\n }\n case 'commander.unknownOption': {\n return 'unknown_option';\n }\n default: {\n return 'other';\n }\n }\n};\n\nconst parseHelpText = (parseState: CommanderParseState): string | null => {\n const stderr = parseState.stderrChunks.join('');\n if (stderr.length > 0) {\n return stderr;\n }\n\n const stdout = parseState.stdoutChunks.join('');\n return stdout.length > 0 ? stdout : null;\n};\n\nexport const createCommanderParseState = (): CommanderParseState => {\n return {\n stderrChunks: [],\n stdoutChunks: [],\n };\n};\n\nexport const toParseCliError = (\n error: CommanderError,\n parseState: CommanderParseState,\n options: ParseCliErrorOptions = {},\n): ParseCliErrorResult => {\n const scope = inferCommandScope(parseState);\n const helpCommand = cliCommands.helpForScope(scope);\n const helpAction = nextActionForParseError(scope, helpCommand);\n return {\n nextActions: parseActionsForScope(scope, helpAction),\n payload: {\n category: 'parse',\n code: 'CLI_PARSE_ERROR',\n detail: detailForParseError(error, scope),\n diagnostics: {\n kind: parseErrorKind(error),\n scope,\n ...(options.includeDebug === true\n ? {\n helpText: parseHelpText(parseState),\n parserCode: error.code,\n }\n : {}),\n },\n retryable: false,\n title: 'CLI parse error',\n },\n };\n};\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\nexport const cuid = /^[cC][^\\s-]{8,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n 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)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const 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}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const 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])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const 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])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst 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])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 3,\n patch: 6,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && result.schema._prefault)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, { ...params, path: [...params.path, \"items\"] });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n // encoding/decoding\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: /^https?$/,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn) {\n return core._superRefine(fn);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n","// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","import { readFileSync } from 'node:fs';\n\nimport { z } from 'zod';\n\nexport const APP_NAME = 'ogment';\nexport const APP_DESCRIPTION =\n \"Ogment CLI - secure your AI agents' SaaS credentials\";\n\nexport const DEFAULT_OGMENT_BASE_URL = 'https://dashboard.ogment.ai';\n\nconst packageJsonSchema = z.object({\n version: z.string().min(1),\n});\n\nconst hasCode = (value: unknown, code: string): boolean => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n return Reflect.get(value, 'code') === code;\n};\n\nconst readPackageJson = (): { version: string } => {\n const candidates = ['../../package.json', '../package.json'];\n\n for (const candidate of candidates) {\n try {\n return packageJsonSchema.parse(\n JSON.parse(readFileSync(new URL(candidate, import.meta.url), 'utf8')),\n );\n } catch (error) {\n if (hasCode(error, 'ENOENT')) {\n continue;\n }\n throw error;\n }\n }\n\n throw new Error('Could not locate package.json for CLI version metadata');\n};\n\nconst packageJson = readPackageJson();\n\nexport const VERSION = packageJson.version;\n","import { z } from 'zod';\n\nexport const jsonObjectSchema = z.record(z.string(), z.unknown());\n\nexport const cliErrorSchema = z\n .object({\n code: z.string().min(1),\n message: z.string().min(1),\n })\n .strict();\n\nexport const cliErrorEnvelopeSchema = z\n .object({\n error: cliErrorSchema,\n })\n .strict();\n\nexport const cliSuccessEnvelopeSchema = <TSchema extends z.ZodTypeAny>(\n dataSchema: TSchema,\n) => {\n return z\n .object({\n data: dataSchema,\n })\n .strict();\n};\n\nexport type CliError = z.infer<typeof cliErrorSchema>;\nexport type CliErrorEnvelope = z.infer<typeof cliErrorEnvelopeSchema>;\n","import { z } from 'zod';\n\nimport { cliSuccessEnvelopeSchema } from './common.js';\n\nexport const cliServerSchema = z\n .object({\n createdAt: z.string().nullable(),\n description: z.string().nullable(),\n enabled: z.boolean(),\n enabledToolCount: z.number().int().nonnegative(),\n id: z.string(),\n name: z.string(),\n path: z.string(),\n readOnlyEnabledToolCount: z.number().int().nonnegative(),\n toolCount: z.number().int().nonnegative(),\n })\n .strict();\n\nexport const cliOrgSchema = z\n .object({\n orgId: z.string(),\n orgName: z.string(),\n orgSlug: z.string(),\n role: z.string(),\n servers: z.array(cliServerSchema),\n })\n .strict();\n\nexport const cliMeDataSchema = z\n .object({\n email: z.string().nullable(),\n imageUrl: z.string().nullable(),\n name: z.string().nullable(),\n orgs: z.array(cliOrgSchema),\n userId: z.string(),\n })\n .strict();\n\nexport const accountMeSchema = cliSuccessEnvelopeSchema(cliMeDataSchema);\n\nexport type AccountMeResponse = z.infer<typeof accountMeSchema>;\nexport type CliMeData = z.infer<typeof cliMeDataSchema>;\nexport type CliOrg = z.infer<typeof cliOrgSchema>;\nexport type CliServer = z.infer<typeof cliServerSchema>;\n","import { z } from 'zod';\n\nimport { cliSuccessEnvelopeSchema } from './common.js';\n\nexport const deviceCodeStartDataSchema = z\n .object({\n deviceCode: z.string().min(1),\n expiresIn: z.number().int().positive(),\n interval: z.number().int().positive(),\n userCode: z.string().min(1),\n verificationUri: z.string().url(),\n })\n .strict();\n\nexport const deviceCodeStartSchema = cliSuccessEnvelopeSchema(\n deviceCodeStartDataSchema,\n);\n\nexport const deviceTokenPendingDataSchema = z\n .object({\n status: z.literal('authorization_pending'),\n })\n .strict();\n\nexport const deviceTokenApprovedDataSchema = z\n .object({\n agentName: z.string().min(1),\n apiKey: z.string().min(1),\n status: z.literal('approved'),\n })\n .strict();\n\nexport const deviceTokenDataSchema = z.discriminatedUnion('status', [\n deviceTokenPendingDataSchema,\n deviceTokenApprovedDataSchema,\n]);\n\nexport const deviceTokenSchema = cliSuccessEnvelopeSchema(\n deviceTokenDataSchema,\n);\nexport const deviceTokenApprovedSchema = cliSuccessEnvelopeSchema(\n deviceTokenApprovedDataSchema,\n);\n\nexport const revokeSelfDataSchema = z\n .object({\n success: z.literal(true),\n })\n .strict();\n\nexport const revokeSelfSchema = cliSuccessEnvelopeSchema(revokeSelfDataSchema);\n\nexport type DeviceCodeStartData = z.infer<typeof deviceCodeStartDataSchema>;\nexport type DeviceCodeStartResponse = z.infer<typeof deviceCodeStartSchema>;\nexport type DeviceTokenApprovedData = z.infer<\n typeof deviceTokenApprovedDataSchema\n>;\nexport type DeviceTokenApprovedResponse = z.infer<\n typeof deviceTokenApprovedSchema\n>;\nexport type DeviceTokenData = z.infer<typeof deviceTokenDataSchema>;\nexport type DeviceTokenResponse = z.infer<typeof deviceTokenSchema>;\nexport type RevokeSelfData = z.infer<typeof revokeSelfDataSchema>;\nexport type RevokeSelfResponse = z.infer<typeof revokeSelfSchema>;\n","export const cliEndpoints = {\n accountMe: '/api/v1/cli/me',\n cliRevokeSelf: '/api/v1/cli/revoke-self',\n deviceCode: '/api/v1/cli/device-code',\n deviceToken: '/api/v1/cli/device-token',\n} as const;\n\nexport type CliEndpointName = keyof typeof cliEndpoints;\n","import {\n accountMeSchema,\n deviceCodeStartSchema,\n deviceTokenApprovedSchema,\n deviceTokenSchema,\n} from '@repo/shared/cli';\nimport { z } from 'zod';\n\nexport {\n accountMeSchema,\n deviceCodeStartSchema,\n deviceTokenApprovedSchema,\n deviceTokenSchema,\n};\n\nexport const credentialsFileSchema = z.object({\n agentName: z.string().optional(),\n apiKey: z.string().min(1).optional(),\n});\n","import {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs';\n\nimport { Result } from 'better-result';\n\nimport type { Credentials } from '../shared/types.js';\n\nimport { UnexpectedError } from '../shared/errors.js';\nimport { parseWithSchema } from '../shared/guards.js';\nimport { credentialsFileSchema } from '../shared/schemas.js';\n\nexport interface CredentialsStore {\n delete(): Result<void, UnexpectedError>;\n load(): Result<Credentials | null, UnexpectedError>;\n save(credentials: Credentials): Result<void, UnexpectedError>;\n}\n\ninterface CredentialsStoreDeps {\n credentialsPath: string;\n configDir: string;\n existsSyncFn?: typeof existsSync;\n lstatSyncFn?: typeof lstatSync;\n mkdirSyncFn?: typeof mkdirSync;\n readFileSyncFn?: typeof readFileSync;\n unlinkSyncFn?: typeof unlinkSync;\n writeFileSyncFn?: typeof writeFileSync;\n}\n\nconst deleteIfExists = (\n path: string,\n existsSyncFn: typeof existsSync,\n unlinkSyncFn: typeof unlinkSync,\n): void => {\n if (existsSyncFn(path)) {\n unlinkSyncFn(path);\n }\n};\n\nconst normalizeCredentials = (value: unknown): Credentials | null => {\n const parsed = parseWithSchema(\n credentialsFileSchema,\n value,\n 'credentials file',\n );\n\n if (Result.isError(parsed)) {\n return null;\n }\n\n if (\n typeof parsed.value.apiKey === 'string' &&\n parsed.value.apiKey.length > 0\n ) {\n const credentials: Credentials = { apiKey: parsed.value.apiKey };\n if (typeof parsed.value.agentName === 'string') {\n credentials.agentName = parsed.value.agentName;\n }\n return credentials;\n }\n\n return null;\n};\n\nexport const createFileCredentialsStore = (\n deps: CredentialsStoreDeps,\n): CredentialsStore => {\n const existsSyncFn = deps.existsSyncFn ?? existsSync;\n const lstatSyncFn = deps.lstatSyncFn ?? lstatSync;\n const mkdirSyncFn = deps.mkdirSyncFn ?? mkdirSync;\n const readFileSyncFn = deps.readFileSyncFn ?? readFileSync;\n const unlinkSyncFn = deps.unlinkSyncFn ?? unlinkSync;\n const writeFileSyncFn = deps.writeFileSyncFn ?? writeFileSync;\n\n return {\n delete: () => {\n return Result.try({\n catch: (cause) =>\n new UnexpectedError({\n cause,\n message: 'Failed to delete credentials',\n }),\n try: () => {\n deleteIfExists(deps.credentialsPath, existsSyncFn, unlinkSyncFn);\n },\n });\n },\n load: () => {\n return Result.try({\n catch: (cause) =>\n new UnexpectedError({ cause, message: 'Failed to load credentials' }),\n try: () => {\n if (!existsSyncFn(deps.credentialsPath)) {\n return null;\n }\n\n const raw = readFileSyncFn(deps.credentialsPath, 'utf8');\n const parsed: unknown = JSON.parse(raw);\n const normalized = normalizeCredentials(parsed);\n\n if (normalized === null) {\n deleteIfExists(deps.credentialsPath, existsSyncFn, unlinkSyncFn);\n }\n\n return normalized;\n },\n });\n },\n save: (credentials) => {\n return Result.try({\n catch: (cause) =>\n new UnexpectedError({ cause, message: 'Failed to save credentials' }),\n try: () => {\n mkdirSyncFn(deps.configDir, { recursive: true });\n\n if (\n existsSyncFn(deps.credentialsPath) &&\n lstatSyncFn(deps.credentialsPath).isSymbolicLink()\n ) {\n unlinkSyncFn(deps.credentialsPath);\n }\n\n writeFileSyncFn(\n deps.credentialsPath,\n JSON.stringify(credentials, null, 2),\n {\n mode: 0o600,\n },\n );\n },\n });\n },\n };\n};\n","import { execSync } from 'node:child_process';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nimport type { BaseUrlSource } from '../shared/types.js';\n\nimport { DEFAULT_OGMENT_BASE_URL, VERSION } from '../shared/constants.js';\n\nexport interface RuntimeConfig {\n baseUrl: string;\n baseUrlSource: BaseUrlSource;\n configDir: string;\n credentialsPath: string;\n envApiKey: string | undefined;\n version: string;\n}\n\nexport const createRuntimeConfig = (\n env: NodeJS.ProcessEnv = process.env,\n homeDirectory: string = homedir(),\n): RuntimeConfig => {\n const configDir = join(homeDirectory, '.config', 'ogment');\n const hasBaseUrlOverride = typeof env['OGMENT_BASE_URL'] === 'string';\n\n return {\n baseUrl: env['OGMENT_BASE_URL'] ?? DEFAULT_OGMENT_BASE_URL,\n baseUrlSource: hasBaseUrlOverride ? 'env' : 'default',\n configDir,\n credentialsPath: join(configDir, 'credentials.json'),\n envApiKey: env['OGMENT_API_KEY'],\n version: VERSION,\n };\n};\n\nexport const isInteractiveOutput = (\n stdout: Pick<NodeJS.WriteStream, 'isTTY'> = process.stdout,\n): boolean => {\n return Boolean(stdout.isTTY);\n};\n\nconst getAncestorProcesses = (): string[] => {\n try {\n let pid = process.ppid;\n const ancestors: string[] = [];\n\n for (let depth = 0; depth < 5; depth += 1) {\n const command =\n execSync(`ps -p ${pid} -o comm=`, { timeout: 500 })\n .toString()\n .trim()\n .split('/')\n .pop() ?? '';\n if (command.length === 0) {\n break;\n }\n\n ancestors.push(command);\n\n const parentPid = execSync(`ps -p ${pid} -o ppid=`, { timeout: 500 })\n .toString()\n .trim();\n if (parentPid.length === 0 || parentPid === '0' || parentPid === '1') {\n break;\n }\n\n pid = Number(parentPid);\n }\n\n return ancestors;\n } catch {\n return [];\n }\n};\n\ntype AncestorProcessReader = () => string[];\n\nexport const detectExecutionEnvironment = (\n env: NodeJS.ProcessEnv = process.env,\n getAncestors: AncestorProcessReader = getAncestorProcesses,\n): string => {\n if (\n env['CURSOR_TRACE_ID'] !== undefined ||\n env['CURSOR_SESSION_ID'] !== undefined\n ) {\n return 'Cursor';\n }\n if (env['VSCODE_PID'] !== undefined || env['VSCODE_IPC_HOOK'] !== undefined) {\n return 'VS Code';\n }\n if (env['WINDSURF_SESSION_ID'] !== undefined) {\n return 'Windsurf';\n }\n if (\n typeof env['JETBRAINS_IDE'] === 'string' &&\n env['JETBRAINS_IDE'].length > 0\n ) {\n return env['JETBRAINS_IDE'];\n }\n if (\n env['CLAUDE_CODE_DISABLE_TELEMETRY'] !== undefined ||\n env['CLAUDE_CODE_MAX_TOKENS'] !== undefined ||\n env['CLAUDE_CODE_AUTO_APPROVE'] !== undefined\n ) {\n return 'Claude Code';\n }\n if (env['CI'] !== undefined) {\n return 'CI';\n }\n\n const ancestors = getAncestors();\n const ancestorNames = ancestors.join(' ').toLowerCase();\n\n if (ancestorNames.includes('claude')) {\n return 'Claude Code';\n }\n if (ancestorNames.includes('codex')) {\n return 'Codex';\n }\n if (ancestorNames.includes('cursor')) {\n return 'Cursor';\n }\n if (ancestorNames.includes('windsurf')) {\n return 'Windsurf';\n }\n if (ancestorNames.includes('warp')) {\n return 'Warp';\n }\n if (ancestors.some((value) => value.toLowerCase() === 'code')) {\n return 'VS Code';\n }\n\n if (env['TERM_PROGRAM'] === 'iTerm.app') {\n return 'iTerm';\n }\n if (env['TERM_PROGRAM'] === 'Apple_Terminal') {\n return 'Terminal.app';\n }\n if (env['TERM_PROGRAM'] === 'WezTerm') {\n return 'WezTerm';\n }\n if (env['TERM_PROGRAM'] === 'Hyper') {\n return 'Hyper';\n }\n if (\n typeof env['TERM_PROGRAM'] === 'string' &&\n env['TERM_PROGRAM'].length > 0\n ) {\n return env['TERM_PROGRAM'];\n }\n\n return 'unknown';\n};\n","import { Result } from 'better-result';\n\nimport { RemoteRequestError } from '../shared/errors.js';\n\nconst DEFAULT_HTTP_TIMEOUT_MS = 10_000;\n\nexport interface HttpClient {\n request(\n input: RequestInfo | URL,\n init?: RequestInit,\n options?: {\n operation?: string;\n timeoutMs?: number;\n },\n ): Promise<Result<Response, RemoteRequestError>>;\n}\n\ninterface HttpClientDeps {\n defaultTimeoutMs?: number;\n fetchFn?: typeof fetch;\n}\n\nconst isAbortError = (cause: unknown): boolean => {\n if (cause instanceof DOMException) {\n return cause.name === 'AbortError' || cause.name === 'TimeoutError';\n }\n\n if (cause instanceof Error) {\n return cause.name === 'AbortError' || cause.name === 'TimeoutError';\n }\n\n return false;\n};\n\nexport const createHttpClient = (deps: HttpClientDeps = {}): HttpClient => {\n const defaultTimeoutMs = deps.defaultTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS;\n const fetchFn = deps.fetchFn ?? fetch;\n\n return {\n request: async (input, init, options) => {\n const abortController = new AbortController();\n const timeoutMs = options?.timeoutMs ?? defaultTimeoutMs;\n const cleanupCallbacks: Array<() => void> = [];\n\n const abortWithReason = (reason: unknown): void => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n const upstreamSignal = init?.signal ?? undefined;\n if (upstreamSignal !== undefined) {\n if (upstreamSignal.aborted) {\n abortWithReason(upstreamSignal.reason);\n } else {\n const onAbort = () => {\n abortWithReason(upstreamSignal.reason);\n };\n upstreamSignal.addEventListener('abort', onAbort);\n cleanupCallbacks.push(() => {\n upstreamSignal.removeEventListener('abort', onAbort);\n });\n }\n }\n\n const timeoutId = setTimeout(() => {\n abortWithReason(\n new DOMException('HTTP request timed out', 'TimeoutError'),\n );\n }, timeoutMs);\n cleanupCallbacks.push(() => {\n clearTimeout(timeoutId);\n });\n\n const requestPromise = Result.tryPromise({\n catch: (cause) =>\n new RemoteRequestError({\n message: isAbortError(cause)\n ? 'HTTP request timed out'\n : 'HTTP request failed',\n ...(options?.operation === undefined\n ? {}\n : { operation: options.operation }),\n raw:\n cause instanceof Error\n ? {\n message: cause.message,\n name: cause.name,\n stack: cause.stack,\n }\n : cause,\n retryable: isAbortError(cause),\n source: 'network',\n }),\n try: async () =>\n fetchFn(input, {\n ...init,\n signal: abortController.signal,\n }),\n });\n\n return requestPromise.finally(() => {\n for (const cleanup of cleanupCallbacks) {\n cleanup();\n }\n });\n },\n };\n};\n\nexport const readResponseText = async (response: Response): Promise<string> => {\n return Result.tryPromise({\n catch: () => '',\n try: async () => response.text(),\n }).then((result) => {\n if (Result.isError(result)) {\n return '';\n }\n\n return result.value;\n });\n};\n","import { randomUUID } from 'node:crypto';\n\nimport type { AppError } from '../shared/errors.js';\nimport type {\n CliErrorEnvelope,\n CliNextAction,\n CliParseErrorPayload,\n CliPaginationMeta,\n CliSuccessEnvelope,\n} from '../shared/types.js';\n\nimport { presentRuntimeErrorPayload } from '../shared/error-presentation.js';\n\nexport interface EnvelopeContext {\n command: string;\n diagnostics?: Record<string, unknown>;\n entity?: Record<string, unknown> | null;\n includeDebug?: boolean;\n nextActions?: CliNextAction[];\n pagination?: CliPaginationMeta;\n}\n\ninterface EnvelopeBuilderDeps {\n createRequestId?: () => string;\n now?: () => Date;\n}\n\nexport interface EnvelopeBuilder {\n error: (error: AppError, context: EnvelopeContext) => CliErrorEnvelope;\n parseError: (\n payload: CliParseErrorPayload,\n context: EnvelopeContext,\n ) => CliErrorEnvelope;\n success: <T>(data: T, context: EnvelopeContext) => CliSuccessEnvelope<T>;\n}\n\nexport const createEnvelopeBuilder = (\n deps: EnvelopeBuilderDeps = {},\n): EnvelopeBuilder => {\n const createRequestId = deps.createRequestId ?? randomUUID;\n const now = deps.now ?? (() => new Date());\n\n const toMeta = (context: EnvelopeContext) => {\n const base = {\n command: context.command,\n };\n\n if (context.pagination !== undefined) {\n return {\n ...base,\n pagination: context.pagination,\n ...(context.includeDebug === true\n ? {\n entity: context.entity ?? null,\n requestId: createRequestId(),\n timestamp: now().toISOString(),\n }\n : {}),\n };\n }\n\n return {\n ...base,\n ...(context.includeDebug === true\n ? {\n entity: context.entity ?? null,\n requestId: createRequestId(),\n timestamp: now().toISOString(),\n }\n : {}),\n };\n };\n\n return {\n error: (error, context) => {\n const payload = presentRuntimeErrorPayload(error, {\n ...(context.diagnostics === undefined\n ? {}\n : { contextDiagnostics: context.diagnostics }),\n includeDebug: context.includeDebug === true,\n });\n\n return {\n data: null,\n error: payload,\n meta: toMeta(context),\n next_actions: context.nextActions ?? [],\n ok: false,\n };\n },\n parseError: (payload, context) => {\n return {\n data: null,\n error: payload,\n meta: toMeta(context),\n next_actions: context.nextActions ?? [],\n ok: false,\n };\n },\n success: (data, context) => {\n return {\n data,\n error: null,\n meta: toMeta(context),\n next_actions: context.nextActions ?? [],\n ok: true,\n };\n },\n };\n};\n","import type {\n CliErrorEnvelope,\n CliNextAction,\n CliPaginationMeta,\n CliParseErrorPayload,\n CliSuccessEnvelope,\n} from '../shared/types.js';\n\nimport { appErrorMeta, type AppError } from '../shared/errors.js';\nimport { createEnvelopeBuilder, type EnvelopeBuilder } from './envelope.js';\n\nexport type OutputMode = 'json' | 'quiet';\n\nexport interface OutputInitOptions {\n debug?: boolean | undefined;\n json?: boolean | undefined;\n quiet: boolean | undefined;\n yes: boolean | undefined;\n}\n\ninterface WritableLike {\n write(chunk: string): boolean;\n}\n\ninterface OutputManagerDeps {\n createRequestId?: () => string;\n isTty?: boolean;\n noColor?: boolean;\n now?: () => Date;\n stderr?: WritableLike;\n stdout?: WritableLike;\n}\n\ninterface EnvelopeOptions {\n command: string;\n diagnostics?: Record<string, unknown>;\n entity?: Record<string, unknown> | null;\n nextActions?: CliNextAction[];\n pagination?: CliPaginationMeta;\n}\n\ntype SuccessOptions = EnvelopeOptions;\n\nconst toJson = (value: unknown): string => {\n return `${JSON.stringify(value, null, 2)}\\n`;\n};\n\nconst toMinimalEnvelope = (\n envelope: CliErrorEnvelope | CliSuccessEnvelope<unknown>,\n): {\n data: unknown;\n error: unknown;\n ok: boolean;\n} => {\n return {\n data: envelope.data,\n error: envelope.error,\n ok: envelope.ok,\n };\n};\n\nconst mergeNextActions = (\n recovery: CliNextAction | undefined | null,\n contextActions: CliNextAction[] | undefined,\n): CliNextAction[] => {\n const merged = [\n ...(recovery === undefined || recovery === null ? [] : [recovery]),\n ...(contextActions ?? []),\n ];\n const deduped: CliNextAction[] = [];\n const seen = new Set<string>();\n\n for (const action of merged) {\n const key = `${action.id}::${action.command}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n deduped.push(action);\n }\n\n return deduped;\n};\n\nexport class OutputManager {\n readonly #envelopeBuilder: EnvelopeBuilder;\n #mode: OutputMode;\n #debug = false;\n readonly #stderr: WritableLike;\n readonly #stdout: WritableLike;\n\n public constructor(deps: OutputManagerDeps = {}) {\n this.#stderr = deps.stderr ?? process.stderr;\n this.#stdout = deps.stdout ?? process.stdout;\n this.#mode = 'json';\n this.#envelopeBuilder = createEnvelopeBuilder({\n ...(deps.createRequestId === undefined\n ? {}\n : { createRequestId: deps.createRequestId }),\n ...(deps.now === undefined ? {} : { now: deps.now }),\n });\n }\n\n public configure(options: OutputInitOptions): void {\n this.#mode = options.quiet === true ? 'quiet' : 'json';\n this.#debug = options.debug === true;\n }\n\n public get mode(): OutputMode {\n return this.#mode;\n }\n\n public get debug(): boolean {\n return this.#debug;\n }\n\n public error(error: AppError, options: EnvelopeOptions): CliErrorEnvelope {\n const envelope = this.#envelopeBuilder.error(error, {\n ...options,\n includeDebug: this.#debug,\n nextActions: mergeNextActions(\n appErrorMeta(error).recovery,\n options.nextActions,\n ),\n });\n\n if (this.#mode === 'json') {\n this.#stdout.write(toJson(envelope));\n return envelope;\n }\n\n this.#stdout.write(toJson(toMinimalEnvelope(envelope)));\n return envelope;\n }\n\n public parseError(\n payload: CliParseErrorPayload,\n options: EnvelopeOptions,\n ): CliErrorEnvelope {\n const envelope = this.#envelopeBuilder.parseError(payload, {\n ...options,\n includeDebug: this.#debug,\n });\n\n if (this.#mode === 'json') {\n this.#stdout.write(toJson(envelope));\n return envelope;\n }\n\n this.#stdout.write(toJson(toMinimalEnvelope(envelope)));\n return envelope;\n }\n\n public info(message: string): void {\n if (this.#debug) {\n this.#stderr.write(`${message}\\n`);\n }\n }\n\n public json(value: unknown): void {\n this.#stdout.write(toJson(value));\n }\n\n public success<T>(data: T, options: SuccessOptions): void {\n const envelope = this.#envelopeBuilder.success(data, {\n ...options,\n includeDebug: this.#debug,\n });\n\n if (this.#mode === 'json') {\n this.#stdout.write(toJson(envelope));\n return;\n }\n\n this.#stdout.write(toJson(toMinimalEnvelope(envelope)));\n }\n\n public writeStdout(chunk: string): void {\n this.#stdout.write(chunk);\n }\n\n public writeStderr(chunk: string): void {\n this.#stderr.write(chunk);\n }\n}\n","import { cliEndpoints } from '@repo/shared/cli';\nimport { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type { HttpClient } from '../infra/http.js';\nimport type { AccountProfile, ServerWithOrg } from '../shared/types.js';\n\nimport { readResponseText } from '../infra/http.js';\nimport { ERROR_CODE } from '../shared/error-codes.js';\nimport {\n AuthError,\n RemoteRequestError,\n type ValidationError,\n} from '../shared/errors.js';\nimport { parseWithSchema } from '../shared/guards.js';\nimport { accountMeSchema } from '../shared/schemas.js';\n\nexport type FetchAccountError =\n | AuthError\n | RemoteRequestError\n | ValidationError;\n\nexport interface AccountService {\n fetchAccount(\n apiKey: string,\n ): Promise<ResultType<AccountProfile, FetchAccountError>>;\n listServers(\n apiKey: string,\n ): Promise<ResultType<ServerWithOrg[], FetchAccountError>>;\n}\n\ninterface AccountServiceDeps {\n baseUrl: string;\n httpClient: HttpClient;\n}\n\nconst authHeader = (apiKey: string): Record<string, string> => {\n return {\n Authorization: `Bearer ${apiKey}`,\n };\n};\n\nconst toEndpointUrl = (baseUrl: string, endpoint: string): string => {\n return `${baseUrl}${endpoint}`;\n};\n\nexport const createAccountService = (\n deps: AccountServiceDeps,\n): AccountService => {\n const fetchAccountOnce = async (\n apiKey: string,\n ): Promise<ResultType<AccountProfile, FetchAccountError>> => {\n const responseResult = await deps.httpClient.request(\n toEndpointUrl(deps.baseUrl, cliEndpoints.accountMe),\n {\n headers: authHeader(apiKey),\n },\n );\n\n if (Result.isError(responseResult)) {\n return responseResult;\n }\n\n if (!responseResult.value.ok) {\n if (responseResult.value.status === 401) {\n return Result.err(\n new AuthError({\n code: ERROR_CODE.authInvalidCredentials,\n message: 'Authentication failed. Run `ogment auth login` again.',\n recovery: { command: 'ogment auth login' },\n }),\n );\n }\n\n const body = await readResponseText(responseResult.value);\n return Result.err(\n new RemoteRequestError({\n body,\n httpStatus: responseResult.value.status,\n message: 'Failed to fetch account details',\n operation: 'account/fetch',\n raw: body,\n source: 'http',\n }),\n );\n }\n\n const jsonResult = await Result.tryPromise({\n catch: () =>\n new RemoteRequestError({\n httpStatus: responseResult.value.status,\n message: 'Failed to parse account response JSON',\n operation: 'account/fetch',\n source: 'http',\n }),\n try: async () => responseResult.value.json(),\n });\n\n if (Result.isError(jsonResult)) {\n return jsonResult;\n }\n\n const parsed = parseWithSchema(\n accountMeSchema,\n jsonResult.value,\n 'account response',\n );\n\n if (Result.isError(parsed)) {\n return parsed;\n }\n\n return Result.ok(parsed.value.data);\n };\n\n const fetchAccount = async (\n apiKey: string,\n ): Promise<ResultType<AccountProfile, FetchAccountError>> =>\n fetchAccountOnce(apiKey);\n\n return {\n fetchAccount,\n listServers: async (apiKey) => {\n const profileResult = await fetchAccount(apiKey);\n if (Result.isError(profileResult)) {\n return profileResult;\n }\n\n const servers = profileResult.value.orgs.flatMap((organization) => {\n return organization.servers.map((server) => {\n return {\n description: server.description,\n enabled: server.enabled,\n name: server.name,\n orgSlug: organization.orgSlug,\n path: server.path,\n };\n });\n });\n\n return Result.ok(servers);\n },\n };\n};\n","import { cliEndpoints } from '@repo/shared/cli';\nimport { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type { CredentialsStore } from '../infra/credentials.js';\nimport type { HttpClient } from '../infra/http.js';\nimport type { UnexpectedError } from '../shared/errors.js';\nimport type {\n AuthStatusSuccess,\n LoginSuccess,\n LogoutSuccess,\n} from '../shared/types.js';\n\nimport { readResponseText } from '../infra/http.js';\nimport { ERROR_CODE } from '../shared/error-codes.js';\nimport {\n AuthError,\n RemoteRequestError,\n ValidationError,\n} from '../shared/errors.js';\nimport { parseWithSchema } from '../shared/guards.js';\nimport { deviceCodeStartSchema, deviceTokenSchema } from '../shared/schemas.js';\n\nexport interface LoginPendingInfo {\n userCode: string;\n verificationUri: string;\n}\n\ninterface DeviceLoginOptions {\n mode: 'device';\n onPending?: (info: LoginPendingInfo) => void;\n}\n\ninterface ApiKeyLoginOptions {\n apiKey: string;\n mode: 'apiKey';\n}\n\nexport type LoginOptions = ApiKeyLoginOptions | DeviceLoginOptions;\n\nexport type LoginError =\n | AuthError\n | RemoteRequestError\n | UnexpectedError\n | ValidationError;\n\nexport type ResolveApiKeyError = AuthError | UnexpectedError;\n\nexport interface AuthService {\n login(options: LoginOptions): Promise<ResultType<LoginSuccess, LoginError>>;\n logout(): Promise<ResultType<LogoutSuccess, UnexpectedError>>;\n resolveApiKey(\n overrideApiKey?: string,\n ): Promise<ResultType<string, ResolveApiKeyError>>;\n status(\n overrideApiKey?: string,\n ): Promise<ResultType<AuthStatusSuccess, UnexpectedError>>;\n}\n\ninterface AuthServiceDeps {\n baseUrl: string;\n credentialsStore: CredentialsStore;\n envApiKey: string | undefined;\n httpClient: HttpClient;\n now?: () => number;\n sleep?: (milliseconds: number) => Promise<void>;\n}\n\nconst defaultSleep = async (milliseconds: number): Promise<void> => {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n};\n\nconst toEndpointUrl = (baseUrl: string, endpoint: string): string => {\n return `${baseUrl}${endpoint}`;\n};\n\nconst deviceCodeUrl = (baseUrl: string): string => {\n return toEndpointUrl(baseUrl, cliEndpoints.deviceCode);\n};\n\nconst deviceTokenUrl = (baseUrl: string): string => {\n return toEndpointUrl(baseUrl, cliEndpoints.deviceToken);\n};\n\nconst revokeUrl = (baseUrl: string): string => {\n return toEndpointUrl(baseUrl, cliEndpoints.cliRevokeSelf);\n};\n\nexport const createAuthService = (deps: AuthServiceDeps): AuthService => {\n const now = deps.now ?? Date.now;\n const sleep = deps.sleep ?? defaultSleep;\n\n const requestRemote = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<ResultType<Response, RemoteRequestError>> => {\n return deps.httpClient.request(input, init);\n };\n\n const loginWithDevice = async (\n options: DeviceLoginOptions,\n ): Promise<ResultType<LoginSuccess, LoginError>> => {\n const startFlowResponse = await requestRemote(deviceCodeUrl(deps.baseUrl), {\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n\n if (Result.isError(startFlowResponse)) {\n return startFlowResponse;\n }\n\n if (!startFlowResponse.value.ok) {\n const body = await readResponseText(startFlowResponse.value);\n return Result.err(\n new RemoteRequestError({\n body,\n httpStatus: startFlowResponse.value.status,\n message: 'Failed to start device login',\n operation: 'auth/device/start',\n raw: body,\n source: 'http',\n }),\n );\n }\n\n const startPayload = await Result.tryPromise({\n catch: () =>\n new RemoteRequestError({\n httpStatus: startFlowResponse.value.status,\n message: 'Failed to parse device login start payload',\n operation: 'auth/device/start',\n source: 'http',\n }),\n try: async () => startFlowResponse.value.json(),\n });\n\n if (Result.isError(startPayload)) {\n return startPayload;\n }\n\n const parsedStartPayload = parseWithSchema(\n deviceCodeStartSchema,\n startPayload.value,\n 'device login start response',\n );\n\n if (Result.isError(parsedStartPayload)) {\n return parsedStartPayload;\n }\n\n options.onPending?.({\n userCode: parsedStartPayload.value.data.userCode,\n verificationUri: parsedStartPayload.value.data.verificationUri,\n });\n\n const deadline = now() + parsedStartPayload.value.data.expiresIn * 1000;\n const interval = parsedStartPayload.value.data.interval * 1000;\n\n while (now() < deadline) {\n await sleep(interval);\n\n const pollResponse = await requestRemote(deviceTokenUrl(deps.baseUrl), {\n body: JSON.stringify({\n deviceCode: parsedStartPayload.value.data.deviceCode,\n }),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n\n if (Result.isError(pollResponse)) {\n return pollResponse;\n }\n\n if (pollResponse.value.status === 410) {\n return Result.err(\n new AuthError({\n code: ERROR_CODE.authDeviceExpired,\n message:\n 'Device login code expired. Run `ogment auth login` again.',\n recovery: { command: 'ogment auth login' },\n }),\n );\n }\n\n if (pollResponse.value.status === 404) {\n return Result.err(\n new AuthError({\n code: ERROR_CODE.authInvalidCredentials,\n message:\n 'Invalid device login code. Run `ogment auth login` again.',\n recovery: { command: 'ogment auth login' },\n }),\n );\n }\n\n if (!pollResponse.value.ok) {\n const body = await readResponseText(pollResponse.value);\n return Result.err(\n new RemoteRequestError({\n body,\n httpStatus: pollResponse.value.status,\n message: 'Failed to poll device login status',\n operation: 'auth/device/poll',\n raw: body,\n source: 'http',\n }),\n );\n }\n\n const pollPayload = await Result.tryPromise({\n catch: () =>\n new RemoteRequestError({\n httpStatus: pollResponse.value.status,\n message: 'Failed to parse device login poll payload',\n operation: 'auth/device/poll',\n source: 'http',\n }),\n try: async () => pollResponse.value.json(),\n });\n\n if (Result.isError(pollPayload)) {\n return pollPayload;\n }\n\n const parsedTokenPayload = parseWithSchema(\n deviceTokenSchema,\n pollPayload.value,\n 'device login poll response',\n );\n\n if (Result.isError(parsedTokenPayload)) {\n return parsedTokenPayload;\n }\n\n if (parsedTokenPayload.value.data.status === 'authorization_pending') {\n continue;\n }\n\n const approvedPayload = parsedTokenPayload.value.data;\n\n const saveResult = deps.credentialsStore.save({\n agentName: approvedPayload.agentName,\n apiKey: approvedPayload.apiKey,\n });\n\n if (Result.isError(saveResult)) {\n return saveResult;\n }\n\n return Result.ok({\n agentName: approvedPayload.agentName,\n loggedIn: true,\n outcome: 'authenticated',\n });\n }\n\n return Result.err(\n new AuthError({\n code: ERROR_CODE.authDeviceExpired,\n message: 'Device login code expired. Run `ogment auth login` again.',\n recovery: { command: 'ogment auth login' },\n }),\n );\n };\n\n return {\n login: async (options) => {\n if (options.mode === 'apiKey' && options.apiKey.length > 0) {\n const saveResult = deps.credentialsStore.save({\n agentName: 'CLI Agent',\n apiKey: options.apiKey,\n });\n\n if (Result.isError(saveResult)) {\n return saveResult;\n }\n\n return Result.ok({\n agentName: 'CLI Agent',\n loggedIn: true,\n outcome: 'authenticated',\n });\n }\n\n if (options.mode === 'apiKey') {\n return Result.err(\n new ValidationError({\n code: ERROR_CODE.validationInvalidInput,\n message: 'Missing API key value. Provide a non-empty API key.',\n recovery: { command: 'ogment auth login --api-key <key>' },\n }),\n );\n }\n\n const stored = deps.credentialsStore.load();\n if (Result.isError(stored)) {\n return stored;\n }\n\n if (stored.value !== null) {\n return Result.ok({\n agentName: stored.value.agentName ?? 'CLI Agent',\n loggedIn: true,\n outcome: 'already_authenticated',\n });\n }\n\n return loginWithDevice(options);\n },\n\n logout: async () => {\n const stored = deps.credentialsStore.load();\n if (Result.isError(stored)) {\n return stored;\n }\n\n if (stored.value === null) {\n return Result.ok({\n localCredentialsDeleted: false,\n revoked: false,\n });\n }\n\n const revokeResult = await requestRemote(revokeUrl(deps.baseUrl), {\n headers: {\n Authorization: `Bearer ${stored.value.apiKey}`,\n },\n method: 'POST',\n });\n\n const deleteResult = deps.credentialsStore.delete();\n if (Result.isError(deleteResult)) {\n return deleteResult;\n }\n\n const revoked = Result.isOk(revokeResult) && revokeResult.value.ok;\n\n return Result.ok({\n localCredentialsDeleted: true,\n revoked,\n });\n },\n\n resolveApiKey: async (overrideApiKey) => {\n if (typeof overrideApiKey === 'string' && overrideApiKey.length > 0) {\n return Result.ok(overrideApiKey);\n }\n\n if (typeof deps.envApiKey === 'string' && deps.envApiKey.length > 0) {\n return Result.ok(deps.envApiKey);\n }\n\n const stored = deps.credentialsStore.load();\n if (Result.isError(stored)) {\n return stored;\n }\n\n if (stored.value !== null) {\n return Result.ok(stored.value.apiKey);\n }\n\n return Result.err(\n new AuthError({\n code: ERROR_CODE.authRequired,\n message:\n 'Not logged in. Run `ogment auth login` or set OGMENT_API_KEY.',\n recovery: { command: 'ogment auth login' },\n }),\n );\n },\n\n status: async (overrideApiKey) => {\n if (typeof overrideApiKey === 'string' && overrideApiKey.length > 0) {\n return Result.ok({\n agentName: null,\n apiKeySource: 'apiKeyOption',\n loggedIn: true,\n });\n }\n\n if (typeof deps.envApiKey === 'string' && deps.envApiKey.length > 0) {\n return Result.ok({\n agentName: null,\n apiKeySource: 'env',\n loggedIn: true,\n });\n }\n\n const stored = deps.credentialsStore.load();\n if (Result.isError(stored)) {\n return stored;\n }\n\n if (stored.value === null) {\n return Result.ok({\n agentName: null,\n apiKeySource: 'none',\n loggedIn: false,\n });\n }\n\n return Result.ok({\n agentName: stored.value.agentName ?? null,\n apiKeySource: 'credentialsFile',\n loggedIn: true,\n });\n },\n };\n};\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\n\nimport { cliEndpoints } from '@repo/shared/cli';\nimport { Result } from 'better-result';\n\nimport type { CredentialsStore } from '../infra/credentials.js';\nimport type { HttpClient } from '../infra/http.js';\nimport type {\n BaseUrlSource,\n InfoAccountCheck,\n InfoApiKeySource,\n InfoPayload,\n InfoSummary,\n} from '../shared/types.js';\nimport type { AccountService } from './account.js';\n\nimport { detectExecutionEnvironment } from '../infra/env.js';\n\ninterface ApiKeyResolution {\n loadError: string | null;\n source: InfoApiKeySource;\n value: string | null;\n}\n\ntype DiagnosticIssueCode =\n | 'auth_failed'\n | 'credentials_load_failed'\n | 'no_api_key'\n | 'remote_request_failed'\n | 'response_validation_failed'\n | 'unreachable'\n | 'unexpected_diagnostic_error';\n\ninterface DiagnosticIssue {\n code: DiagnosticIssueCode;\n message: string;\n}\n\nexport interface InfoService {\n collect(apiKeyOverride?: string): Promise<InfoPayload>;\n}\n\ninterface InfoServiceDeps {\n accountService: AccountService;\n baseUrl: string;\n baseUrlSource: BaseUrlSource;\n configDir: string;\n credentialsPath: string;\n credentialsStore: CredentialsStore;\n detectExecutionEnvironmentFn?: () => string;\n envApiKey: string | undefined;\n existsSyncFn?: (path: string) => boolean;\n httpClient: HttpClient;\n now?: () => number;\n version: string;\n}\n\nconst maskApiKey = (apiKey: string): string => {\n if (apiKey.length <= 8) {\n return `*** (sha256:${createHash('sha256').update(apiKey).digest('hex').slice(0, 12)})`;\n }\n\n const start = apiKey.slice(0, 4);\n const end = apiKey.slice(-4);\n const fingerprint = createHash('sha256')\n .update(apiKey)\n .digest('hex')\n .slice(0, 12);\n return `${start}...${end} (sha256:${fingerprint})`;\n};\n\nconst resolveApiKey = (\n apiKeyOverride: string | undefined,\n envApiKey: string | undefined,\n credentialsStore: CredentialsStore,\n): ApiKeyResolution => {\n if (typeof apiKeyOverride === 'string' && apiKeyOverride.length > 0) {\n return {\n loadError: null,\n source: 'apiKeyOption',\n value: apiKeyOverride,\n };\n }\n\n if (typeof envApiKey === 'string' && envApiKey.length > 0) {\n return {\n loadError: null,\n source: 'env',\n value: envApiKey,\n };\n }\n\n const storedCredentials = credentialsStore.load();\n if (Result.isError(storedCredentials)) {\n return {\n loadError: storedCredentials.error.message,\n source: 'credentialsError',\n value: null,\n };\n }\n\n if (storedCredentials.value !== null) {\n return {\n loadError: null,\n source: 'credentialsFile',\n value: storedCredentials.value.apiKey,\n };\n }\n\n return {\n loadError: null,\n source: 'none',\n value: null,\n };\n};\n\nconst nextActionByIssueCode: Partial<Record<DiagnosticIssueCode, string>> = {\n auth_failed: 'Run `ogment auth login` to refresh credentials.',\n credentials_load_failed:\n 'Check file permissions and contents of `~/.config/ogment/credentials.json`.',\n no_api_key: 'Run `ogment auth login` or set `OGMENT_API_KEY`.',\n unreachable: 'Verify `OGMENT_BASE_URL` and network connectivity.',\n};\n\nconst toSummary = (issues: DiagnosticIssue[]): InfoSummary => {\n const nextActions = new Set<string>();\n\n for (const issue of issues) {\n const nextAction = nextActionByIssueCode[issue.code];\n if (nextAction !== undefined) {\n nextActions.add(nextAction);\n }\n }\n\n nextActions.add('Run `ogment catalog` to inspect available servers.');\n\n return {\n issues: issues.map((issue) => issue.message),\n nextActions: [...nextActions],\n status: issues.length > 0 ? 'warning' : 'ok',\n };\n};\n\nconst emptyAccountErrorDetails = (): Pick<\n InfoAccountCheck,\n | 'errorCode'\n | 'errorHttpStatus'\n | 'errorMcpCode'\n | 'errorRaw'\n | 'errorRetryable'\n | 'errorSource'\n> => {\n return {\n errorCode: null,\n errorHttpStatus: null,\n errorMcpCode: null,\n errorRaw: null,\n errorRetryable: null,\n errorSource: null,\n };\n};\n\nexport const createInfoService = (deps: InfoServiceDeps): InfoService => {\n const detectEnvironment =\n deps.detectExecutionEnvironmentFn ?? detectExecutionEnvironment;\n const existsSyncFn = deps.existsSyncFn ?? existsSync;\n const now = deps.now ?? Date.now;\n\n return {\n collect: async (apiKeyOverride) => {\n const apiKeyResolution = resolveApiKey(\n apiKeyOverride,\n deps.envApiKey,\n deps.credentialsStore,\n );\n const selectedApiKey = apiKeyResolution.value;\n const credentialsFileExists = existsSyncFn(deps.credentialsPath);\n const endpoint = `${deps.baseUrl}${cliEndpoints.accountMe}`;\n\n const pingHeaders: Record<string, string> | undefined =\n typeof selectedApiKey === 'string'\n ? {\n Authorization: `Bearer ${selectedApiKey}`,\n }\n : undefined;\n\n const pingStartedAt = now();\n const pingResult = await deps.httpClient.request(\n endpoint,\n pingHeaders === undefined ? undefined : { headers: pingHeaders },\n );\n const pingElapsedMs = now() - pingStartedAt;\n\n const ping = Result.isOk(pingResult)\n ? {\n endpoint,\n error: null,\n latencyMs: pingElapsedMs,\n reachable: true,\n status: pingResult.value.status,\n statusText: pingResult.value.statusText,\n }\n : {\n endpoint,\n error: pingResult.error.message,\n latencyMs: null,\n reachable: false,\n status: null,\n statusText: null,\n };\n\n const collectAccount = async (): Promise<InfoAccountCheck> => {\n if (selectedApiKey === null) {\n return {\n ...emptyAccountErrorDetails(),\n errorType: null,\n latencyMs: null,\n message: 'No API key available',\n orgCount: null,\n serverCount: null,\n serverPaths: [],\n status: 'skipped',\n };\n }\n\n const accountStartedAt = now();\n const accountResult =\n await deps.accountService.fetchAccount(selectedApiKey);\n const accountElapsedMs = now() - accountStartedAt;\n\n if (Result.isOk(accountResult)) {\n const servers = accountResult.value.orgs.flatMap((organization) => {\n return organization.servers.map((server) => server.path);\n });\n\n return {\n ...emptyAccountErrorDetails(),\n errorType: null,\n latencyMs: accountElapsedMs,\n message: null,\n orgCount: accountResult.value.orgs.length,\n serverCount: servers.length,\n serverPaths: servers.slice(0, 5),\n status: 'success',\n };\n }\n\n let normalizedStatus: InfoAccountCheck['status'] = 'unexpected_error';\n switch (accountResult.error._tag) {\n case 'AuthError': {\n normalizedStatus = 'auth_error';\n break;\n }\n case 'RemoteRequestError': {\n normalizedStatus = 'remote_error';\n break;\n }\n case 'ValidationError': {\n normalizedStatus = 'validation_error';\n break;\n }\n default: {\n normalizedStatus = 'unexpected_error';\n break;\n }\n }\n\n return {\n ...('code' in accountResult.error\n ? {\n errorCode: String(accountResult.error.code),\n }\n : {\n errorCode: null,\n }),\n ...('httpStatus' in accountResult.error\n ? {\n errorHttpStatus:\n typeof accountResult.error.httpStatus === 'number'\n ? accountResult.error.httpStatus\n : null,\n }\n : {\n errorHttpStatus: null,\n }),\n ...('mcpCode' in accountResult.error\n ? {\n errorMcpCode:\n typeof accountResult.error.mcpCode === 'number'\n ? accountResult.error.mcpCode\n : null,\n }\n : {\n errorMcpCode: null,\n }),\n ...('raw' in accountResult.error\n ? {\n errorRaw: accountResult.error.raw ?? null,\n }\n : {\n errorRaw: null,\n }),\n ...('retryable' in accountResult.error\n ? {\n errorRetryable:\n typeof accountResult.error.retryable === 'boolean'\n ? accountResult.error.retryable\n : null,\n }\n : {\n errorRetryable: null,\n }),\n ...('source' in accountResult.error\n ? {\n errorSource:\n typeof accountResult.error.source === 'string'\n ? accountResult.error.source\n : null,\n }\n : {\n errorSource: null,\n }),\n errorType: accountResult.error._tag,\n latencyMs: accountElapsedMs,\n message: accountResult.error.message,\n orgCount: null,\n serverCount: null,\n serverPaths: [],\n status: normalizedStatus,\n };\n };\n\n const account = await collectAccount();\n\n const issues: DiagnosticIssue[] = [];\n\n if (!ping.reachable) {\n issues.push({\n code: 'unreachable',\n message: `Could not reach ${deps.baseUrl}: ${ping.error ?? 'unknown error'}`,\n });\n }\n\n if (apiKeyResolution.source === 'none') {\n issues.push({\n code: 'no_api_key',\n message:\n 'No API key found in --api-key, OGMENT_API_KEY, or credentials file.',\n });\n }\n\n if (\n apiKeyResolution.source === 'credentialsError' &&\n apiKeyResolution.loadError !== null\n ) {\n issues.push({\n code: 'credentials_load_failed',\n message: `Failed to load credentials file: ${apiKeyResolution.loadError}`,\n });\n }\n\n if (account.status === 'auth_error') {\n issues.push({\n code: 'auth_failed',\n message: `Authentication failed: ${account.message ?? 'unknown auth error'}`,\n });\n }\n\n if (account.status === 'remote_error') {\n issues.push({\n code: 'remote_request_failed',\n message: `Remote request failed: ${account.message ?? 'unknown remote error'}`,\n });\n }\n\n if (account.status === 'validation_error') {\n issues.push({\n code: 'response_validation_failed',\n message: `Response validation failed: ${account.message ?? 'unknown validation error'}`,\n });\n }\n\n if (account.status === 'unexpected_error') {\n issues.push({\n code: 'unexpected_diagnostic_error',\n message: `Unexpected diagnostic error: ${account.message ?? 'unknown error'}`,\n });\n }\n\n return {\n auth: {\n apiKeyPresent: selectedApiKey !== null,\n apiKeyPreview:\n selectedApiKey === null ? null : maskApiKey(selectedApiKey),\n apiKeySource: apiKeyResolution.source,\n credentialsFileExists,\n credentialsFileLoadError: apiKeyResolution.loadError,\n },\n config: {\n baseUrl: deps.baseUrl,\n baseUrlSource: deps.baseUrlSource,\n configDir: deps.configDir,\n credentialsPath: deps.credentialsPath,\n },\n documentation: {\n configPrecedence: [\n '--api-key option',\n 'OGMENT_API_KEY environment variable',\n '~/.config/ogment/credentials.json',\n 'default base URL when OGMENT_BASE_URL is unset',\n ],\n quickCommands: [\n 'ogment status',\n 'ogment auth login',\n 'ogment catalog',\n 'ogment catalog <server-id>',\n 'ogment catalog <server-id> <tool-name>',\n \"ogment invoke <server-id>/<tool-name> --input '{}'\",\n ],\n },\n generatedAt: new Date(now()).toISOString(),\n remote: {\n account,\n ping,\n },\n runtime: {\n cliVersion: deps.version,\n executionEnvironment: detectEnvironment(),\n nodeVersion: process.version,\n platform: process.platform,\n processArch: process.arch,\n },\n summary: toSummary(issues),\n };\n },\n };\n};\n","// zod-compat.ts\n// ----------------------------------------------------\n// Unified types + helpers to accept Zod v3 and v4 (Mini)\n// ----------------------------------------------------\nimport * as z3rt from 'zod/v3';\nimport * as z4mini from 'zod/v4-mini';\n// --- Runtime detection ---\nexport function isZ4Schema(s) {\n // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3\n const schema = s;\n return !!schema._zod;\n}\n// --- Schema construction ---\nexport function objectFromShape(shape) {\n const values = Object.values(shape);\n if (values.length === 0)\n return z4mini.object({}); // default to v4 Mini\n const allV4 = values.every(isZ4Schema);\n const allV3 = values.every(s => !isZ4Schema(s));\n if (allV4)\n return z4mini.object(shape);\n if (allV3)\n return z3rt.object(shape);\n throw new Error('Mixed Zod versions detected in object shape.');\n}\n// --- Unified parsing ---\nexport function safeParse(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParse\n const result = z4mini.safeParse(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = v3Schema.safeParse(data);\n return result;\n}\nexport async function safeParseAsync(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParseAsync\n const result = await z4mini.safeParseAsync(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = await v3Schema.safeParseAsync(data);\n return result;\n}\n// --- Shape extraction ---\nexport function getObjectShape(schema) {\n if (!schema)\n return undefined;\n // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape`\n let rawShape;\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n rawShape = v4Schema._zod?.def?.shape;\n }\n else {\n const v3Schema = schema;\n rawShape = v3Schema.shape;\n }\n if (!rawShape)\n return undefined;\n if (typeof rawShape === 'function') {\n try {\n return rawShape();\n }\n catch {\n return undefined;\n }\n }\n return rawShape;\n}\n// --- Schema normalization ---\n/**\n * Normalizes a schema to an object schema. Handles both:\n * - Already-constructed object schemas (v3 or v4)\n * - Raw shapes that need to be wrapped into object schemas\n */\nexport function normalizeObjectSchema(schema) {\n if (!schema)\n return undefined;\n // First check if it's a raw shape (Record<string, AnySchema>)\n // Raw shapes don't have _def or _zod properties and aren't schemas themselves\n if (typeof schema === 'object') {\n // Check if it's actually a ZodRawShapeCompat (not a schema instance)\n // by checking if it lacks schema-like internal properties\n const asV3 = schema;\n const asV4 = schema;\n // If it's not a schema instance (no _def or _zod), it might be a raw shape\n if (!asV3._def && !asV4._zod) {\n // Check if all values are schemas (heuristic to confirm it's a raw shape)\n const values = Object.values(schema);\n if (values.length > 0 &&\n values.every(v => typeof v === 'object' &&\n v !== null &&\n (v._def !== undefined ||\n v._zod !== undefined ||\n typeof v.parse === 'function'))) {\n return objectFromShape(schema);\n }\n }\n }\n // If we get here, it should be an AnySchema (not a raw shape)\n // Check if it's already an object schema\n if (isZ4Schema(schema)) {\n // Check if it's a v4 object\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def && (def.type === 'object' || def.shape !== undefined)) {\n return schema;\n }\n }\n else {\n // Check if it's a v3 object\n const v3Schema = schema;\n if (v3Schema.shape !== undefined) {\n return schema;\n }\n }\n return undefined;\n}\n// --- Error message extraction ---\n/**\n * Safely extracts an error message from a parse result error.\n * Zod errors can have different structures, so we handle various cases.\n */\nexport function getParseErrorMessage(error) {\n if (error && typeof error === 'object') {\n // Try common error structures\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {\n const firstIssue = error.issues[0];\n if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {\n return String(firstIssue.message);\n }\n }\n // Fallback: try to stringify the error\n try {\n return JSON.stringify(error);\n }\n catch {\n return String(error);\n }\n }\n return String(error);\n}\n// --- Schema metadata access ---\n/**\n * Gets the description from a schema, if available.\n * Works with both Zod v3 and v4.\n *\n * Both versions expose a `.description` getter that returns the description\n * from their respective internal storage (v3: _def, v4: globalRegistry).\n */\nexport function getSchemaDescription(schema) {\n return schema.description;\n}\n/**\n * Checks if a schema is optional.\n * Works with both Zod v3 and v4.\n */\nexport function isSchemaOptional(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n return v4Schema._zod?.def?.type === 'optional';\n }\n const v3Schema = schema;\n // v3 has isOptional() method\n if (typeof schema.isOptional === 'function') {\n return schema.isOptional();\n }\n return v3Schema._def?.typeName === 'ZodOptional';\n}\n/**\n * Gets the literal value from a schema, if it's a literal schema.\n * Works with both Zod v3 and v4.\n * Returns undefined if the schema is not a literal or the value cannot be determined.\n */\nexport function getLiteralValue(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def) {\n // Try various ways to get the literal value\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n }\n const v3Schema = schema;\n const def = v3Schema._def;\n if (def) {\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n // Fallback: check for direct value property (some Zod versions)\n const directValue = schema.value;\n if (directValue !== undefined)\n return directValue;\n return undefined;\n}\n//# sourceMappingURL=zod-compat.js.map","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]).optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","/**\n * Experimental task interfaces for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n */\n/**\n * Checks if a task status represents a terminal state.\n * Terminal states are those where the task has finished and will not change.\n *\n * @param status - The task status to check\n * @returns True if the status is terminal (completed, failed, or cancelled)\n * @experimental\n */\nexport function isTerminal(status) {\n return status === 'completed' || status === 'failed' || status === 'cancelled';\n}\n//# sourceMappingURL=interfaces.js.map","// zod-json-schema-compat.ts\n// ----------------------------------------------------\n// JSON Schema conversion for both Zod v3 and Zod v4 (Mini)\n// v3 uses your vendored converter; v4 uses Mini's toJSONSchema\n// ----------------------------------------------------\nimport * as z4mini from 'zod/v4-mini';\nimport { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nfunction mapMiniTarget(t) {\n if (!t)\n return 'draft-7';\n if (t === 'jsonSchema7' || t === 'draft-7')\n return 'draft-7';\n if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')\n return 'draft-2020-12';\n return 'draft-7'; // fallback\n}\nexport function toJsonSchemaCompat(schema, opts) {\n if (isZ4Schema(schema)) {\n // v4 branch — use Mini's built-in toJSONSchema\n return z4mini.toJSONSchema(schema, {\n target: mapMiniTarget(opts?.target),\n io: opts?.pipeStrategy ?? 'input'\n });\n }\n // v3 branch — use vendored converter\n return zodToJsonSchema(schema, {\n strictUnions: opts?.strictUnions ?? true,\n pipeStrategy: opts?.pipeStrategy ?? 'input'\n });\n}\nexport function getMethodLiteral(schema) {\n const shape = getObjectShape(schema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n const value = getLiteralValue(methodSchema);\n if (typeof value !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n return value;\n}\nexport function parseWithCompat(schema, data) {\n const result = safeParse(schema, data);\n if (!result.success) {\n throw result.error;\n }\n return result.data;\n}\n//# sourceMappingURL=zod-json-schema-compat.js.map","import { safeParse } from '../server/zod-compat.js';\nimport { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js';\nimport { isTerminal } from '../experimental/tasks/interfaces.js';\nimport { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js';\n/**\n * The default request timeout, in miliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n */\nexport class Protocol {\n constructor(_options) {\n this._options = _options;\n this._requestMessageId = 0;\n this._requestHandlers = new Map();\n this._requestHandlerAbortControllers = new Map();\n this._notificationHandlers = new Map();\n this._responseHandlers = new Map();\n this._progressHandlers = new Map();\n this._timeoutInfo = new Map();\n this._pendingDebouncedNotifications = new Set();\n // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult\n this._taskProgressTokens = new Map();\n this._requestResolvers = new Map();\n this.setNotificationHandler(CancelledNotificationSchema, notification => {\n this._oncancel(notification);\n });\n this.setNotificationHandler(ProgressNotificationSchema, notification => {\n this._onprogress(notification);\n });\n this.setRequestHandler(PingRequestSchema, \n // Automatic pong by default.\n _request => ({}));\n // Install task handlers if TaskStore is provided\n this._taskStore = _options?.taskStore;\n this._taskMessageQueue = _options?.taskMessageQueue;\n if (this._taskStore) {\n this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n // Per spec: tasks/get responses SHALL NOT include related-task metadata\n // as the taskId parameter is the source of truth\n // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else\n return {\n ...task\n };\n });\n this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {\n const handleTaskResult = async () => {\n const taskId = request.params.taskId;\n // Deliver queued messages\n if (this._taskMessageQueue) {\n let queuedMessage;\n while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {\n // Handle response and error messages by routing them to the appropriate resolver\n if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {\n const message = queuedMessage.message;\n const requestId = message.id;\n // Lookup resolver in _requestResolvers map\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n // Remove resolver from map after invocation\n this._requestResolvers.delete(requestId);\n // Invoke resolver with response or error\n if (queuedMessage.type === 'response') {\n resolver(message);\n }\n else {\n // Convert JSONRPCError to McpError\n const errorMessage = message;\n const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);\n resolver(error);\n }\n }\n else {\n // Handle missing resolver gracefully with error logging\n const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';\n this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));\n }\n // Continue to next message\n continue;\n }\n // Send the message on the response stream by passing the relatedRequestId\n // This tells the transport to write the message to the tasks/result response stream\n await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });\n }\n }\n // Now check task status\n const task = await this._taskStore.getTask(taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);\n }\n // Block if task is not terminal (we've already delivered all queued messages above)\n if (!isTerminal(task.status)) {\n // Wait for status change or new messages\n await this._waitForTaskUpdate(taskId, extra.signal);\n // After waking up, recursively call to deliver any new messages or result\n return await handleTaskResult();\n }\n // If task is terminal, return the result\n if (isTerminal(task.status)) {\n const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);\n this._clearTaskQueue(taskId);\n return {\n ...result,\n _meta: {\n ...result._meta,\n [RELATED_TASK_META_KEY]: {\n taskId: taskId\n }\n }\n };\n }\n return await handleTaskResult();\n };\n return await handleTaskResult();\n });\n this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {\n try {\n const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);\n // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else\n return {\n tasks,\n nextCursor,\n _meta: {}\n };\n }\n catch (error) {\n throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {\n try {\n // Get the current task to check if it's in a terminal state, in case the implementation is not atomic\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);\n }\n // Reject cancellation of terminal tasks\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);\n }\n await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);\n this._clearTaskQueue(request.params.taskId);\n const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!cancelledTask) {\n // Task was deleted during cancellation (e.g., cleanup happened)\n throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);\n }\n return {\n _meta: {},\n ...cancelledTask\n };\n }\n catch (error) {\n // Re-throw McpError as-is\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n }\n }\n async _oncancel(notification) {\n if (!notification.params.requestId) {\n return;\n }\n // Handle request cancellation\n const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n controller?.abort(notification.params.reason);\n }\n _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {\n this._timeoutInfo.set(messageId, {\n timeoutId: setTimeout(onTimeout, timeout),\n startTime: Date.now(),\n timeout,\n maxTotalTimeout,\n resetTimeoutOnProgress,\n onTimeout\n });\n }\n _resetTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (!info)\n return false;\n const totalElapsed = Date.now() - info.startTime;\n if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n this._timeoutInfo.delete(messageId);\n throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: info.maxTotalTimeout,\n totalElapsed\n });\n }\n clearTimeout(info.timeoutId);\n info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n return true;\n }\n _cleanupTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (info) {\n clearTimeout(info.timeoutId);\n this._timeoutInfo.delete(messageId);\n }\n }\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n */\n async connect(transport) {\n this._transport = transport;\n const _onclose = this.transport?.onclose;\n this._transport.onclose = () => {\n _onclose?.();\n this._onclose();\n };\n const _onerror = this.transport?.onerror;\n this._transport.onerror = (error) => {\n _onerror?.(error);\n this._onerror(error);\n };\n const _onmessage = this._transport?.onmessage;\n this._transport.onmessage = (message, extra) => {\n _onmessage?.(message, extra);\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._onresponse(message);\n }\n else if (isJSONRPCRequest(message)) {\n this._onrequest(message, extra);\n }\n else if (isJSONRPCNotification(message)) {\n this._onnotification(message);\n }\n else {\n this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n }\n };\n await this._transport.start();\n }\n _onclose() {\n const responseHandlers = this._responseHandlers;\n this._responseHandlers = new Map();\n this._progressHandlers.clear();\n this._taskProgressTokens.clear();\n this._pendingDebouncedNotifications.clear();\n const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed');\n this._transport = undefined;\n this.onclose?.();\n for (const handler of responseHandlers.values()) {\n handler(error);\n }\n }\n _onerror(error) {\n this.onerror?.(error);\n }\n _onnotification(notification) {\n const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;\n // Ignore notifications not being subscribed to.\n if (handler === undefined) {\n return;\n }\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => handler(notification))\n .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n }\n _onrequest(request, extra) {\n const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n // Capture the current transport at request time to ensure responses go to the correct client\n const capturedTransport = this._transport;\n // Extract taskId from request metadata if present (needed early for method not found case)\n const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;\n if (handler === undefined) {\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: ErrorCode.MethodNotFound,\n message: 'Method not found'\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));\n }\n else {\n capturedTransport\n ?.send(errorResponse)\n .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n }\n return;\n }\n const abortController = new AbortController();\n this._requestHandlerAbortControllers.set(request.id, abortController);\n const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;\n const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;\n const fullExtra = {\n signal: abortController.signal,\n sessionId: capturedTransport?.sessionId,\n _meta: request.params?._meta,\n sendNotification: async (notification) => {\n // Include related-task metadata if this request is part of a task\n const notificationOptions = { relatedRequestId: request.id };\n if (relatedTaskId) {\n notificationOptions.relatedTask = { taskId: relatedTaskId };\n }\n await this.notification(notification, notificationOptions);\n },\n sendRequest: async (r, resultSchema, options) => {\n // Include related-task metadata if this request is part of a task\n const requestOptions = { ...options, relatedRequestId: request.id };\n if (relatedTaskId && !requestOptions.relatedTask) {\n requestOptions.relatedTask = { taskId: relatedTaskId };\n }\n // Set task status to input_required when sending a request within a task context\n // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)\n const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;\n if (effectiveTaskId && taskStore) {\n await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');\n }\n return await this.request(r, resultSchema, requestOptions);\n },\n authInfo: extra?.authInfo,\n requestId: request.id,\n requestInfo: extra?.requestInfo,\n taskId: relatedTaskId,\n taskStore: taskStore,\n taskRequestedTtl: taskCreationParams?.ttl,\n closeSSEStream: extra?.closeSSEStream,\n closeStandaloneSSEStream: extra?.closeStandaloneSSEStream\n };\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => {\n // If this request asked for task creation, check capability first\n if (taskCreationParams) {\n // Check if the request method supports task creation\n this.assertTaskHandlerCapability(request.method);\n }\n })\n .then(() => handler(request, fullExtra))\n .then(async (result) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const response = {\n result,\n jsonrpc: '2.0',\n id: request.id\n };\n // Queue or send the response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'response',\n message: response,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(response);\n }\n }, async (error) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError,\n message: error.message ?? 'Internal error',\n ...(error['data'] !== undefined && { data: error['data'] })\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(errorResponse);\n }\n })\n .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n .finally(() => {\n this._requestHandlerAbortControllers.delete(request.id);\n });\n }\n _onprogress(notification) {\n const { progressToken, ...params } = notification.params;\n const messageId = Number(progressToken);\n const handler = this._progressHandlers.get(messageId);\n if (!handler) {\n this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n return;\n }\n const responseHandler = this._responseHandlers.get(messageId);\n const timeoutInfo = this._timeoutInfo.get(messageId);\n if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n try {\n this._resetTimeout(messageId);\n }\n catch (error) {\n // Clean up if maxTotalTimeout was exceeded\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n responseHandler(error);\n return;\n }\n }\n handler(params);\n }\n _onresponse(response) {\n const messageId = Number(response.id);\n // Check if this is a response to a queued request\n const resolver = this._requestResolvers.get(messageId);\n if (resolver) {\n this._requestResolvers.delete(messageId);\n if (isJSONRPCResultResponse(response)) {\n resolver(response);\n }\n else {\n const error = new McpError(response.error.code, response.error.message, response.error.data);\n resolver(error);\n }\n return;\n }\n const handler = this._responseHandlers.get(messageId);\n if (handler === undefined) {\n this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n return;\n }\n this._responseHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n // Keep progress handler alive for CreateTaskResult responses\n let isTaskResponse = false;\n if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {\n const result = response.result;\n if (result.task && typeof result.task === 'object') {\n const task = result.task;\n if (typeof task.taskId === 'string') {\n isTaskResponse = true;\n this._taskProgressTokens.set(task.taskId, messageId);\n }\n }\n }\n if (!isTaskResponse) {\n this._progressHandlers.delete(messageId);\n }\n if (isJSONRPCResultResponse(response)) {\n handler(response);\n }\n else {\n const error = McpError.fromError(response.error.code, response.error.message, response.error.data);\n handler(error);\n }\n }\n get transport() {\n return this._transport;\n }\n /**\n * Closes the connection.\n */\n async close() {\n await this._transport?.close();\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * @example\n * ```typescript\n * const stream = protocol.requestStream(request, resultSchema, options);\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Final result:', message.result);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @experimental Use `client.experimental.tasks.requestStream()` to access this method.\n */\n async *requestStream(request, resultSchema, options) {\n const { task } = options ?? {};\n // For non-task requests, just yield the result\n if (!task) {\n try {\n const result = await this.request(request, resultSchema, options);\n yield { type: 'result', result };\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n return;\n }\n // For task-augmented requests, we need to poll for status\n // First, make the request to create the task\n let taskId;\n try {\n // Send the request and get the CreateTaskResult\n const createResult = await this.request(request, CreateTaskResultSchema, options);\n // Extract taskId from the result\n if (createResult.task) {\n taskId = createResult.task.taskId;\n yield { type: 'taskCreated', task: createResult.task };\n }\n else {\n throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task');\n }\n // Poll for task completion\n while (true) {\n // Get current task status\n const task = await this.getTask({ taskId }, options);\n yield { type: 'taskStatus', task };\n // Check if task is terminal\n if (isTerminal(task.status)) {\n if (task.status === 'completed') {\n // Get the final result\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n }\n else if (task.status === 'failed') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)\n };\n }\n else if (task.status === 'cancelled') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)\n };\n }\n return;\n }\n // When input_required, call tasks/result to deliver queued messages\n // (elicitation, sampling) via SSE and block until terminal\n if (task.status === 'input_required') {\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n return;\n }\n // Wait before polling again\n const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n // Check if cancelled\n options?.signal?.throwIfAborted();\n }\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n }\n /**\n * Sends a request and waits for a response.\n *\n * Do not use this method to emit notifications! Use notification() instead.\n */\n request(request, resultSchema, options) {\n const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};\n // Send the request\n return new Promise((resolve, reject) => {\n const earlyReject = (error) => {\n reject(error);\n };\n if (!this._transport) {\n earlyReject(new Error('Not connected'));\n return;\n }\n if (this._options?.enforceStrictCapabilities === true) {\n try {\n this.assertCapabilityForMethod(request.method);\n // If task creation is requested, also check task capabilities\n if (task) {\n this.assertTaskCapability(request.method);\n }\n }\n catch (e) {\n earlyReject(e);\n return;\n }\n }\n options?.signal?.throwIfAborted();\n const messageId = this._requestMessageId++;\n const jsonrpcRequest = {\n ...request,\n jsonrpc: '2.0',\n id: messageId\n };\n if (options?.onprogress) {\n this._progressHandlers.set(messageId, options.onprogress);\n jsonrpcRequest.params = {\n ...request.params,\n _meta: {\n ...(request.params?._meta || {}),\n progressToken: messageId\n }\n };\n }\n // Augment with task creation parameters if provided\n if (task) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n task: task\n };\n }\n // Augment with related task metadata if relatedTask is provided\n if (relatedTask) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n _meta: {\n ...(jsonrpcRequest.params?._meta || {}),\n [RELATED_TASK_META_KEY]: relatedTask\n }\n };\n }\n const cancel = (reason) => {\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n this._transport\n ?.send({\n jsonrpc: '2.0',\n method: 'notifications/cancelled',\n params: {\n requestId: messageId,\n reason: String(reason)\n }\n }, { relatedRequestId, resumptionToken, onresumptiontoken })\n .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n // Wrap the reason in an McpError if it isn't already\n const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));\n reject(error);\n };\n this._responseHandlers.set(messageId, response => {\n if (options?.signal?.aborted) {\n return;\n }\n if (response instanceof Error) {\n return reject(response);\n }\n try {\n const parseResult = safeParse(resultSchema, response.result);\n if (!parseResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n reject(parseResult.error);\n }\n else {\n resolve(parseResult.data);\n }\n }\n catch (error) {\n reject(error);\n }\n });\n options?.signal?.addEventListener('abort', () => {\n cancel(options?.signal?.reason);\n });\n const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n // Queue request if related to a task\n const relatedTaskId = relatedTask?.taskId;\n if (relatedTaskId) {\n // Store the response resolver for this request so responses can be routed back\n const responseResolver = (response) => {\n const handler = this._responseHandlers.get(messageId);\n if (handler) {\n handler(response);\n }\n else {\n // Log error when resolver is missing, but don't fail\n this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));\n }\n };\n this._requestResolvers.set(messageId, responseResolver);\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'request',\n message: jsonrpcRequest,\n timestamp: Date.now()\n }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n }\n else {\n // No related task - send through transport normally\n this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n }\n });\n }\n /**\n * Gets the current status of a task.\n *\n * @experimental Use `client.experimental.tasks.getTask()` to access this method.\n */\n async getTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.\n */\n async getTaskResult(params, resultSchema, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/result', params }, resultSchema, options);\n }\n /**\n * Lists tasks, optionally starting from a pagination cursor.\n *\n * @experimental Use `client.experimental.tasks.listTasks()` to access this method.\n */\n async listTasks(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options);\n }\n /**\n * Cancels a specific task.\n *\n * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.\n */\n async cancelTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options);\n }\n /**\n * Emits a notification, which is a one-way message that does not expect a response.\n */\n async notification(notification, options) {\n if (!this._transport) {\n throw new Error('Not connected');\n }\n this.assertNotificationCapability(notification.method);\n // Queue notification if related to a task\n const relatedTaskId = options?.relatedTask?.taskId;\n if (relatedTaskId) {\n // Build the JSONRPC notification with metadata\n const jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0',\n params: {\n ...notification.params,\n _meta: {\n ...(notification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'notification',\n message: jsonrpcNotification,\n timestamp: Date.now()\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n return;\n }\n const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n // A notification can only be debounced if it's in the list AND it's \"simple\"\n // (i.e., has no parameters and no related request ID or related task that could be lost).\n const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;\n if (canDebounce) {\n // If a notification of this type is already scheduled, do nothing.\n if (this._pendingDebouncedNotifications.has(notification.method)) {\n return;\n }\n // Mark this notification type as pending.\n this._pendingDebouncedNotifications.add(notification.method);\n // Schedule the actual send to happen in the next microtask.\n // This allows all synchronous calls in the current event loop tick to be coalesced.\n Promise.resolve().then(() => {\n // Un-mark the notification so the next one can be scheduled.\n this._pendingDebouncedNotifications.delete(notification.method);\n // SAFETY CHECK: If the connection was closed while this was pending, abort.\n if (!this._transport) {\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n // Send the notification, but don't await it here to avoid blocking.\n // Handle potential errors with a .catch().\n this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n });\n // Return immediately.\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n await this._transport.send(jsonrpcNotification, options);\n }\n /**\n * Registers a handler to invoke when this protocol object receives a request with the given method.\n *\n * Note that this will replace any previous request handler for the same method.\n */\n setRequestHandler(requestSchema, handler) {\n const method = getMethodLiteral(requestSchema);\n this.assertRequestHandlerCapability(method);\n this._requestHandlers.set(method, (request, extra) => {\n const parsed = parseWithCompat(requestSchema, request);\n return Promise.resolve(handler(parsed, extra));\n });\n }\n /**\n * Removes the request handler for the given method.\n */\n removeRequestHandler(method) {\n this._requestHandlers.delete(method);\n }\n /**\n * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n */\n assertCanSetRequestHandler(method) {\n if (this._requestHandlers.has(method)) {\n throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n }\n }\n /**\n * Registers a handler to invoke when this protocol object receives a notification with the given method.\n *\n * Note that this will replace any previous notification handler for the same method.\n */\n setNotificationHandler(notificationSchema, handler) {\n const method = getMethodLiteral(notificationSchema);\n this._notificationHandlers.set(method, notification => {\n const parsed = parseWithCompat(notificationSchema, notification);\n return Promise.resolve(handler(parsed));\n });\n }\n /**\n * Removes the notification handler for the given method.\n */\n removeNotificationHandler(method) {\n this._notificationHandlers.delete(method);\n }\n /**\n * Cleans up the progress handler associated with a task.\n * This should be called when a task reaches a terminal status.\n */\n _cleanupTaskProgressHandler(taskId) {\n const progressToken = this._taskProgressTokens.get(taskId);\n if (progressToken !== undefined) {\n this._progressHandlers.delete(progressToken);\n this._taskProgressTokens.delete(taskId);\n }\n }\n /**\n * Enqueues a task-related message for side-channel delivery via tasks/result.\n * @param taskId The task ID to associate the message with\n * @param message The message to enqueue\n * @param sessionId Optional session ID for binding the operation to a specific session\n * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)\n *\n * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle\n * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer\n * simply propagates the error.\n */\n async _enqueueTaskMessage(taskId, message, sessionId) {\n // Task message queues are only used when taskStore is configured\n if (!this._taskStore || !this._taskMessageQueue) {\n throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');\n }\n const maxQueueSize = this._options?.maxTaskQueueSize;\n await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);\n }\n /**\n * Clears the message queue for a task and rejects any pending request resolvers.\n * @param taskId The task ID whose queue should be cleared\n * @param sessionId Optional session ID for binding the operation to a specific session\n */\n async _clearTaskQueue(taskId, sessionId) {\n if (this._taskMessageQueue) {\n // Reject any pending request resolvers\n const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);\n for (const message of messages) {\n if (message.type === 'request' && isJSONRPCRequest(message.message)) {\n // Extract request ID from the message\n const requestId = message.message.id;\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed'));\n this._requestResolvers.delete(requestId);\n }\n else {\n // Log error when resolver is missing during cleanup for better observability\n this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));\n }\n }\n }\n }\n }\n /**\n * Waits for a task update (new messages or status change) with abort signal support.\n * Uses polling to check for updates at the task's configured poll interval.\n * @param taskId The task ID to wait for\n * @param signal Abort signal to cancel the wait\n * @returns Promise that resolves when an update occurs or rejects if aborted\n */\n async _waitForTaskUpdate(taskId, signal) {\n // Get the task's poll interval, falling back to default\n let interval = this._options?.defaultTaskPollInterval ?? 1000;\n try {\n const task = await this._taskStore?.getTask(taskId);\n if (task?.pollInterval) {\n interval = task.pollInterval;\n }\n }\n catch {\n // Use default interval if task lookup fails\n }\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n return;\n }\n // Wait for the poll interval, then resolve so caller can check for updates\n const timeoutId = setTimeout(resolve, interval);\n // Clean up timeout and reject if aborted\n signal.addEventListener('abort', () => {\n clearTimeout(timeoutId);\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n }, { once: true });\n });\n }\n requestTaskStore(request, sessionId) {\n const taskStore = this._taskStore;\n if (!taskStore) {\n throw new Error('No task store configured');\n }\n return {\n createTask: async (taskParams) => {\n if (!request) {\n throw new Error('No request provided');\n }\n return await taskStore.createTask(taskParams, request.id, {\n method: request.method,\n params: request.params\n }, sessionId);\n },\n getTask: async (taskId) => {\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n return task;\n },\n storeTaskResult: async (taskId, status, result) => {\n await taskStore.storeTaskResult(taskId, status, result, sessionId);\n // Get updated task state and send notification\n const task = await taskStore.getTask(taskId, sessionId);\n if (task) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: task\n });\n await this.notification(notification);\n if (isTerminal(task.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n getTaskResult: taskId => {\n return taskStore.getTaskResult(taskId, sessionId);\n },\n updateTaskStatus: async (taskId, status, statusMessage) => {\n // Check if task exists\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task \"${taskId}\" not found - it may have been cleaned up`);\n }\n // Don't allow transitions from terminal states\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot update task \"${taskId}\" from terminal status \"${task.status}\" to \"${status}\". Terminal states (completed, failed, cancelled) cannot transition to other states.`);\n }\n await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);\n // Get updated task state and send notification\n const updatedTask = await taskStore.getTask(taskId, sessionId);\n if (updatedTask) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: updatedTask\n });\n await this.notification(notification);\n if (isTerminal(updatedTask.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n listTasks: cursor => {\n return taskStore.listTasks(cursor, sessionId);\n }\n };\n }\n}\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nexport function mergeCapabilities(base, additional) {\n const result = { ...base };\n for (const key in additional) {\n const k = key;\n const addValue = additional[k];\n if (addValue === undefined)\n continue;\n const baseValue = result[k];\n if (isPlainObject(baseValue) && isPlainObject(addValue)) {\n result[k] = { ...baseValue, ...addValue };\n }\n else {\n result[k] = addValue;\n }\n }\n return result;\n}\n//# sourceMappingURL=protocol.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass _CodeOrName {\n}\nexports._CodeOrName = _CodeOrName;\nexports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;\nclass Name extends _CodeOrName {\n constructor(s) {\n super();\n if (!exports.IDENTIFIER.test(s))\n throw new Error(\"CodeGen: name must be a valid identifier\");\n this.str = s;\n }\n toString() {\n return this.str;\n }\n emptyStr() {\n return false;\n }\n get names() {\n return { [this.str]: 1 };\n }\n}\nexports.Name = Name;\nclass _Code extends _CodeOrName {\n constructor(code) {\n super();\n this._items = typeof code === \"string\" ? [code] : code;\n }\n toString() {\n return this.str;\n }\n emptyStr() {\n if (this._items.length > 1)\n return false;\n const item = this._items[0];\n return item === \"\" || item === '\"\"';\n }\n get str() {\n var _a;\n return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, \"\")));\n }\n get names() {\n var _a;\n return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {\n if (c instanceof Name)\n names[c.str] = (names[c.str] || 0) + 1;\n return names;\n }, {})));\n }\n}\nexports._Code = _Code;\nexports.nil = new _Code(\"\");\nfunction _(strs, ...args) {\n const code = [strs[0]];\n let i = 0;\n while (i < args.length) {\n addCodeArg(code, args[i]);\n code.push(strs[++i]);\n }\n return new _Code(code);\n}\nexports._ = _;\nconst plus = new _Code(\"+\");\nfunction str(strs, ...args) {\n const expr = [safeStringify(strs[0])];\n let i = 0;\n while (i < args.length) {\n expr.push(plus);\n addCodeArg(expr, args[i]);\n expr.push(plus, safeStringify(strs[++i]));\n }\n optimize(expr);\n return new _Code(expr);\n}\nexports.str = str;\nfunction addCodeArg(code, arg) {\n if (arg instanceof _Code)\n code.push(...arg._items);\n else if (arg instanceof Name)\n code.push(arg);\n else\n code.push(interpolate(arg));\n}\nexports.addCodeArg = addCodeArg;\nfunction optimize(expr) {\n let i = 1;\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1]);\n if (res !== undefined) {\n expr.splice(i - 1, 3, res);\n continue;\n }\n expr[i++] = \"+\";\n }\n i++;\n }\n}\nfunction mergeExprItems(a, b) {\n if (b === '\"\"')\n return a;\n if (a === '\"\"')\n return b;\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"')\n return;\n if (typeof b != \"string\")\n return `${a.slice(0, -1)}${b}\"`;\n if (b[0] === '\"')\n return a.slice(0, -1) + b.slice(1);\n return;\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name))\n return `\"${a}${b.slice(1)}`;\n return;\n}\nfunction strConcat(c1, c2) {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;\n}\nexports.strConcat = strConcat;\n// TODO do not allow arrays here\nfunction interpolate(x) {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x);\n}\nfunction stringify(x) {\n return new _Code(safeStringify(x));\n}\nexports.stringify = stringify;\nfunction safeStringify(x) {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\nexports.safeStringify = safeStringify;\nfunction getProperty(key) {\n return typeof key == \"string\" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;\n}\nexports.getProperty = getProperty;\n//Does best effort to format the name properly\nfunction getEsmExportName(key) {\n if (typeof key == \"string\" && exports.IDENTIFIER.test(key)) {\n return new _Code(`${key}`);\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);\n}\nexports.getEsmExportName = getEsmExportName;\nfunction regexpCode(rx) {\n return new _Code(rx.toString());\n}\nexports.regexpCode = regexpCode;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;\nconst code_1 = require(\"./code\");\nclass ValueError extends Error {\n constructor(name) {\n super(`CodeGen: \"code\" for ${name} not defined`);\n this.value = name.value;\n }\n}\nvar UsedValueState;\n(function (UsedValueState) {\n UsedValueState[UsedValueState[\"Started\"] = 0] = \"Started\";\n UsedValueState[UsedValueState[\"Completed\"] = 1] = \"Completed\";\n})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));\nexports.varKinds = {\n const: new code_1.Name(\"const\"),\n let: new code_1.Name(\"let\"),\n var: new code_1.Name(\"var\"),\n};\nclass Scope {\n constructor({ prefixes, parent } = {}) {\n this._names = {};\n this._prefixes = prefixes;\n this._parent = parent;\n }\n toName(nameOrPrefix) {\n return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);\n }\n name(prefix) {\n return new code_1.Name(this._newName(prefix));\n }\n _newName(prefix) {\n const ng = this._names[prefix] || this._nameGroup(prefix);\n return `${prefix}${ng.index++}`;\n }\n _nameGroup(prefix) {\n var _a, _b;\n if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`);\n }\n return (this._names[prefix] = { prefix, index: 0 });\n }\n}\nexports.Scope = Scope;\nclass ValueScopeName extends code_1.Name {\n constructor(prefix, nameStr) {\n super(nameStr);\n this.prefix = prefix;\n }\n setValue(value, { property, itemIndex }) {\n this.value = value;\n this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;\n }\n}\nexports.ValueScopeName = ValueScopeName;\nconst line = (0, code_1._) `\\n`;\nclass ValueScope extends Scope {\n constructor(opts) {\n super(opts);\n this._values = {};\n this._scope = opts.scope;\n this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };\n }\n get() {\n return this._scope;\n }\n name(prefix) {\n return new ValueScopeName(prefix, this._newName(prefix));\n }\n value(nameOrPrefix, value) {\n var _a;\n if (value.ref === undefined)\n throw new Error(\"CodeGen: ref must be passed in value\");\n const name = this.toName(nameOrPrefix);\n const { prefix } = name;\n const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;\n let vs = this._values[prefix];\n if (vs) {\n const _name = vs.get(valueKey);\n if (_name)\n return _name;\n }\n else {\n vs = this._values[prefix] = new Map();\n }\n vs.set(valueKey, name);\n const s = this._scope[prefix] || (this._scope[prefix] = []);\n const itemIndex = s.length;\n s[itemIndex] = value.ref;\n name.setValue(value, { property: prefix, itemIndex });\n return name;\n }\n getValue(prefix, keyOrRef) {\n const vs = this._values[prefix];\n if (!vs)\n return;\n return vs.get(keyOrRef);\n }\n scopeRefs(scopeName, values = this._values) {\n return this._reduceValues(values, (name) => {\n if (name.scopePath === undefined)\n throw new Error(`CodeGen: name \"${name}\" has no value`);\n return (0, code_1._) `${scopeName}${name.scopePath}`;\n });\n }\n scopeCode(values = this._values, usedValues, getCode) {\n return this._reduceValues(values, (name) => {\n if (name.value === undefined)\n throw new Error(`CodeGen: name \"${name}\" has no value`);\n return name.value.code;\n }, usedValues, getCode);\n }\n _reduceValues(values, valueCode, usedValues = {}, getCode) {\n let code = code_1.nil;\n for (const prefix in values) {\n const vs = values[prefix];\n if (!vs)\n continue;\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());\n vs.forEach((name) => {\n if (nameSet.has(name))\n return;\n nameSet.set(name, UsedValueState.Started);\n let c = valueCode(name);\n if (c) {\n const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;\n code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;\n }\n else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {\n code = (0, code_1._) `${code}${c}${this.opts._n}`;\n }\n else {\n throw new ValueError(name);\n }\n nameSet.set(name, UsedValueState.Completed);\n });\n }\n return code;\n }\n}\nexports.ValueScope = ValueScope;\n//# sourceMappingURL=scope.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst code_1 = require(\"./code\");\nconst scope_1 = require(\"./scope\");\nvar code_2 = require(\"./code\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return code_2._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return code_2.str; } });\nObject.defineProperty(exports, \"strConcat\", { enumerable: true, get: function () { return code_2.strConcat; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return code_2.nil; } });\nObject.defineProperty(exports, \"getProperty\", { enumerable: true, get: function () { return code_2.getProperty; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return code_2.stringify; } });\nObject.defineProperty(exports, \"regexpCode\", { enumerable: true, get: function () { return code_2.regexpCode; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return code_2.Name; } });\nvar scope_2 = require(\"./scope\");\nObject.defineProperty(exports, \"Scope\", { enumerable: true, get: function () { return scope_2.Scope; } });\nObject.defineProperty(exports, \"ValueScope\", { enumerable: true, get: function () { return scope_2.ValueScope; } });\nObject.defineProperty(exports, \"ValueScopeName\", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });\nObject.defineProperty(exports, \"varKinds\", { enumerable: true, get: function () { return scope_2.varKinds; } });\nexports.operators = {\n GT: new code_1._Code(\">\"),\n GTE: new code_1._Code(\">=\"),\n LT: new code_1._Code(\"<\"),\n LTE: new code_1._Code(\"<=\"),\n EQ: new code_1._Code(\"===\"),\n NEQ: new code_1._Code(\"!==\"),\n NOT: new code_1._Code(\"!\"),\n OR: new code_1._Code(\"||\"),\n AND: new code_1._Code(\"&&\"),\n ADD: new code_1._Code(\"+\"),\n};\nclass Node {\n optimizeNodes() {\n return this;\n }\n optimizeNames(_names, _constants) {\n return this;\n }\n}\nclass Def extends Node {\n constructor(varKind, name, rhs) {\n super();\n this.varKind = varKind;\n this.name = name;\n this.rhs = rhs;\n }\n render({ es5, _n }) {\n const varKind = es5 ? scope_1.varKinds.var : this.varKind;\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`;\n return `${varKind} ${this.name}${rhs};` + _n;\n }\n optimizeNames(names, constants) {\n if (!names[this.name.str])\n return;\n if (this.rhs)\n this.rhs = optimizeExpr(this.rhs, names, constants);\n return this;\n }\n get names() {\n return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};\n }\n}\nclass Assign extends Node {\n constructor(lhs, rhs, sideEffects) {\n super();\n this.lhs = lhs;\n this.rhs = rhs;\n this.sideEffects = sideEffects;\n }\n render({ _n }) {\n return `${this.lhs} = ${this.rhs};` + _n;\n }\n optimizeNames(names, constants) {\n if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)\n return;\n this.rhs = optimizeExpr(this.rhs, names, constants);\n return this;\n }\n get names() {\n const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };\n return addExprNames(names, this.rhs);\n }\n}\nclass AssignOp extends Assign {\n constructor(lhs, op, rhs, sideEffects) {\n super(lhs, rhs, sideEffects);\n this.op = op;\n }\n render({ _n }) {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n;\n }\n}\nclass Label extends Node {\n constructor(label) {\n super();\n this.label = label;\n this.names = {};\n }\n render({ _n }) {\n return `${this.label}:` + _n;\n }\n}\nclass Break extends Node {\n constructor(label) {\n super();\n this.label = label;\n this.names = {};\n }\n render({ _n }) {\n const label = this.label ? ` ${this.label}` : \"\";\n return `break${label};` + _n;\n }\n}\nclass Throw extends Node {\n constructor(error) {\n super();\n this.error = error;\n }\n render({ _n }) {\n return `throw ${this.error};` + _n;\n }\n get names() {\n return this.error.names;\n }\n}\nclass AnyCode extends Node {\n constructor(code) {\n super();\n this.code = code;\n }\n render({ _n }) {\n return `${this.code};` + _n;\n }\n optimizeNodes() {\n return `${this.code}` ? this : undefined;\n }\n optimizeNames(names, constants) {\n this.code = optimizeExpr(this.code, names, constants);\n return this;\n }\n get names() {\n return this.code instanceof code_1._CodeOrName ? this.code.names : {};\n }\n}\nclass ParentNode extends Node {\n constructor(nodes = []) {\n super();\n this.nodes = nodes;\n }\n render(opts) {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\");\n }\n optimizeNodes() {\n const { nodes } = this;\n let i = nodes.length;\n while (i--) {\n const n = nodes[i].optimizeNodes();\n if (Array.isArray(n))\n nodes.splice(i, 1, ...n);\n else if (n)\n nodes[i] = n;\n else\n nodes.splice(i, 1);\n }\n return nodes.length > 0 ? this : undefined;\n }\n optimizeNames(names, constants) {\n const { nodes } = this;\n let i = nodes.length;\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i];\n if (n.optimizeNames(names, constants))\n continue;\n subtractNames(names, n.names);\n nodes.splice(i, 1);\n }\n return nodes.length > 0 ? this : undefined;\n }\n get names() {\n return this.nodes.reduce((names, n) => addNames(names, n.names), {});\n }\n}\nclass BlockNode extends ParentNode {\n render(opts) {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n;\n }\n}\nclass Root extends ParentNode {\n}\nclass Else extends BlockNode {\n}\nElse.kind = \"else\";\nclass If extends BlockNode {\n constructor(condition, nodes) {\n super(nodes);\n this.condition = condition;\n }\n render(opts) {\n let code = `if(${this.condition})` + super.render(opts);\n if (this.else)\n code += \"else \" + this.else.render(opts);\n return code;\n }\n optimizeNodes() {\n super.optimizeNodes();\n const cond = this.condition;\n if (cond === true)\n return this.nodes; // else is ignored here\n let e = this.else;\n if (e) {\n const ns = e.optimizeNodes();\n e = this.else = Array.isArray(ns) ? new Else(ns) : ns;\n }\n if (e) {\n if (cond === false)\n return e instanceof If ? e : e.nodes;\n if (this.nodes.length)\n return this;\n return new If(not(cond), e instanceof If ? [e] : e.nodes);\n }\n if (cond === false || !this.nodes.length)\n return undefined;\n return this;\n }\n optimizeNames(names, constants) {\n var _a;\n this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n if (!(super.optimizeNames(names, constants) || this.else))\n return;\n this.condition = optimizeExpr(this.condition, names, constants);\n return this;\n }\n get names() {\n const names = super.names;\n addExprNames(names, this.condition);\n if (this.else)\n addNames(names, this.else.names);\n return names;\n }\n}\nIf.kind = \"if\";\nclass For extends BlockNode {\n}\nFor.kind = \"for\";\nclass ForLoop extends For {\n constructor(iteration) {\n super();\n this.iteration = iteration;\n }\n render(opts) {\n return `for(${this.iteration})` + super.render(opts);\n }\n optimizeNames(names, constants) {\n if (!super.optimizeNames(names, constants))\n return;\n this.iteration = optimizeExpr(this.iteration, names, constants);\n return this;\n }\n get names() {\n return addNames(super.names, this.iteration.names);\n }\n}\nclass ForRange extends For {\n constructor(varKind, name, from, to) {\n super();\n this.varKind = varKind;\n this.name = name;\n this.from = from;\n this.to = to;\n }\n render(opts) {\n const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;\n const { name, from, to } = this;\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);\n }\n get names() {\n const names = addExprNames(super.names, this.from);\n return addExprNames(names, this.to);\n }\n}\nclass ForIter extends For {\n constructor(loop, varKind, name, iterable) {\n super();\n this.loop = loop;\n this.varKind = varKind;\n this.name = name;\n this.iterable = iterable;\n }\n render(opts) {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);\n }\n optimizeNames(names, constants) {\n if (!super.optimizeNames(names, constants))\n return;\n this.iterable = optimizeExpr(this.iterable, names, constants);\n return this;\n }\n get names() {\n return addNames(super.names, this.iterable.names);\n }\n}\nclass Func extends BlockNode {\n constructor(name, args, async) {\n super();\n this.name = name;\n this.args = args;\n this.async = async;\n }\n render(opts) {\n const _async = this.async ? \"async \" : \"\";\n return `${_async}function ${this.name}(${this.args})` + super.render(opts);\n }\n}\nFunc.kind = \"func\";\nclass Return extends ParentNode {\n render(opts) {\n return \"return \" + super.render(opts);\n }\n}\nReturn.kind = \"return\";\nclass Try extends BlockNode {\n render(opts) {\n let code = \"try\" + super.render(opts);\n if (this.catch)\n code += this.catch.render(opts);\n if (this.finally)\n code += this.finally.render(opts);\n return code;\n }\n optimizeNodes() {\n var _a, _b;\n super.optimizeNodes();\n (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();\n (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();\n return this;\n }\n optimizeNames(names, constants) {\n var _a, _b;\n super.optimizeNames(names, constants);\n (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);\n return this;\n }\n get names() {\n const names = super.names;\n if (this.catch)\n addNames(names, this.catch.names);\n if (this.finally)\n addNames(names, this.finally.names);\n return names;\n }\n}\nclass Catch extends BlockNode {\n constructor(error) {\n super();\n this.error = error;\n }\n render(opts) {\n return `catch(${this.error})` + super.render(opts);\n }\n}\nCatch.kind = \"catch\";\nclass Finally extends BlockNode {\n render(opts) {\n return \"finally\" + super.render(opts);\n }\n}\nFinally.kind = \"finally\";\nclass CodeGen {\n constructor(extScope, opts = {}) {\n this._values = {};\n this._blockStarts = [];\n this._constants = {};\n this.opts = { ...opts, _n: opts.lines ? \"\\n\" : \"\" };\n this._extScope = extScope;\n this._scope = new scope_1.Scope({ parent: extScope });\n this._nodes = [new Root()];\n }\n toString() {\n return this._root.render(this.opts);\n }\n // returns unique name in the internal scope\n name(prefix) {\n return this._scope.name(prefix);\n }\n // reserves unique name in the external scope\n scopeName(prefix) {\n return this._extScope.name(prefix);\n }\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName, value) {\n const name = this._extScope.value(prefixOrName, value);\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());\n vs.add(name);\n return name;\n }\n getScopeValue(prefix, keyOrRef) {\n return this._extScope.getValue(prefix, keyOrRef);\n }\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName) {\n return this._extScope.scopeRefs(scopeName, this._values);\n }\n scopeCode() {\n return this._extScope.scopeCode(this._values);\n }\n _def(varKind, nameOrPrefix, rhs, constant) {\n const name = this._scope.toName(nameOrPrefix);\n if (rhs !== undefined && constant)\n this._constants[name.str] = rhs;\n this._leafNode(new Def(varKind, name, rhs));\n return name;\n }\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix, rhs, _constant) {\n return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);\n }\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix, rhs, _constant) {\n return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);\n }\n // `var` declaration with optional assignment\n var(nameOrPrefix, rhs, _constant) {\n return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);\n }\n // assignment code\n assign(lhs, rhs, sideEffects) {\n return this._leafNode(new Assign(lhs, rhs, sideEffects));\n }\n // `+=` code\n add(lhs, rhs) {\n return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));\n }\n // appends passed SafeExpr to code or executes Block\n code(c) {\n if (typeof c == \"function\")\n c();\n else if (c !== code_1.nil)\n this._leafNode(new AnyCode(c));\n return this;\n }\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues) {\n const code = [\"{\"];\n for (const [key, value] of keyValues) {\n if (code.length > 1)\n code.push(\",\");\n code.push(key);\n if (key !== value || this.opts.es5) {\n code.push(\":\");\n (0, code_1.addCodeArg)(code, value);\n }\n }\n code.push(\"}\");\n return new code_1._Code(code);\n }\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition, thenBody, elseBody) {\n this._blockNode(new If(condition));\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf();\n }\n else if (thenBody) {\n this.code(thenBody).endIf();\n }\n else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body');\n }\n return this;\n }\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition) {\n return this._elseNode(new If(condition));\n }\n // `else` clause - only valid after `if` or `else if` clauses\n else() {\n return this._elseNode(new Else());\n }\n // end `if` statement (needed if gen.if was used only with condition)\n endIf() {\n return this._endBlockNode(If, Else);\n }\n _for(node, forBody) {\n this._blockNode(node);\n if (forBody)\n this.code(forBody).endFor();\n return this;\n }\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration, forBody) {\n return this._for(new ForLoop(iteration), forBody);\n }\n // `for` statement for a range of values\n forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {\n const name = this._scope.toName(nameOrPrefix);\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name));\n }\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {\n const name = this._scope.toName(nameOrPrefix);\n if (this.opts.es5) {\n const arr = iterable instanceof code_1.Name ? iterable : this.var(\"_arr\", iterable);\n return this.forRange(\"_i\", 0, (0, code_1._) `${arr}.length`, (i) => {\n this.var(name, (0, code_1._) `${arr}[${i}]`);\n forBody(name);\n });\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name));\n }\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);\n }\n const name = this._scope.toName(nameOrPrefix);\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name));\n }\n // end `for` loop\n endFor() {\n return this._endBlockNode(For);\n }\n // `label` statement\n label(label) {\n return this._leafNode(new Label(label));\n }\n // `break` statement\n break(label) {\n return this._leafNode(new Break(label));\n }\n // `return` statement\n return(value) {\n const node = new Return();\n this._blockNode(node);\n this.code(value);\n if (node.nodes.length !== 1)\n throw new Error('CodeGen: \"return\" should have one node');\n return this._endBlockNode(Return);\n }\n // `try` statement\n try(tryBody, catchCode, finallyCode) {\n if (!catchCode && !finallyCode)\n throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"');\n const node = new Try();\n this._blockNode(node);\n this.code(tryBody);\n if (catchCode) {\n const error = this.name(\"e\");\n this._currNode = node.catch = new Catch(error);\n catchCode(error);\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally();\n this.code(finallyCode);\n }\n return this._endBlockNode(Catch, Finally);\n }\n // `throw` statement\n throw(error) {\n return this._leafNode(new Throw(error));\n }\n // start self-balancing block\n block(body, nodeCount) {\n this._blockStarts.push(this._nodes.length);\n if (body)\n this.code(body).endBlock(nodeCount);\n return this;\n }\n // end the current self-balancing block\n endBlock(nodeCount) {\n const len = this._blockStarts.pop();\n if (len === undefined)\n throw new Error(\"CodeGen: not in self-balancing block\");\n const toClose = this._nodes.length - len;\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);\n }\n this._nodes.length = len;\n return this;\n }\n // `function` heading (or definition if funcBody is passed)\n func(name, args = code_1.nil, async, funcBody) {\n this._blockNode(new Func(name, args, async));\n if (funcBody)\n this.code(funcBody).endFunc();\n return this;\n }\n // end function definition\n endFunc() {\n return this._endBlockNode(Func);\n }\n optimize(n = 1) {\n while (n-- > 0) {\n this._root.optimizeNodes();\n this._root.optimizeNames(this._root.names, this._constants);\n }\n }\n _leafNode(node) {\n this._currNode.nodes.push(node);\n return this;\n }\n _blockNode(node) {\n this._currNode.nodes.push(node);\n this._nodes.push(node);\n }\n _endBlockNode(N1, N2) {\n const n = this._currNode;\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop();\n return this;\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`);\n }\n _elseNode(node) {\n const n = this._currNode;\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"');\n }\n this._currNode = n.else = node;\n return this;\n }\n get _root() {\n return this._nodes[0];\n }\n get _currNode() {\n const ns = this._nodes;\n return ns[ns.length - 1];\n }\n set _currNode(node) {\n const ns = this._nodes;\n ns[ns.length - 1] = node;\n }\n}\nexports.CodeGen = CodeGen;\nfunction addNames(names, from) {\n for (const n in from)\n names[n] = (names[n] || 0) + (from[n] || 0);\n return names;\n}\nfunction addExprNames(names, from) {\n return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;\n}\nfunction optimizeExpr(expr, names, constants) {\n if (expr instanceof code_1.Name)\n return replaceName(expr);\n if (!canOptimize(expr))\n return expr;\n return new code_1._Code(expr._items.reduce((items, c) => {\n if (c instanceof code_1.Name)\n c = replaceName(c);\n if (c instanceof code_1._Code)\n items.push(...c._items);\n else\n items.push(c);\n return items;\n }, []));\n function replaceName(n) {\n const c = constants[n.str];\n if (c === undefined || names[n.str] !== 1)\n return n;\n delete names[n.str];\n return c;\n }\n function canOptimize(e) {\n return (e instanceof code_1._Code &&\n e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));\n }\n}\nfunction subtractNames(names, from) {\n for (const n in from)\n names[n] = (names[n] || 0) - (from[n] || 0);\n}\nfunction not(x) {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : (0, code_1._) `!${par(x)}`;\n}\nexports.not = not;\nconst andCode = mappend(exports.operators.AND);\n// boolean AND (&&) expression with the passed arguments\nfunction and(...args) {\n return args.reduce(andCode);\n}\nexports.and = and;\nconst orCode = mappend(exports.operators.OR);\n// boolean OR (||) expression with the passed arguments\nfunction or(...args) {\n return args.reduce(orCode);\n}\nexports.or = or;\nfunction mappend(op) {\n return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);\n}\nfunction par(x) {\n return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst codegen_1 = require(\"./codegen\");\nconst code_1 = require(\"./codegen/code\");\n// TODO refactor to use Set\nfunction toHash(arr) {\n const hash = {};\n for (const item of arr)\n hash[item] = true;\n return hash;\n}\nexports.toHash = toHash;\nfunction alwaysValidSchema(it, schema) {\n if (typeof schema == \"boolean\")\n return schema;\n if (Object.keys(schema).length === 0)\n return true;\n checkUnknownRules(it, schema);\n return !schemaHasRules(schema, it.self.RULES.all);\n}\nexports.alwaysValidSchema = alwaysValidSchema;\nfunction checkUnknownRules(it, schema = it.schema) {\n const { opts, self } = it;\n if (!opts.strictSchema)\n return;\n if (typeof schema === \"boolean\")\n return;\n const rules = self.RULES.keywords;\n for (const key in schema) {\n if (!rules[key])\n checkStrictMode(it, `unknown keyword: \"${key}\"`);\n }\n}\nexports.checkUnknownRules = checkUnknownRules;\nfunction schemaHasRules(schema, rules) {\n if (typeof schema == \"boolean\")\n return !schema;\n for (const key in schema)\n if (rules[key])\n return true;\n return false;\n}\nexports.schemaHasRules = schemaHasRules;\nfunction schemaHasRulesButRef(schema, RULES) {\n if (typeof schema == \"boolean\")\n return !schema;\n for (const key in schema)\n if (key !== \"$ref\" && RULES.all[key])\n return true;\n return false;\n}\nexports.schemaHasRulesButRef = schemaHasRulesButRef;\nfunction schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\")\n return schema;\n if (typeof schema == \"string\")\n return (0, codegen_1._) `${schema}`;\n }\n return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;\n}\nexports.schemaRefOrVal = schemaRefOrVal;\nfunction unescapeFragment(str) {\n return unescapeJsonPointer(decodeURIComponent(str));\n}\nexports.unescapeFragment = unescapeFragment;\nfunction escapeFragment(str) {\n return encodeURIComponent(escapeJsonPointer(str));\n}\nexports.escapeFragment = escapeFragment;\nfunction escapeJsonPointer(str) {\n if (typeof str == \"number\")\n return `${str}`;\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexports.escapeJsonPointer = escapeJsonPointer;\nfunction unescapeJsonPointer(str) {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\nexports.unescapeJsonPointer = unescapeJsonPointer;\nfunction eachItem(xs, f) {\n if (Array.isArray(xs)) {\n for (const x of xs)\n f(x);\n }\n else {\n f(xs);\n }\n}\nexports.eachItem = eachItem;\nfunction makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {\n return (gen, from, to, toName) => {\n const res = to === undefined\n ? from\n : to instanceof codegen_1.Name\n ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof codegen_1.Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to);\n return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;\n };\n}\nexports.mergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {\n 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})`));\n }),\n mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true);\n }\n else {\n gen.assign(to, (0, codegen_1._) `${to} || {}`);\n setEvaluated(gen, to, from);\n }\n }),\n mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n 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}`)),\n mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n};\nfunction evaluatedPropsToName(gen, ps) {\n if (ps === true)\n return gen.var(\"props\", true);\n const props = gen.var(\"props\", (0, codegen_1._) `{}`);\n if (ps !== undefined)\n setEvaluated(gen, props, ps);\n return props;\n}\nexports.evaluatedPropsToName = evaluatedPropsToName;\nfunction setEvaluated(gen, props, ps) {\n Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));\n}\nexports.setEvaluated = setEvaluated;\nconst snippets = {};\nfunction useFunc(gen, f) {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),\n });\n}\nexports.useFunc = useFunc;\nvar Type;\n(function (Type) {\n Type[Type[\"Num\"] = 0] = \"Num\";\n Type[Type[\"Str\"] = 1] = \"Str\";\n})(Type || (exports.Type = Type = {}));\nfunction getErrorPath(dataProp, dataPropType, jsPropertySyntax) {\n // let path\n if (dataProp instanceof codegen_1.Name) {\n const isNumber = dataPropType === Type.Num;\n return jsPropertySyntax\n ? isNumber\n ? (0, codegen_1._) `\"[\" + ${dataProp} + \"]\"`\n : (0, codegen_1._) `\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? (0, codegen_1._) `\"/\" + ${dataProp}`\n : (0, codegen_1._) `\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")`; // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp);\n}\nexports.getErrorPath = getErrorPath;\nfunction checkStrictMode(it, msg, mode = it.opts.strictSchema) {\n if (!mode)\n return;\n msg = `strict mode: ${msg}`;\n if (mode === true)\n throw new Error(msg);\n it.self.logger.warn(msg);\n}\nexports.checkStrictMode = checkStrictMode;\n//# sourceMappingURL=util.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"./codegen\");\nconst names = {\n // validation function arguments\n data: new codegen_1.Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new codegen_1.Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new codegen_1.Name(\"instancePath\"),\n parentData: new codegen_1.Name(\"parentData\"),\n parentDataProperty: new codegen_1.Name(\"parentDataProperty\"),\n rootData: new codegen_1.Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new codegen_1.Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new codegen_1.Name(\"vErrors\"), // null or array of validation errors\n errors: new codegen_1.Name(\"errors\"), // counter of validation errors\n this: new codegen_1.Name(\"this\"),\n // \"globals\"\n self: new codegen_1.Name(\"self\"),\n scope: new codegen_1.Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new codegen_1.Name(\"json\"),\n jsonPos: new codegen_1.Name(\"jsonPos\"),\n jsonLen: new codegen_1.Name(\"jsonLen\"),\n jsonPart: new codegen_1.Name(\"jsonPart\"),\n};\nexports.default = names;\n//# sourceMappingURL=names.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst util_1 = require(\"./util\");\nconst names_1 = require(\"./names\");\nexports.keywordError = {\n message: ({ keyword }) => (0, codegen_1.str) `must pass \"${keyword}\" keyword validation`,\n};\nexports.keyword$DataError = {\n message: ({ keyword, schemaType }) => schemaType\n ? (0, codegen_1.str) `\"${keyword}\" keyword must be ${schemaType} ($data)`\n : (0, codegen_1.str) `\"${keyword}\" keyword is invalid ($data)`,\n};\nfunction reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {\n const { it } = cxt;\n const { gen, compositeRule, allErrors } = it;\n const errObj = errorObjectCode(cxt, error, errorPaths);\n if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {\n addError(gen, errObj);\n }\n else {\n returnErrors(it, (0, codegen_1._) `[${errObj}]`);\n }\n}\nexports.reportError = reportError;\nfunction reportExtraError(cxt, error = exports.keywordError, errorPaths) {\n const { it } = cxt;\n const { gen, compositeRule, allErrors } = it;\n const errObj = errorObjectCode(cxt, error, errorPaths);\n addError(gen, errObj);\n if (!(compositeRule || allErrors)) {\n returnErrors(it, names_1.default.vErrors);\n }\n}\nexports.reportExtraError = reportExtraError;\nfunction resetErrorsCount(gen, errsCount) {\n gen.assign(names_1.default.errors, errsCount);\n 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)));\n}\nexports.resetErrorsCount = resetErrorsCount;\nfunction extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {\n /* istanbul ignore if */\n if (errsCount === undefined)\n throw new Error(\"ajv implementation error\");\n const err = gen.name(\"err\");\n gen.forRange(\"i\", errsCount, names_1.default.errors, (i) => {\n gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);\n 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)));\n gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);\n if (it.opts.verbose) {\n gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);\n gen.assign((0, codegen_1._) `${err}.data`, data);\n }\n });\n}\nexports.extendErrors = extendErrors;\nfunction addError(gen, errObj) {\n const err = gen.const(\"err\", errObj);\n 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})`);\n gen.code((0, codegen_1._) `${names_1.default.errors}++`);\n}\nfunction returnErrors(it, errs) {\n const { gen, validateName, schemaEnv } = it;\n if (schemaEnv.$async) {\n gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);\n }\n else {\n gen.assign((0, codegen_1._) `${validateName}.errors`, errs);\n gen.return(false);\n }\n}\nconst E = {\n keyword: new codegen_1.Name(\"keyword\"),\n schemaPath: new codegen_1.Name(\"schemaPath\"), // also used in JTD errors\n params: new codegen_1.Name(\"params\"),\n propertyName: new codegen_1.Name(\"propertyName\"),\n message: new codegen_1.Name(\"message\"),\n schema: new codegen_1.Name(\"schema\"),\n parentSchema: new codegen_1.Name(\"parentSchema\"),\n};\nfunction errorObjectCode(cxt, error, errorPaths) {\n const { createErrors } = cxt.it;\n if (createErrors === false)\n return (0, codegen_1._) `{}`;\n return errorObject(cxt, error, errorPaths);\n}\nfunction errorObject(cxt, error, errorPaths = {}) {\n const { gen, it } = cxt;\n const keyValues = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ];\n extraErrorProps(cxt, error, keyValues);\n return gen.object(...keyValues);\n}\nfunction errorInstancePath({ errorPath }, { instancePath }) {\n const instPath = instancePath\n ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`\n : errorPath;\n return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];\n}\nfunction errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {\n let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;\n if (schemaPath) {\n schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;\n }\n return [E.schemaPath, schPath];\n}\nfunction extraErrorProps(cxt, { params, message }, keyValues) {\n const { keyword, data, schemaValue, it } = cxt;\n const { opts, propertyName, topSchemaRef, schemaPath } = it;\n keyValues.push([E.keyword, keyword], [E.params, typeof params == \"function\" ? params(cxt) : params || (0, codegen_1._) `{}`]);\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message]);\n }\n if (opts.verbose) {\n keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);\n }\n if (propertyName)\n keyValues.push([E.propertyName, propertyName]);\n}\n//# sourceMappingURL=errors.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst boolError = {\n message: \"boolean schema is false\",\n};\nfunction topBoolOrEmptySchema(it) {\n const { gen, schema, validateName } = it;\n if (schema === false) {\n falseSchemaError(it, false);\n }\n else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(names_1.default.data);\n }\n else {\n gen.assign((0, codegen_1._) `${validateName}.errors`, null);\n gen.return(true);\n }\n}\nexports.topBoolOrEmptySchema = topBoolOrEmptySchema;\nfunction boolOrEmptySchema(it, valid) {\n const { gen, schema } = it;\n if (schema === false) {\n gen.var(valid, false); // TODO var\n falseSchemaError(it);\n }\n else {\n gen.var(valid, true); // TODO var\n }\n}\nexports.boolOrEmptySchema = boolOrEmptySchema;\nfunction falseSchemaError(it, overrideAllErrors) {\n const { gen, data } = it;\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n };\n (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);\n}\n//# sourceMappingURL=boolSchema.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getRules = exports.isJSONType = void 0;\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"];\nconst jsonTypes = new Set(_jsonTypes);\nfunction isJSONType(x) {\n return typeof x == \"string\" && jsonTypes.has(x);\n}\nexports.isJSONType = isJSONType;\nfunction getRules() {\n const groups = {\n number: { type: \"number\", rules: [] },\n string: { type: \"string\", rules: [] },\n array: { type: \"array\", rules: [] },\n object: { type: \"object\", rules: [] },\n };\n return {\n types: { ...groups, integer: true, boolean: true, null: true },\n rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],\n post: { rules: [] },\n all: {},\n keywords: {},\n };\n}\nexports.getRules = getRules;\n//# sourceMappingURL=rules.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;\nfunction schemaHasRulesForType({ schema, self }, type) {\n const group = self.RULES.types[type];\n return group && group !== true && shouldUseGroup(schema, group);\n}\nexports.schemaHasRulesForType = schemaHasRulesForType;\nfunction shouldUseGroup(schema, group) {\n return group.rules.some((rule) => shouldUseRule(schema, rule));\n}\nexports.shouldUseGroup = shouldUseGroup;\nfunction shouldUseRule(schema, rule) {\n var _a;\n return (schema[rule.keyword] !== undefined ||\n ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));\n}\nexports.shouldUseRule = shouldUseRule;\n//# sourceMappingURL=applicability.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;\nconst rules_1 = require(\"../rules\");\nconst applicability_1 = require(\"./applicability\");\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nvar DataType;\n(function (DataType) {\n DataType[DataType[\"Correct\"] = 0] = \"Correct\";\n DataType[DataType[\"Wrong\"] = 1] = \"Wrong\";\n})(DataType || (exports.DataType = DataType = {}));\nfunction getSchemaTypes(schema) {\n const types = getJSONTypes(schema.type);\n const hasNull = types.includes(\"null\");\n if (hasNull) {\n if (schema.nullable === false)\n throw new Error(\"type: null contradicts nullable: false\");\n }\n else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"');\n }\n if (schema.nullable === true)\n types.push(\"null\");\n }\n return types;\n}\nexports.getSchemaTypes = getSchemaTypes;\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nfunction getJSONTypes(ts) {\n const types = Array.isArray(ts) ? ts : ts ? [ts] : [];\n if (types.every(rules_1.isJSONType))\n return types;\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"));\n}\nexports.getJSONTypes = getJSONTypes;\nfunction coerceAndCheckDataType(it, types) {\n const { gen, data, opts } = it;\n const coerceTo = coerceToTypes(types, opts.coerceTypes);\n const checkTypes = types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);\n gen.if(wrongType, () => {\n if (coerceTo.length)\n coerceData(it, types, coerceTo);\n else\n reportTypeError(it);\n });\n }\n return checkTypes;\n}\nexports.coerceAndCheckDataType = coerceAndCheckDataType;\nconst COERCIBLE = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"]);\nfunction coerceToTypes(types, coerceTypes) {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : [];\n}\nfunction coerceData(it, types, coerceTo) {\n const { gen, data, opts } = it;\n const dataType = gen.let(\"dataType\", (0, codegen_1._) `typeof ${data}`);\n const coerced = gen.let(\"coerced\", (0, codegen_1._) `undefined`);\n if (opts.coerceTypes === \"array\") {\n gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen\n .assign(data, (0, codegen_1._) `${data}[0]`)\n .assign(dataType, (0, codegen_1._) `typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));\n }\n gen.if((0, codegen_1._) `${coerced} !== undefined`);\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t);\n }\n }\n gen.else();\n reportTypeError(it);\n gen.endIf();\n gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {\n gen.assign(data, coerced);\n assignParentData(it, coerced);\n });\n function coerceSpecificType(t) {\n switch (t) {\n case \"string\":\n gen\n .elseIf((0, codegen_1._) `${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, (0, codegen_1._) `\"\" + ${data}`)\n .elseIf((0, codegen_1._) `${data} === null`)\n .assign(coerced, (0, codegen_1._) `\"\"`);\n return;\n case \"number\":\n gen\n .elseIf((0, codegen_1._) `${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`)\n .assign(coerced, (0, codegen_1._) `+${data}`);\n return;\n case \"integer\":\n gen\n .elseIf((0, codegen_1._) `${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`)\n .assign(coerced, (0, codegen_1._) `+${data}`);\n return;\n case \"boolean\":\n gen\n .elseIf((0, codegen_1._) `${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf((0, codegen_1._) `${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true);\n return;\n case \"null\":\n gen.elseIf((0, codegen_1._) `${data} === \"\" || ${data} === 0 || ${data} === false`);\n gen.assign(coerced, null);\n return;\n case \"array\":\n gen\n .elseIf((0, codegen_1._) `${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`)\n .assign(coerced, (0, codegen_1._) `[${data}]`);\n }\n }\n}\nfunction assignParentData({ gen, parentData, parentDataProperty }, expr) {\n // TODO use gen.property\n gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));\n}\nfunction checkDataType(dataType, data, strictNums, correct = DataType.Correct) {\n const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;\n let cond;\n switch (dataType) {\n case \"null\":\n return (0, codegen_1._) `${data} ${EQ} null`;\n case \"array\":\n cond = (0, codegen_1._) `Array.isArray(${data})`;\n break;\n case \"object\":\n cond = (0, codegen_1._) `${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`;\n break;\n case \"integer\":\n cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);\n break;\n case \"number\":\n cond = numCond();\n break;\n default:\n return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;\n }\n return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);\n function numCond(_cond = codegen_1.nil) {\n return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == \"number\"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);\n }\n}\nexports.checkDataType = checkDataType;\nfunction checkDataTypes(dataTypes, data, strictNums, correct) {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct);\n }\n let cond;\n const types = (0, util_1.toHash)(dataTypes);\n if (types.array && types.object) {\n const notObj = (0, codegen_1._) `typeof ${data} != \"object\"`;\n cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;\n delete types.null;\n delete types.array;\n delete types.object;\n }\n else {\n cond = codegen_1.nil;\n }\n if (types.number)\n delete types.integer;\n for (const t in types)\n cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));\n return cond;\n}\nexports.checkDataTypes = checkDataTypes;\nconst typeError = {\n message: ({ schema }) => `must be ${schema}`,\n params: ({ schema, schemaValue }) => typeof schema == \"string\" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,\n};\nfunction reportTypeError(it) {\n const cxt = getTypeErrorContext(it);\n (0, errors_1.reportError)(cxt, typeError);\n}\nexports.reportTypeError = reportTypeError;\nfunction getTypeErrorContext(it) {\n const { gen, data, schema } = it;\n const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, \"type\");\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n };\n}\n//# sourceMappingURL=dataType.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.assignDefaults = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction assignDefaults(it, ty) {\n const { properties, items } = it.schema;\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default);\n }\n }\n else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i) => assignDefault(it, i, sch.default));\n }\n}\nexports.assignDefaults = assignDefaults;\nfunction assignDefault(it, prop, defaultValue) {\n const { gen, compositeRule, data, opts } = it;\n if (defaultValue === undefined)\n return;\n const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;\n if (compositeRule) {\n (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);\n return;\n }\n let condition = (0, codegen_1._) `${childData} === undefined`;\n if (opts.useDefaults === \"empty\") {\n condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === \"\"`;\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);\n}\n//# sourceMappingURL=defaults.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst codegen_1 = require(\"../compile/codegen\");\nconst util_1 = require(\"../compile/util\");\nconst names_1 = require(\"../compile/names\");\nconst util_2 = require(\"../compile/util\");\nfunction checkReportMissingProp(cxt, prop) {\n const { gen, data, it } = cxt;\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);\n cxt.error();\n });\n}\nexports.checkReportMissingProp = checkReportMissingProp;\nfunction checkMissingProp({ gen, data, it: { opts } }, properties, missing) {\n return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));\n}\nexports.checkMissingProp = checkMissingProp;\nfunction reportMissingProp(cxt, missing) {\n cxt.setParams({ missingProperty: missing }, true);\n cxt.error();\n}\nexports.reportMissingProp = reportMissingProp;\nfunction hasPropFunc(gen) {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,\n });\n}\nexports.hasPropFunc = hasPropFunc;\nfunction isOwnProperty(gen, data, property) {\n return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;\n}\nexports.isOwnProperty = isOwnProperty;\nfunction propertyInData(gen, data, property, ownProperties) {\n const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;\n return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;\n}\nexports.propertyInData = propertyInData;\nfunction noPropertyInData(gen, data, property, ownProperties) {\n const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;\n return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;\n}\nexports.noPropertyInData = noPropertyInData;\nfunction allSchemaProperties(schemaMap) {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : [];\n}\nexports.allSchemaProperties = allSchemaProperties;\nfunction schemaProperties(it, schemaMap) {\n return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));\n}\nexports.schemaProperties = schemaProperties;\nfunction callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {\n const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;\n const valCxt = [\n [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],\n [names_1.default.parentData, it.parentData],\n [names_1.default.parentDataProperty, it.parentDataProperty],\n [names_1.default.rootData, names_1.default.rootData],\n ];\n if (it.opts.dynamicRef)\n valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);\n const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;\n return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;\n}\nexports.callValidateCode = callValidateCode;\nconst newRegExp = (0, codegen_1._) `new RegExp`;\nfunction usePattern({ gen, it: { opts } }, pattern) {\n const u = opts.unicodeRegExp ? \"u\" : \"\";\n const { regExp } = opts.code;\n const rx = regExp(pattern, u);\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: (0, codegen_1._) `${regExp.code === \"new RegExp\" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,\n });\n}\nexports.usePattern = usePattern;\nfunction validateArray(cxt) {\n const { gen, data, keyword, it } = cxt;\n const valid = gen.name(\"valid\");\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true);\n validateItems(() => gen.assign(validArr, false));\n return validArr;\n }\n gen.var(valid, true);\n validateItems(() => gen.break());\n return valid;\n function validateItems(notValid) {\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema({\n keyword,\n dataProp: i,\n dataPropType: util_1.Type.Num,\n }, valid);\n gen.if((0, codegen_1.not)(valid), notValid);\n });\n }\n}\nexports.validateArray = validateArray;\nfunction validateUnion(cxt) {\n const { gen, schema, keyword, it } = cxt;\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));\n if (alwaysValid && !it.opts.unevaluated)\n return;\n const valid = gen.let(\"valid\", false);\n const schValid = gen.name(\"_valid\");\n gen.block(() => schema.forEach((_sch, i) => {\n const schCxt = cxt.subschema({\n keyword,\n schemaProp: i,\n compositeRule: true,\n }, schValid);\n gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);\n const merged = cxt.mergeValidEvaluated(schCxt, schValid);\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged)\n gen.if((0, codegen_1.not)(valid));\n }));\n cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n}\nexports.validateUnion = validateUnion;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst code_1 = require(\"../../vocabularies/code\");\nconst errors_1 = require(\"../errors\");\nfunction macroKeywordCode(cxt, def) {\n const { gen, keyword, schema, parentSchema, it } = cxt;\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it);\n const schemaRef = useKeyword(gen, keyword, macroSchema);\n if (it.opts.validateSchema !== false)\n it.self.validateSchema(macroSchema, true);\n const valid = gen.name(\"valid\");\n cxt.subschema({\n schema: macroSchema,\n schemaPath: codegen_1.nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n }, valid);\n cxt.pass(valid, () => cxt.error(true));\n}\nexports.macroKeywordCode = macroKeywordCode;\nfunction funcKeywordCode(cxt, def) {\n var _a;\n const { gen, keyword, schema, parentSchema, $data, it } = cxt;\n checkAsyncKeyword(it, def);\n const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;\n const validateRef = useKeyword(gen, keyword, validate);\n const valid = gen.let(\"valid\");\n cxt.block$data(valid, validateKeyword);\n cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);\n function validateKeyword() {\n if (def.errors === false) {\n assignValid();\n if (def.modifying)\n modifyData(cxt);\n reportErrs(() => cxt.error());\n }\n else {\n const ruleErrs = def.async ? validateAsync() : validateSync();\n if (def.modifying)\n modifyData(cxt);\n reportErrs(() => addErrs(cxt, ruleErrs));\n }\n }\n function validateAsync() {\n const ruleErrs = gen.let(\"ruleErrs\", null);\n 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)));\n return ruleErrs;\n }\n function validateSync() {\n const validateErrs = (0, codegen_1._) `${validateRef}.errors`;\n gen.assign(validateErrs, null);\n assignValid(codegen_1.nil);\n return validateErrs;\n }\n function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {\n const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false);\n gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);\n }\n function reportErrs(errors) {\n var _a;\n gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);\n }\n}\nexports.funcKeywordCode = funcKeywordCode;\nfunction modifyData(cxt) {\n const { gen, data, it } = cxt;\n gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));\n}\nfunction addErrs(cxt, errs) {\n const { gen } = cxt;\n gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {\n gen\n .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)\n .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n (0, errors_1.extendErrors)(cxt);\n }, () => cxt.error());\n}\nfunction checkAsyncKeyword({ schemaEnv }, def) {\n if (def.async && !schemaEnv.$async)\n throw new Error(\"async keyword in sync schema\");\n}\nfunction useKeyword(gen, keyword, result) {\n if (result === undefined)\n throw new Error(`keyword \"${keyword}\" failed to compile`);\n return gen.scopeValue(\"keyword\", typeof result == \"function\" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });\n}\nfunction validSchemaType(schema, schemaType, allowUndefined = false) {\n // TODO add tests\n return (!schemaType.length ||\n schemaType.some((st) => st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")));\n}\nexports.validSchemaType = validSchemaType;\nfunction validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\");\n }\n const deps = def.dependencies;\n if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`);\n }\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword]);\n if (!valid) {\n const msg = `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors);\n if (opts.validateSchema === \"log\")\n self.logger.error(msg);\n else\n throw new Error(msg);\n }\n }\n}\nexports.validateKeywordUsage = validateKeywordUsage;\n//# sourceMappingURL=keyword.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed');\n }\n if (keyword !== undefined) {\n const sch = it.schema[keyword];\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,\n };\n }\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"');\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n };\n }\n throw new Error('either \"keyword\" or \"schema\" must be passed');\n}\nexports.getSubschema = getSubschema;\nfunction extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed');\n }\n const { gen } = it;\n if (dataProp !== undefined) {\n const { errorPath, dataPathArr, opts } = it;\n const nextData = gen.let(\"data\", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);\n dataContextProps(nextData);\n subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;\n subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];\n }\n if (data !== undefined) {\n const nextData = data instanceof codegen_1.Name ? data : gen.let(\"data\", data, true); // replaceable if used once?\n dataContextProps(nextData);\n if (propertyName !== undefined)\n subschema.propertyName = propertyName;\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n if (dataTypes)\n subschema.dataTypes = dataTypes;\n function dataContextProps(_nextData) {\n subschema.data = _nextData;\n subschema.dataLevel = it.dataLevel + 1;\n subschema.dataTypes = [];\n it.definedProperties = new Set();\n subschema.parentData = it.data;\n subschema.dataNames = [...it.dataNames, _nextData];\n }\n}\nexports.extendSubschemaData = extendSubschemaData;\nfunction extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {\n if (compositeRule !== undefined)\n subschema.compositeRule = compositeRule;\n if (createErrors !== undefined)\n subschema.createErrors = createErrors;\n if (allErrors !== undefined)\n subschema.allErrors = allErrors;\n subschema.jtdDiscriminator = jtdDiscriminator; // not inherited\n subschema.jtdMetadata = jtdMetadata; // not inherited\n}\nexports.extendSubschemaMode = extendSubschemaMode;\n//# sourceMappingURL=subschema.js.map","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i<sch.length; i++)\n _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n }\n } else if (key in traverse.propsKeywords) {\n if (sch && typeof sch == 'object') {\n for (var prop in sch)\n _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n }\n } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n }\n }\n post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n }\n}\n\n\nfunction escapeJsonPtr(str) {\n return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;\nconst util_1 = require(\"./util\");\nconst equal = require(\"fast-deep-equal\");\nconst traverse = require(\"json-schema-traverse\");\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n]);\nfunction inlineRef(schema, limit = true) {\n if (typeof schema == \"boolean\")\n return true;\n if (limit === true)\n return !hasRef(schema);\n if (!limit)\n return false;\n return countKeys(schema) <= limit;\n}\nexports.inlineRef = inlineRef;\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n]);\nfunction hasRef(schema) {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key))\n return true;\n const sch = schema[key];\n if (Array.isArray(sch) && sch.some(hasRef))\n return true;\n if (typeof sch == \"object\" && hasRef(sch))\n return true;\n }\n return false;\n}\nfunction countKeys(schema) {\n let count = 0;\n for (const key in schema) {\n if (key === \"$ref\")\n return Infinity;\n count++;\n if (SIMPLE_INLINED.has(key))\n continue;\n if (typeof schema[key] == \"object\") {\n (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));\n }\n if (count === Infinity)\n return Infinity;\n }\n return count;\n}\nfunction getFullPath(resolver, id = \"\", normalize) {\n if (normalize !== false)\n id = normalizeId(id);\n const p = resolver.parse(id);\n return _getFullPath(resolver, p);\n}\nexports.getFullPath = getFullPath;\nfunction _getFullPath(resolver, p) {\n const serialized = resolver.serialize(p);\n return serialized.split(\"#\")[0] + \"#\";\n}\nexports._getFullPath = _getFullPath;\nconst TRAILING_SLASH_HASH = /#\\/?$/;\nfunction normalizeId(id) {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\";\n}\nexports.normalizeId = normalizeId;\nfunction resolveUrl(resolver, baseId, id) {\n id = normalizeId(id);\n return resolver.resolve(baseId, id);\n}\nexports.resolveUrl = resolveUrl;\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i;\nfunction getSchemaRefs(schema, baseId) {\n if (typeof schema == \"boolean\")\n return {};\n const { schemaId, uriResolver } = this.opts;\n const schId = normalizeId(schema[schemaId] || baseId);\n const baseIds = { \"\": schId };\n const pathPrefix = getFullPath(uriResolver, schId, false);\n const localRefs = {};\n const schemaRefs = new Set();\n traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined)\n return;\n const fullPath = pathPrefix + jsonPtr;\n let innerBaseId = baseIds[parentJsonPtr];\n if (typeof sch[schemaId] == \"string\")\n innerBaseId = addRef.call(this, sch[schemaId]);\n addAnchor.call(this, sch.$anchor);\n addAnchor.call(this, sch.$dynamicAnchor);\n baseIds[jsonPtr] = innerBaseId;\n function addRef(ref) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve;\n ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);\n if (schemaRefs.has(ref))\n throw ambiguos(ref);\n schemaRefs.add(ref);\n let schOrRef = this.refs[ref];\n if (typeof schOrRef == \"string\")\n schOrRef = this.refs[schOrRef];\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref);\n }\n else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref);\n localRefs[ref] = sch;\n }\n else {\n this.refs[ref] = fullPath;\n }\n }\n return ref;\n }\n function addAnchor(anchor) {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor))\n throw new Error(`invalid anchor \"${anchor}\"`);\n addRef.call(this, `#${anchor}`);\n }\n }\n });\n return localRefs;\n function checkAmbiguosRef(sch1, sch2, ref) {\n if (sch2 !== undefined && !equal(sch1, sch2))\n throw ambiguos(ref);\n }\n function ambiguos(ref) {\n return new Error(`reference \"${ref}\" resolves to more than one schema`);\n }\n}\nexports.getSchemaRefs = getSchemaRefs;\n//# sourceMappingURL=resolve.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;\nconst boolSchema_1 = require(\"./boolSchema\");\nconst dataType_1 = require(\"./dataType\");\nconst applicability_1 = require(\"./applicability\");\nconst dataType_2 = require(\"./dataType\");\nconst defaults_1 = require(\"./defaults\");\nconst keyword_1 = require(\"./keyword\");\nconst subschema_1 = require(\"./subschema\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst resolve_1 = require(\"../resolve\");\nconst util_1 = require(\"../util\");\nconst errors_1 = require(\"../errors\");\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nfunction validateFunctionCode(it) {\n if (isSchemaObj(it)) {\n checkKeywords(it);\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it);\n return;\n }\n }\n validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));\n}\nexports.validateFunctionCode = validateFunctionCode;\nfunction validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {\n if (opts.code.es5) {\n gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {\n gen.code((0, codegen_1._) `\"use strict\"; ${funcSourceUrl(schema, opts)}`);\n destructureValCxtES5(gen, opts);\n gen.code(body);\n });\n }\n else {\n gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));\n }\n}\nfunction destructureValCxt(opts) {\n 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}}={}`;\n}\nfunction destructureValCxtES5(gen, opts) {\n gen.if(names_1.default.valCxt, () => {\n gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);\n gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);\n gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);\n gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);\n if (opts.dynamicRef)\n gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);\n }, () => {\n gen.var(names_1.default.instancePath, (0, codegen_1._) `\"\"`);\n gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);\n gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);\n gen.var(names_1.default.rootData, names_1.default.data);\n if (opts.dynamicRef)\n gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);\n });\n}\nfunction topSchemaObjCode(it) {\n const { schema, opts, gen } = it;\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment)\n commentKeyword(it);\n checkNoDefault(it);\n gen.let(names_1.default.vErrors, null);\n gen.let(names_1.default.errors, 0);\n if (opts.unevaluated)\n resetEvaluated(it);\n typeAndKeywords(it);\n returnResults(it);\n });\n return;\n}\nfunction resetEvaluated(it) {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const { gen, validateName } = it;\n it.evaluated = gen.const(\"evaluated\", (0, codegen_1._) `${validateName}.evaluated`);\n gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));\n gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));\n}\nfunction funcSourceUrl(schema, opts) {\n const schId = typeof schema == \"object\" && schema[opts.schemaId];\n return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;\n}\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it, valid) {\n if (isSchemaObj(it)) {\n checkKeywords(it);\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid);\n return;\n }\n }\n (0, boolSchema_1.boolOrEmptySchema)(it, valid);\n}\nfunction schemaCxtHasRules({ schema, self }) {\n if (typeof schema == \"boolean\")\n return !schema;\n for (const key in schema)\n if (self.RULES.all[key])\n return true;\n return false;\n}\nfunction isSchemaObj(it) {\n return typeof it.schema != \"boolean\";\n}\nfunction subSchemaObjCode(it, valid) {\n const { schema, gen, opts } = it;\n if (opts.$comment && schema.$comment)\n commentKeyword(it);\n updateContext(it);\n checkAsyncSchema(it);\n const errsCount = gen.const(\"_errs\", names_1.default.errors);\n typeAndKeywords(it, errsCount);\n // TODO var\n gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n}\nfunction checkKeywords(it) {\n (0, util_1.checkUnknownRules)(it);\n checkRefsAndKeywords(it);\n}\nfunction typeAndKeywords(it, errsCount) {\n if (it.opts.jtd)\n return schemaKeywords(it, [], false, errsCount);\n const types = (0, dataType_1.getSchemaTypes)(it.schema);\n const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);\n schemaKeywords(it, types, !checkedTypes, errsCount);\n}\nfunction checkRefsAndKeywords(it) {\n const { schema, errSchemaPath, opts, self } = it;\n if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`);\n }\n}\nfunction checkNoDefault(it) {\n const { schema, opts } = it;\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n (0, util_1.checkStrictMode)(it, \"default is ignored in the schema root\");\n }\n}\nfunction updateContext(it) {\n const schId = it.schema[it.opts.schemaId];\n if (schId)\n it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);\n}\nfunction checkAsyncSchema(it) {\n if (it.schema.$async && !it.schemaEnv.$async)\n throw new Error(\"async schema in sync schema\");\n}\nfunction commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {\n const msg = schema.$comment;\n if (opts.$comment === true) {\n gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);\n }\n else if (typeof opts.$comment == \"function\") {\n const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;\n const rootName = gen.scopeValue(\"root\", { ref: schemaEnv.root });\n gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);\n }\n}\nfunction returnResults(it) {\n const { gen, schemaEnv, validateName, ValidationError, opts } = it;\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n 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})`));\n }\n else {\n gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);\n if (opts.unevaluated)\n assignEvaluated(it);\n gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);\n }\n}\nfunction assignEvaluated({ gen, evaluated, props, items }) {\n if (props instanceof codegen_1.Name)\n gen.assign((0, codegen_1._) `${evaluated}.props`, props);\n if (items instanceof codegen_1.Name)\n gen.assign((0, codegen_1._) `${evaluated}.items`, items);\n}\nfunction schemaKeywords(it, types, typeErrors, errsCount) {\n const { gen, schema, data, allErrors, opts, self } = it;\n const { RULES } = self;\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", RULES.all.$ref.definition)); // TODO typecast\n return;\n }\n if (!opts.jtd)\n checkStrictTypes(it, types);\n gen.block(() => {\n for (const group of RULES.rules)\n groupKeywords(group);\n groupKeywords(RULES.post);\n });\n function groupKeywords(group) {\n if (!(0, applicability_1.shouldUseGroup)(schema, group))\n return;\n if (group.type) {\n gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));\n iterateKeywords(it, group);\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else();\n (0, dataType_2.reportTypeError)(it);\n }\n gen.endIf();\n }\n else {\n iterateKeywords(it, group);\n }\n // TODO make it \"ok\" call?\n if (!allErrors)\n gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);\n }\n}\nfunction iterateKeywords(it, group) {\n const { gen, schema, opts: { useDefaults }, } = it;\n if (useDefaults)\n (0, defaults_1.assignDefaults)(it, group.type);\n gen.block(() => {\n for (const rule of group.rules) {\n if ((0, applicability_1.shouldUseRule)(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type);\n }\n }\n });\n}\nfunction checkStrictTypes(it, types) {\n if (it.schemaEnv.meta || !it.opts.strictTypes)\n return;\n checkContextTypes(it, types);\n if (!it.opts.allowUnionTypes)\n checkMultipleTypes(it, types);\n checkKeywordTypes(it, it.dataTypes);\n}\nfunction checkContextTypes(it, types) {\n if (!types.length)\n return;\n if (!it.dataTypes.length) {\n it.dataTypes = types;\n return;\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`);\n }\n });\n narrowSchemaTypes(it, types);\n}\nfunction checkMultipleTypes(it, ts) {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\");\n }\n}\nfunction checkKeywordTypes(it, ts) {\n const rules = it.self.RULES.all;\n for (const keyword in rules) {\n const rule = rules[keyword];\n if (typeof rule == \"object\" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {\n const { type } = rule.definition;\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`);\n }\n }\n }\n}\nfunction hasApplicableType(schTs, kwdT) {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"));\n}\nfunction includesType(ts, t) {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"));\n}\nfunction narrowSchemaTypes(it, withTypes) {\n const ts = [];\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t))\n ts.push(t);\n else if (withTypes.includes(\"integer\") && t === \"number\")\n ts.push(\"integer\");\n }\n it.dataTypes = ts;\n}\nfunction strictTypesError(it, msg) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n msg += ` at \"${schemaPath}\" (strictTypes)`;\n (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);\n}\nclass KeywordCxt {\n constructor(it, def, keyword) {\n (0, keyword_1.validateKeywordUsage)(it, def, keyword);\n this.gen = it.gen;\n this.allErrors = it.allErrors;\n this.keyword = keyword;\n this.data = it.data;\n this.schema = it.schema[keyword];\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;\n this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);\n this.schemaType = def.schemaType;\n this.parentSchema = it.schema;\n this.params = {};\n this.it = it;\n this.def = def;\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it));\n }\n else {\n this.schemaCode = this.schemaValue;\n if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);\n }\n }\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", names_1.default.errors);\n }\n }\n result(condition, successAction, failAction) {\n this.failResult((0, codegen_1.not)(condition), successAction, failAction);\n }\n failResult(condition, successAction, failAction) {\n this.gen.if(condition);\n if (failAction)\n failAction();\n else\n this.error();\n if (successAction) {\n this.gen.else();\n successAction();\n if (this.allErrors)\n this.gen.endIf();\n }\n else {\n if (this.allErrors)\n this.gen.endIf();\n else\n this.gen.else();\n }\n }\n pass(condition, failAction) {\n this.failResult((0, codegen_1.not)(condition), undefined, failAction);\n }\n fail(condition) {\n if (condition === undefined) {\n this.error();\n if (!this.allErrors)\n this.gen.if(false); // this branch will be removed by gen.optimize\n return;\n }\n this.gen.if(condition);\n this.error();\n if (this.allErrors)\n this.gen.endIf();\n else\n this.gen.else();\n }\n fail$data(condition) {\n if (!this.$data)\n return this.fail(condition);\n const { schemaCode } = this;\n this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);\n }\n error(append, errorParams, errorPaths) {\n if (errorParams) {\n this.setParams(errorParams);\n this._error(append, errorPaths);\n this.setParams({});\n return;\n }\n this._error(append, errorPaths);\n }\n _error(append, errorPaths) {\n ;\n (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);\n }\n $dataError() {\n (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);\n }\n reset() {\n if (this.errsCount === undefined)\n throw new Error('add \"trackErrors\" to keyword definition');\n (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);\n }\n ok(cond) {\n if (!this.allErrors)\n this.gen.if(cond);\n }\n setParams(obj, assign) {\n if (assign)\n Object.assign(this.params, obj);\n else\n this.params = obj;\n }\n block$data(valid, codeBlock, $dataValid = codegen_1.nil) {\n this.gen.block(() => {\n this.check$data(valid, $dataValid);\n codeBlock();\n });\n }\n check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {\n if (!this.$data)\n return;\n const { gen, schemaCode, schemaType, def } = this;\n gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));\n if (valid !== codegen_1.nil)\n gen.assign(valid, true);\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data());\n this.$dataError();\n if (valid !== codegen_1.nil)\n gen.assign(valid, false);\n }\n gen.else();\n }\n invalid$data() {\n const { gen, schemaCode, schemaType, def, it } = this;\n return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());\n function wrong$DataType() {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof codegen_1.Name))\n throw new Error(\"ajv implementation error\");\n const st = Array.isArray(schemaType) ? schemaType : [schemaType];\n return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;\n }\n return codegen_1.nil;\n }\n function invalid$DataSchema() {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", { ref: def.validateSchema }); // TODO value.code for standalone\n return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;\n }\n return codegen_1.nil;\n }\n }\n subschema(appl, valid) {\n const subschema = (0, subschema_1.getSubschema)(this.it, appl);\n (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);\n (0, subschema_1.extendSubschemaMode)(subschema, appl);\n const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };\n subschemaCode(nextContext, valid);\n return nextContext;\n }\n mergeEvaluated(schemaCxt, toName) {\n const { it, gen } = this;\n if (!it.opts.unevaluated)\n return;\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);\n }\n }\n mergeValidEvaluated(schemaCxt, valid) {\n const { it, gen } = this;\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));\n return true;\n }\n }\n}\nexports.KeywordCxt = KeywordCxt;\nfunction keywordCode(it, keyword, def, ruleType) {\n const cxt = new KeywordCxt(it, def, keyword);\n if (\"code\" in def) {\n def.code(cxt, ruleType);\n }\n else if (cxt.$data && def.validate) {\n (0, keyword_1.funcKeywordCode)(cxt, def);\n }\n else if (\"macro\" in def) {\n (0, keyword_1.macroKeywordCode)(cxt, def);\n }\n else if (def.compile || def.validate) {\n (0, keyword_1.funcKeywordCode)(cxt, def);\n }\n}\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/;\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/;\nfunction getData($data, { dataLevel, dataNames, dataPathArr }) {\n let jsonPointer;\n let data;\n if ($data === \"\")\n return names_1.default.rootData;\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data))\n throw new Error(`Invalid JSON-pointer: ${$data}`);\n jsonPointer = $data;\n data = names_1.default.rootData;\n }\n else {\n const matches = RELATIVE_JSON_POINTER.exec($data);\n if (!matches)\n throw new Error(`Invalid JSON-pointer: ${$data}`);\n const up = +matches[1];\n jsonPointer = matches[2];\n if (jsonPointer === \"#\") {\n if (up >= dataLevel)\n throw new Error(errorMsg(\"property/index\", up));\n return dataPathArr[dataLevel - up];\n }\n if (up > dataLevel)\n throw new Error(errorMsg(\"data\", up));\n data = dataNames[dataLevel - up];\n if (!jsonPointer)\n return data;\n }\n let expr = data;\n const segments = jsonPointer.split(\"/\");\n for (const segment of segments) {\n if (segment) {\n data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;\n expr = (0, codegen_1._) `${expr} && ${data}`;\n }\n }\n return expr;\n function errorMsg(pointerType, up) {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;\n }\n}\nexports.getData = getData;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass ValidationError extends Error {\n constructor(errors) {\n super(\"validation failed\");\n this.errors = errors;\n this.ajv = this.validation = true;\n }\n}\nexports.default = ValidationError;\n//# sourceMappingURL=validation_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst resolve_1 = require(\"./resolve\");\nclass MissingRefError extends Error {\n constructor(resolver, baseId, ref, msg) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`);\n this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);\n this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));\n }\n}\nexports.default = MissingRefError;\n//# sourceMappingURL=ref_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst validation_error_1 = require(\"../runtime/validation_error\");\nconst names_1 = require(\"./names\");\nconst resolve_1 = require(\"./resolve\");\nconst util_1 = require(\"./util\");\nconst validate_1 = require(\"./validate\");\nclass SchemaEnv {\n constructor(env) {\n var _a;\n this.refs = {};\n this.dynamicAnchors = {};\n let schema;\n if (typeof env.schema == \"object\")\n schema = env.schema;\n this.schema = env.schema;\n this.schemaId = env.schemaId;\n this.root = env.root || this;\n this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || \"$id\"]);\n this.schemaPath = env.schemaPath;\n this.localRefs = env.localRefs;\n this.meta = env.meta;\n this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;\n this.refs = {};\n }\n}\nexports.SchemaEnv = SchemaEnv;\n// let codeSize = 0\n// let nodeCount = 0\n// Compiles schema in SchemaEnv\nfunction compileSchema(sch) {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch);\n if (_sch)\n return _sch;\n const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails\n const { es5, lines } = this.opts.code;\n const { ownProperties } = this.opts;\n const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });\n let _ValidationError;\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: validation_error_1.default,\n code: (0, codegen_1._) `require(\"ajv/dist/runtime/validation_error\").default`,\n });\n }\n const validateName = gen.scopeName(\"validate\");\n sch.validateName = validateName;\n const schemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: names_1.default.data,\n parentData: names_1.default.parentData,\n parentDataProperty: names_1.default.parentDataProperty,\n dataNames: [names_1.default.data],\n dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set(),\n topSchemaRef: gen.scopeValue(\"schema\", this.opts.code.source === true\n ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }\n : { ref: sch.schema }),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: codegen_1.nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: (0, codegen_1._) `\"\"`,\n opts: this.opts,\n self: this,\n };\n let sourceCode;\n try {\n this._compilations.add(sch);\n (0, validate_1.validateFunctionCode)(schemaCxt);\n gen.optimize(this.opts.code.optimize);\n // gen.optimize(1)\n const validateCode = gen.toString();\n sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process)\n sourceCode = this.opts.code.process(sourceCode, sch);\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);\n const validate = makeValidate(this, this.scope.get());\n this.scope.value(validateName, { ref: validate });\n validate.errors = null;\n validate.schema = sch.schema;\n validate.schemaEnv = sch;\n if (sch.$async)\n validate.$async = true;\n if (this.opts.code.source === true) {\n validate.source = { validateName, validateCode, scopeValues: gen._values };\n }\n if (this.opts.unevaluated) {\n const { props, items } = schemaCxt;\n validate.evaluated = {\n props: props instanceof codegen_1.Name ? undefined : props,\n items: items instanceof codegen_1.Name ? undefined : items,\n dynamicProps: props instanceof codegen_1.Name,\n dynamicItems: items instanceof codegen_1.Name,\n };\n if (validate.source)\n validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);\n }\n sch.validate = validate;\n return sch;\n }\n catch (e) {\n delete sch.validate;\n delete sch.validateName;\n if (sourceCode)\n this.logger.error(\"Error compiling schema, function code:\", sourceCode);\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e;\n }\n finally {\n this._compilations.delete(sch);\n }\n}\nexports.compileSchema = compileSchema;\nfunction resolveRef(root, baseId, ref) {\n var _a;\n ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);\n const schOrFunc = root.refs[ref];\n if (schOrFunc)\n return schOrFunc;\n let _sch = resolve.call(this, root, ref);\n if (_sch === undefined) {\n const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv\n const { schemaId } = this.opts;\n if (schema)\n _sch = new SchemaEnv({ schema, schemaId, root, baseId });\n }\n if (_sch === undefined)\n return;\n return (root.refs[ref] = inlineOrCompile.call(this, _sch));\n}\nexports.resolveRef = resolveRef;\nfunction inlineOrCompile(sch) {\n if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))\n return sch.schema;\n return sch.validate ? sch : compileSchema.call(this, sch);\n}\n// Index of schema compilation in the currently compiled list\nfunction getCompilingSchema(schEnv) {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv))\n return sch;\n }\n}\nexports.getCompilingSchema = getCompilingSchema;\nfunction sameSchemaEnv(s1, s2) {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;\n}\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(root, // information about the root schema for the current schema\nref // reference to resolve\n) {\n let sch;\n while (typeof (sch = this.refs[ref]) == \"string\")\n ref = sch;\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);\n}\n// Resolve schema, its root and baseId\nfunction resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\nref // reference to resolve\n) {\n const p = this.opts.uriResolver.parse(ref);\n const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);\n let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root);\n }\n const id = (0, resolve_1.normalizeId)(refPath);\n const schOrRef = this.refs[id] || this.schemas[id];\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef);\n if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== \"object\")\n return;\n return getJsonPointer.call(this, p, sch);\n }\n if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== \"object\")\n return;\n if (!schOrRef.validate)\n compileSchema.call(this, schOrRef);\n if (id === (0, resolve_1.normalizeId)(ref)) {\n const { schema } = schOrRef;\n const { schemaId } = this.opts;\n const schId = schema[schemaId];\n if (schId)\n baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n return new SchemaEnv({ schema, schemaId, root, baseId });\n }\n return getJsonPointer.call(this, p, schOrRef);\n}\nexports.resolveSchema = resolveSchema;\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n]);\nfunction getJsonPointer(parsedRef, { baseId, schema, root }) {\n var _a;\n if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== \"/\")\n return;\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\")\n return;\n const partSchema = schema[(0, util_1.unescapeFragment)(part)];\n if (partSchema === undefined)\n return;\n schema = partSchema;\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId];\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n }\n }\n let env;\n if (typeof schema != \"boolean\" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {\n const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);\n env = resolveSchema.call(this, root, $ref);\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const { schemaId } = this.opts;\n env = env || new SchemaEnv({ schema, schemaId, root, baseId });\n if (env.schema !== env.root.schema)\n return env;\n return undefined;\n}\n//# sourceMappingURL=index.js.map","","'use strict'\n\n/** @type {(value: string) => boolean} */\nconst isUUID = RegExp.prototype.test.bind(/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst 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)\n\n/**\n * @param {Array<string>} input\n * @returns {string}\n */\nfunction stringArrayToHexStripped (input) {\n let acc = ''\n let code = 0\n let i = 0\n\n for (i = 0; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (code === 48) {\n continue\n }\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n break\n }\n\n for (i += 1; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n }\n return acc\n}\n\n/**\n * @typedef {Object} GetIPV6Result\n * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.\n * @property {string} address - The parsed IPv6 address.\n * @property {string} [zone] - The zone identifier, if present.\n */\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nconst nonSimpleDomain = RegExp.prototype.test.bind(/[^!\"$&'()*+,\\-.;=_`a-z{}~]/u)\n\n/**\n * @param {Array<string>} buffer\n * @returns {boolean}\n */\nfunction consumeIsZone (buffer) {\n buffer.length = 0\n return true\n}\n\n/**\n * @param {Array<string>} buffer\n * @param {Array<string>} address\n * @param {GetIPV6Result} output\n * @returns {boolean}\n */\nfunction consumeHextets (buffer, address, output) {\n if (buffer.length) {\n const hex = stringArrayToHexStripped(buffer)\n if (hex !== '') {\n address.push(hex)\n } else {\n output.error = true\n return false\n }\n buffer.length = 0\n }\n return true\n}\n\n/**\n * @param {string} input\n * @returns {GetIPV6Result}\n */\nfunction getIPV6 (input) {\n let tokenCount = 0\n const output = { error: false, address: '', zone: '' }\n /** @type {Array<string>} */\n const address = []\n /** @type {Array<string>} */\n const buffer = []\n let endipv6Encountered = false\n let endIpv6 = false\n\n let consume = consumeHextets\n\n for (let i = 0; i < input.length; i++) {\n const cursor = input[i]\n if (cursor === '[' || cursor === ']') { continue }\n if (cursor === ':') {\n if (endipv6Encountered === true) {\n endIpv6 = true\n }\n if (!consume(buffer, address, output)) { break }\n if (++tokenCount > 7) {\n // not valid\n output.error = true\n break\n }\n if (i > 0 && input[i - 1] === ':') {\n endipv6Encountered = true\n }\n address.push(':')\n continue\n } else if (cursor === '%') {\n if (!consume(buffer, address, output)) { break }\n // switch to zone detection\n consume = consumeIsZone\n } else {\n buffer.push(cursor)\n continue\n }\n }\n if (buffer.length) {\n if (consume === consumeIsZone) {\n output.zone = buffer.join('')\n } else if (endIpv6) {\n address.push(buffer.join(''))\n } else {\n address.push(stringArrayToHexStripped(buffer))\n }\n }\n output.address = address.join('')\n return output\n}\n\n/**\n * @typedef {Object} NormalizeIPv6Result\n * @property {string} host - The normalized host.\n * @property {string} [escapedHost] - The escaped host.\n * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.\n */\n\n/**\n * @param {string} host\n * @returns {NormalizeIPv6Result}\n */\nfunction normalizeIPv6 (host) {\n if (findToken(host, ':') < 2) { return { host, isIPV6: false } }\n const ipv6 = getIPV6(host)\n\n if (!ipv6.error) {\n let newHost = ipv6.address\n let escapedHost = ipv6.address\n if (ipv6.zone) {\n newHost += '%' + ipv6.zone\n escapedHost += '%25' + ipv6.zone\n }\n return { host: newHost, isIPV6: true, escapedHost }\n } else {\n return { host, isIPV6: false }\n }\n}\n\n/**\n * @param {string} str\n * @param {string} token\n * @returns {number}\n */\nfunction findToken (str, token) {\n let ind = 0\n for (let i = 0; i < str.length; i++) {\n if (str[i] === token) ind++\n }\n return ind\n}\n\n/**\n * @param {string} path\n * @returns {string}\n *\n * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n */\nfunction removeDotSegments (path) {\n let input = path\n const output = []\n let nextSlash = -1\n let len = 0\n\n // eslint-disable-next-line no-cond-assign\n while (len = input.length) {\n if (len === 1) {\n if (input === '.') {\n break\n } else if (input === '/') {\n output.push('/')\n break\n } else {\n output.push(input)\n break\n }\n } else if (len === 2) {\n if (input[0] === '.') {\n if (input[1] === '.') {\n break\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.' || input[1] === '/') {\n output.push('/')\n break\n }\n }\n } else if (len === 3) {\n if (input === '/..') {\n if (output.length !== 0) {\n output.pop()\n }\n output.push('/')\n break\n }\n }\n if (input[0] === '.') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(3)\n continue\n }\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(2)\n continue\n } else if (input[2] === '.') {\n if (input[3] === '/') {\n input = input.slice(3)\n if (output.length !== 0) {\n output.pop()\n }\n continue\n }\n }\n }\n }\n\n // Rule 2E: Move normal path segment to output\n if ((nextSlash = input.indexOf('/', 1)) === -1) {\n output.push(input)\n break\n } else {\n output.push(input.slice(0, nextSlash))\n input = input.slice(nextSlash)\n }\n }\n\n return output.join('')\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @param {boolean} esc\n * @returns {import('../types/index').URIComponent}\n */\nfunction normalizeComponentEncoding (component, esc) {\n const func = esc !== true ? escape : unescape\n if (component.scheme !== undefined) {\n component.scheme = func(component.scheme)\n }\n if (component.userinfo !== undefined) {\n component.userinfo = func(component.userinfo)\n }\n if (component.host !== undefined) {\n component.host = func(component.host)\n }\n if (component.path !== undefined) {\n component.path = func(component.path)\n }\n if (component.query !== undefined) {\n component.query = func(component.query)\n }\n if (component.fragment !== undefined) {\n component.fragment = func(component.fragment)\n }\n return component\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @returns {string|undefined}\n */\nfunction recomposeAuthority (component) {\n const uriTokens = []\n\n if (component.userinfo !== undefined) {\n uriTokens.push(component.userinfo)\n uriTokens.push('@')\n }\n\n if (component.host !== undefined) {\n let host = unescape(component.host)\n if (!isIPv4(host)) {\n const ipV6res = normalizeIPv6(host)\n if (ipV6res.isIPV6 === true) {\n host = `[${ipV6res.escapedHost}]`\n } else {\n host = component.host\n }\n }\n uriTokens.push(host)\n }\n\n if (typeof component.port === 'number' || typeof component.port === 'string') {\n uriTokens.push(':')\n uriTokens.push(String(component.port))\n }\n\n return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n nonSimpleDomain,\n recomposeAuthority,\n normalizeComponentEncoding,\n removeDotSegments,\n isIPv4,\n isUUID,\n normalizeIPv6,\n stringArrayToHexStripped\n}\n","'use strict'\n\nconst { isUUID } = require('./utils')\nconst URN_REG = /([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-.:;=@]|%[\\da-f]{2})+)/iu\n\nconst supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',\n 'wss', 'urn', 'urn:uuid'])\n\n/** @typedef {supportedSchemeNames[number]} SchemeName */\n\n/**\n * @param {string} name\n * @returns {name is SchemeName}\n */\nfunction isValidSchemeName (name) {\n return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1\n}\n\n/**\n * @callback SchemeFn\n * @param {import('../types/index').URIComponent} component\n * @param {import('../types/index').Options} options\n * @returns {import('../types/index').URIComponent}\n */\n\n/**\n * @typedef {Object} SchemeHandler\n * @property {SchemeName} scheme - The scheme name.\n * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.\n * @property {SchemeFn} parse - Function to parse the URI component for this scheme.\n * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.\n * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.\n * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.\n * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.\n */\n\n/**\n * @param {import('../types/index').URIComponent} wsComponent\n * @returns {boolean}\n */\nfunction wsIsSecure (wsComponent) {\n if (wsComponent.secure === true) {\n return true\n } else if (wsComponent.secure === false) {\n return false\n } else if (wsComponent.scheme) {\n return (\n wsComponent.scheme.length === 3 &&\n (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&\n (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&\n (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')\n )\n } else {\n return false\n }\n}\n\n/** @type {SchemeFn} */\nfunction httpParse (component) {\n if (!component.host) {\n component.error = component.error || 'HTTP URIs must have a host.'\n }\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction httpSerialize (component) {\n const secure = String(component.scheme).toLowerCase() === 'https'\n\n // normalize the default port\n if (component.port === (secure ? 443 : 80) || component.port === '') {\n component.port = undefined\n }\n\n // normalize the empty path\n if (!component.path) {\n component.path = '/'\n }\n\n // NOTE: We do not parse query strings for HTTP URIs\n // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n // and not the HTTP spec.\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction wsParse (wsComponent) {\n// indicate if the secure flag is set\n wsComponent.secure = wsIsSecure(wsComponent)\n\n // construct resouce name\n wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')\n wsComponent.path = undefined\n wsComponent.query = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction wsSerialize (wsComponent) {\n// normalize the default port\n if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {\n wsComponent.port = undefined\n }\n\n // ensure scheme matches secure flag\n if (typeof wsComponent.secure === 'boolean') {\n wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')\n wsComponent.secure = undefined\n }\n\n // reconstruct path from resource name\n if (wsComponent.resourceName) {\n const [path, query] = wsComponent.resourceName.split('?')\n wsComponent.path = (path && path !== '/' ? path : undefined)\n wsComponent.query = query\n wsComponent.resourceName = undefined\n }\n\n // forbid fragment component\n wsComponent.fragment = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnParse (urnComponent, options) {\n if (!urnComponent.path) {\n urnComponent.error = 'URN can not be parsed'\n return urnComponent\n }\n const matches = urnComponent.path.match(URN_REG)\n if (matches) {\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n urnComponent.nid = matches[1].toLowerCase()\n urnComponent.nss = matches[2]\n const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n urnComponent.path = undefined\n\n if (schemeHandler) {\n urnComponent = schemeHandler.parse(urnComponent, options)\n }\n } else {\n urnComponent.error = urnComponent.error || 'URN can not be parsed.'\n }\n\n return urnComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnSerialize (urnComponent, options) {\n if (urnComponent.nid === undefined) {\n throw new Error('URN without nid cannot be serialized')\n }\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n const nid = urnComponent.nid.toLowerCase()\n const urnScheme = `${scheme}:${options.nid || nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n\n if (schemeHandler) {\n urnComponent = schemeHandler.serialize(urnComponent, options)\n }\n\n const uriComponent = urnComponent\n const nss = urnComponent.nss\n uriComponent.path = `${nid || options.nid}:${nss}`\n\n options.skipEscape = true\n return uriComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidParse (urnComponent, options) {\n const uuidComponent = urnComponent\n uuidComponent.uuid = uuidComponent.nss\n uuidComponent.nss = undefined\n\n if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {\n uuidComponent.error = uuidComponent.error || 'UUID is not valid.'\n }\n\n return uuidComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidSerialize (uuidComponent) {\n const urnComponent = uuidComponent\n // normalize UUID\n urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()\n return urnComponent\n}\n\nconst http = /** @type {SchemeHandler} */ ({\n scheme: 'http',\n domainHost: true,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst https = /** @type {SchemeHandler} */ ({\n scheme: 'https',\n domainHost: http.domainHost,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst ws = /** @type {SchemeHandler} */ ({\n scheme: 'ws',\n domainHost: true,\n parse: wsParse,\n serialize: wsSerialize\n})\n\nconst wss = /** @type {SchemeHandler} */ ({\n scheme: 'wss',\n domainHost: ws.domainHost,\n parse: ws.parse,\n serialize: ws.serialize\n})\n\nconst urn = /** @type {SchemeHandler} */ ({\n scheme: 'urn',\n parse: urnParse,\n serialize: urnSerialize,\n skipNormalize: true\n})\n\nconst urnuuid = /** @type {SchemeHandler} */ ({\n scheme: 'urn:uuid',\n parse: urnuuidParse,\n serialize: urnuuidSerialize,\n skipNormalize: true\n})\n\nconst SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({\n http,\n https,\n ws,\n wss,\n urn,\n 'urn:uuid': urnuuid\n})\n\nObject.setPrototypeOf(SCHEMES, null)\n\n/**\n * @param {string|undefined} scheme\n * @returns {SchemeHandler|undefined}\n */\nfunction getSchemeHandler (scheme) {\n return (\n scheme && (\n SCHEMES[/** @type {SchemeName} */ (scheme)] ||\n SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])\n ) ||\n undefined\n}\n\nmodule.exports = {\n wsIsSecure,\n SCHEMES,\n isValidSchemeName,\n getSchemeHandler,\n}\n","'use strict'\n\nconst { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require('./lib/utils')\nconst { SCHEMES, getSchemeHandler } = require('./lib/schemes')\n\n/**\n * @template {import('./types/index').URIComponent|string} T\n * @param {T} uri\n * @param {import('./types/index').Options} [options]\n * @returns {T}\n */\nfunction normalize (uri, options) {\n if (typeof uri === 'string') {\n uri = /** @type {T} */ (serialize(parse(uri, options), options))\n } else if (typeof uri === 'object') {\n uri = /** @type {T} */ (parse(serialize(uri, options), options))\n }\n return uri\n}\n\n/**\n * @param {string} baseURI\n * @param {string} relativeURI\n * @param {import('./types/index').Options} [options]\n * @returns {string}\n */\nfunction resolve (baseURI, relativeURI, options) {\n const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }\n const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)\n schemelessOptions.skipEscape = true\n return serialize(resolved, schemelessOptions)\n}\n\n/**\n * @param {import ('./types/index').URIComponent} base\n * @param {import ('./types/index').URIComponent} relative\n * @param {import('./types/index').Options} [options]\n * @param {boolean} [skipNormalization=false]\n * @returns {import ('./types/index').URIComponent}\n */\nfunction resolveComponent (base, relative, options, skipNormalization) {\n /** @type {import('./types/index').URIComponent} */\n const target = {}\n if (!skipNormalization) {\n base = parse(serialize(base, options), options) // normalize base component\n relative = parse(serialize(relative, options), options) // normalize relative component\n }\n options = options || {}\n\n if (!options.tolerant && relative.scheme) {\n target.scheme = relative.scheme\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (!relative.path) {\n target.path = base.path\n if (relative.query !== undefined) {\n target.query = relative.query\n } else {\n target.query = base.query\n }\n } else {\n if (relative.path[0] === '/') {\n target.path = removeDotSegments(relative.path)\n } else {\n if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n target.path = '/' + relative.path\n } else if (!base.path) {\n target.path = relative.path\n } else {\n target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n }\n target.path = removeDotSegments(target.path)\n }\n target.query = relative.query\n }\n // target.authority = base.authority;\n target.userinfo = base.userinfo\n target.host = base.host\n target.port = base.port\n }\n target.scheme = base.scheme\n }\n\n target.fragment = relative.fragment\n\n return target\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uriA\n * @param {import ('./types/index').URIComponent|string} uriB\n * @param {import ('./types/index').Options} options\n * @returns {boolean}\n */\nfunction equal (uriA, uriB, options) {\n if (typeof uriA === 'string') {\n uriA = unescape(uriA)\n uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true })\n } else if (typeof uriA === 'object') {\n uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true })\n }\n\n if (typeof uriB === 'string') {\n uriB = unescape(uriB)\n uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true })\n } else if (typeof uriB === 'object') {\n uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true })\n }\n\n return uriA.toLowerCase() === uriB.toLowerCase()\n}\n\n/**\n * @param {Readonly<import('./types/index').URIComponent>} cmpts\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction serialize (cmpts, opts) {\n const component = {\n host: cmpts.host,\n scheme: cmpts.scheme,\n userinfo: cmpts.userinfo,\n port: cmpts.port,\n path: cmpts.path,\n query: cmpts.query,\n nid: cmpts.nid,\n nss: cmpts.nss,\n uuid: cmpts.uuid,\n fragment: cmpts.fragment,\n reference: cmpts.reference,\n resourceName: cmpts.resourceName,\n secure: cmpts.secure,\n error: ''\n }\n const options = Object.assign({}, opts)\n const uriTokens = []\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || component.scheme)\n\n // perform scheme specific serialization\n if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)\n\n if (component.path !== undefined) {\n if (!options.skipEscape) {\n component.path = escape(component.path)\n\n if (component.scheme !== undefined) {\n component.path = component.path.split('%3A').join(':')\n }\n } else {\n component.path = unescape(component.path)\n }\n }\n\n if (options.reference !== 'suffix' && component.scheme) {\n uriTokens.push(component.scheme, ':')\n }\n\n const authority = recomposeAuthority(component)\n if (authority !== undefined) {\n if (options.reference !== 'suffix') {\n uriTokens.push('//')\n }\n\n uriTokens.push(authority)\n\n if (component.path && component.path[0] !== '/') {\n uriTokens.push('/')\n }\n }\n if (component.path !== undefined) {\n let s = component.path\n\n if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n s = removeDotSegments(s)\n }\n\n if (\n authority === undefined &&\n s[0] === '/' &&\n s[1] === '/'\n ) {\n // don't allow the path to start with \"//\"\n s = '/%2F' + s.slice(2)\n }\n\n uriTokens.push(s)\n }\n\n if (component.query !== undefined) {\n uriTokens.push('?', component.query)\n }\n\n if (component.fragment !== undefined) {\n uriTokens.push('#', component.fragment)\n }\n return uriTokens.join('')\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns\n */\nfunction parse (uri, opts) {\n const options = Object.assign({}, opts)\n /** @type {import('./types/index').URIComponent} */\n const parsed = {\n scheme: undefined,\n userinfo: undefined,\n host: '',\n port: undefined,\n path: '',\n query: undefined,\n fragment: undefined\n }\n\n let isIP = false\n if (options.reference === 'suffix') {\n if (options.scheme) {\n uri = options.scheme + ':' + uri\n } else {\n uri = '//' + uri\n }\n }\n\n const matches = uri.match(URI_PARSE)\n\n if (matches) {\n // store each component\n parsed.scheme = matches[1]\n parsed.userinfo = matches[3]\n parsed.host = matches[4]\n parsed.port = parseInt(matches[5], 10)\n parsed.path = matches[6] || ''\n parsed.query = matches[7]\n parsed.fragment = matches[8]\n\n // fix port number\n if (isNaN(parsed.port)) {\n parsed.port = matches[5]\n }\n if (parsed.host) {\n const ipv4result = isIPv4(parsed.host)\n if (ipv4result === false) {\n const ipv6result = normalizeIPv6(parsed.host)\n parsed.host = ipv6result.host.toLowerCase()\n isIP = ipv6result.isIPV6\n } else {\n isIP = true\n }\n }\n if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n parsed.reference = 'same-document'\n } else if (parsed.scheme === undefined) {\n parsed.reference = 'relative'\n } else if (parsed.fragment === undefined) {\n parsed.reference = 'absolute'\n } else {\n parsed.reference = 'uri'\n }\n\n // check for reference errors\n if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n }\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)\n\n // check if scheme can't handle IRIs\n if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n // if host component is a domain name\n if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {\n // convert Unicode IDN -> ASCII IDN\n try {\n parsed.host = URL.domainToASCII(parsed.host.toLowerCase())\n } catch (e) {\n parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n }\n }\n // convert IRI -> URI\n }\n\n if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n if (uri.indexOf('%') !== -1) {\n if (parsed.scheme !== undefined) {\n parsed.scheme = unescape(parsed.scheme)\n }\n if (parsed.host !== undefined) {\n parsed.host = unescape(parsed.host)\n }\n }\n if (parsed.path) {\n parsed.path = escape(unescape(parsed.path))\n }\n if (parsed.fragment) {\n parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))\n }\n }\n\n // perform scheme specific parsing\n if (schemeHandler && schemeHandler.parse) {\n schemeHandler.parse(parsed, options)\n }\n } else {\n parsed.error = parsed.error || 'URI can not be parsed.'\n }\n return parsed\n}\n\nconst fastUri = {\n SCHEMES,\n normalize,\n resolve,\n resolveComponent,\n equal,\n serialize,\n parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst uri = require(\"fast-uri\");\nuri.code = 'require(\"ajv/dist/runtime/uri\").default';\nexports.default = uri;\n//# sourceMappingURL=uri.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nconst validation_error_1 = require(\"./runtime/validation_error\");\nconst ref_error_1 = require(\"./compile/ref_error\");\nconst rules_1 = require(\"./compile/rules\");\nconst compile_1 = require(\"./compile\");\nconst codegen_2 = require(\"./compile/codegen\");\nconst resolve_1 = require(\"./compile/resolve\");\nconst dataType_1 = require(\"./compile/validate/dataType\");\nconst util_1 = require(\"./compile/util\");\nconst $dataRefSchema = require(\"./refs/data.json\");\nconst uri_1 = require(\"./runtime/uri\");\nconst defaultRegExp = (str, flags) => new RegExp(str, flags);\ndefaultRegExp.code = \"new RegExp\";\nconst META_IGNORE_OPTIONS = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"];\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n]);\nconst removedOptions = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n};\nconst deprecatedOptions = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n};\nconst MAX_EXPRESSION = 200;\n// eslint-disable-next-line complexity\nfunction requiredOptions(o) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;\n const s = o.strict;\n const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;\n const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;\n const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;\n return {\n strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,\n strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,\n strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : \"log\",\n strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : \"log\",\n strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,\n code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },\n loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,\n loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,\n meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,\n messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,\n inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,\n schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : \"$id\",\n addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,\n validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,\n validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,\n unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,\n int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,\n uriResolver: uriResolver,\n };\n}\nclass Ajv {\n constructor(opts = {}) {\n this.schemas = {};\n this.refs = {};\n this.formats = {};\n this._compilations = new Set();\n this._loading = {};\n this._cache = new Map();\n opts = this.opts = { ...opts, ...requiredOptions(opts) };\n const { es5, lines } = this.opts.code;\n this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });\n this.logger = getLogger(opts.logger);\n const formatOpt = opts.validateFormats;\n opts.validateFormats = false;\n this.RULES = (0, rules_1.getRules)();\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\");\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\");\n this._metaOpts = getMetaSchemaOptions.call(this);\n if (opts.formats)\n addInitialFormats.call(this);\n this._addVocabularies();\n this._addDefaultMetaSchema();\n if (opts.keywords)\n addInitialKeywords.call(this, opts.keywords);\n if (typeof opts.meta == \"object\")\n this.addMetaSchema(opts.meta);\n addInitialSchemas.call(this);\n opts.validateFormats = formatOpt;\n }\n _addVocabularies() {\n this.addKeyword(\"$async\");\n }\n _addDefaultMetaSchema() {\n const { $data, meta, schemaId } = this.opts;\n let _dataRefSchema = $dataRefSchema;\n if (schemaId === \"id\") {\n _dataRefSchema = { ...$dataRefSchema };\n _dataRefSchema.id = _dataRefSchema.$id;\n delete _dataRefSchema.$id;\n }\n if (meta && $data)\n this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);\n }\n defaultMeta() {\n const { meta, schemaId } = this.opts;\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined);\n }\n validate(schemaKeyRef, // key, ref or schema object\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n data // to be validated\n ) {\n let v;\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema(schemaKeyRef);\n if (!v)\n throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`);\n }\n else {\n v = this.compile(schemaKeyRef);\n }\n const valid = v(data);\n if (!(\"$async\" in v))\n this.errors = v.errors;\n return valid;\n }\n compile(schema, _meta) {\n const sch = this._addSchema(schema, _meta);\n return (sch.validate || this._compileSchemaEnv(sch));\n }\n compileAsync(schema, meta) {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\");\n }\n const { loadSchema } = this.opts;\n return runCompileAsync.call(this, schema, meta);\n async function runCompileAsync(_schema, _meta) {\n await loadMetaSchema.call(this, _schema.$schema);\n const sch = this._addSchema(_schema, _meta);\n return sch.validate || _compileAsync.call(this, sch);\n }\n async function loadMetaSchema($ref) {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, { $ref }, true);\n }\n }\n async function _compileAsync(sch) {\n try {\n return this._compileSchemaEnv(sch);\n }\n catch (e) {\n if (!(e instanceof ref_error_1.default))\n throw e;\n checkLoaded.call(this, e);\n await loadMissingSchema.call(this, e.missingSchema);\n return _compileAsync.call(this, sch);\n }\n }\n function checkLoaded({ missingSchema: ref, missingRef }) {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);\n }\n }\n async function loadMissingSchema(ref) {\n const _schema = await _loadSchema.call(this, ref);\n if (!this.refs[ref])\n await loadMetaSchema.call(this, _schema.$schema);\n if (!this.refs[ref])\n this.addSchema(_schema, ref, meta);\n }\n async function _loadSchema(ref) {\n const p = this._loading[ref];\n if (p)\n return p;\n try {\n return await (this._loading[ref] = loadSchema(ref));\n }\n finally {\n delete this._loading[ref];\n }\n }\n }\n // Adds schema to the instance\n addSchema(schema, // If array is passed, `key` will be ignored\n key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ) {\n if (Array.isArray(schema)) {\n for (const sch of schema)\n this.addSchema(sch, undefined, _meta, _validateSchema);\n return this;\n }\n let id;\n if (typeof schema === \"object\") {\n const { schemaId } = this.opts;\n id = schema[schemaId];\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`);\n }\n }\n key = (0, resolve_1.normalizeId)(key || id);\n this._checkUnique(key);\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);\n return this;\n }\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(schema, key, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ) {\n this.addSchema(schema, key, true, _validateSchema);\n return this;\n }\n // Validate schema against its meta-schema\n validateSchema(schema, throwOrLogError) {\n if (typeof schema == \"boolean\")\n return true;\n let $schema;\n $schema = schema.$schema;\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\");\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta();\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\");\n this.errors = null;\n return true;\n }\n const valid = this.validate($schema, schema);\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText();\n if (this.opts.validateSchema === \"log\")\n this.logger.error(message);\n else\n throw new Error(message);\n }\n return valid;\n }\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema(keyRef) {\n let sch;\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\")\n keyRef = sch;\n if (sch === undefined) {\n const { schemaId } = this.opts;\n const root = new compile_1.SchemaEnv({ schema: {}, schemaId });\n sch = compile_1.resolveSchema.call(this, root, keyRef);\n if (!sch)\n return;\n this.refs[keyRef] = sch;\n }\n return (sch.validate || this._compileSchemaEnv(sch));\n }\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef) {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef);\n this._removeAllSchemas(this.refs, schemaKeyRef);\n return this;\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas);\n this._removeAllSchemas(this.refs);\n this._cache.clear();\n return this;\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef);\n if (typeof sch == \"object\")\n this._cache.delete(sch.schema);\n delete this.schemas[schemaKeyRef];\n delete this.refs[schemaKeyRef];\n return this;\n }\n case \"object\": {\n const cacheKey = schemaKeyRef;\n this._cache.delete(cacheKey);\n let id = schemaKeyRef[this.opts.schemaId];\n if (id) {\n id = (0, resolve_1.normalizeId)(id);\n delete this.schemas[id];\n delete this.refs[id];\n }\n return this;\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\");\n }\n }\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions) {\n for (const def of definitions)\n this.addKeyword(def);\n return this;\n }\n addKeyword(kwdOrDef, def // deprecated\n ) {\n let keyword;\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef;\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\");\n def.keyword = keyword;\n }\n }\n else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef;\n keyword = def.keyword;\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\");\n }\n }\n else {\n throw new Error(\"invalid addKeywords parameters\");\n }\n checkKeyword.call(this, keyword, def);\n if (!def) {\n (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));\n return this;\n }\n keywordMetaschema.call(this, def);\n const definition = {\n ...def,\n type: (0, dataType_1.getJSONTypes)(def.type),\n schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),\n };\n (0, util_1.eachItem)(keyword, definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));\n return this;\n }\n getKeyword(keyword) {\n const rule = this.RULES.all[keyword];\n return typeof rule == \"object\" ? rule.definition : !!rule;\n }\n // Remove keyword\n removeKeyword(keyword) {\n // TODO return type should be Ajv\n const { RULES } = this;\n delete RULES.keywords[keyword];\n delete RULES.all[keyword];\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword);\n if (i >= 0)\n group.rules.splice(i, 1);\n }\n return this;\n }\n // Add format\n addFormat(name, format) {\n if (typeof format == \"string\")\n format = new RegExp(format);\n this.formats[name] = format;\n return this;\n }\n errorsText(errors = this.errors, // optional array of validation errors\n { separator = \", \", dataVar = \"data\" } = {} // optional options with properties `separator` and `dataVar`\n ) {\n if (!errors || errors.length === 0)\n return \"No errors\";\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg);\n }\n $dataMetaSchema(metaSchema, keywordsJsonPointers) {\n const rules = this.RULES.all;\n metaSchema = JSON.parse(JSON.stringify(metaSchema));\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1); // first segment is an empty string\n let keywords = metaSchema;\n for (const seg of segments)\n keywords = keywords[seg];\n for (const key in rules) {\n const rule = rules[key];\n if (typeof rule != \"object\")\n continue;\n const { $data } = rule.definition;\n const schema = keywords[key];\n if ($data && schema)\n keywords[key] = schemaOrData(schema);\n }\n }\n return metaSchema;\n }\n _removeAllSchemas(schemas, regex) {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef];\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef];\n }\n else if (sch && !sch.meta) {\n this._cache.delete(sch.schema);\n delete schemas[keyRef];\n }\n }\n }\n }\n _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {\n let id;\n const { schemaId } = this.opts;\n if (typeof schema == \"object\") {\n id = schema[schemaId];\n }\n else {\n if (this.opts.jtd)\n throw new Error(\"schema must be object\");\n else if (typeof schema != \"boolean\")\n throw new Error(\"schema must be object or boolean\");\n }\n let sch = this._cache.get(schema);\n if (sch !== undefined)\n return sch;\n baseId = (0, resolve_1.normalizeId)(id || baseId);\n const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);\n sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });\n this._cache.set(sch.schema, sch);\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId)\n this._checkUnique(baseId);\n this.refs[baseId] = sch;\n }\n if (validateSchema)\n this.validateSchema(schema, true);\n return sch;\n }\n _checkUnique(id) {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`);\n }\n }\n _compileSchemaEnv(sch) {\n if (sch.meta)\n this._compileMetaSchema(sch);\n else\n compile_1.compileSchema.call(this, sch);\n /* istanbul ignore if */\n if (!sch.validate)\n throw new Error(\"ajv implementation error\");\n return sch.validate;\n }\n _compileMetaSchema(sch) {\n const currentOpts = this.opts;\n this.opts = this._metaOpts;\n try {\n compile_1.compileSchema.call(this, sch);\n }\n finally {\n this.opts = currentOpts;\n }\n }\n}\nAjv.ValidationError = validation_error_1.default;\nAjv.MissingRefError = ref_error_1.default;\nexports.default = Ajv;\nfunction checkOptions(checkOpts, options, msg, log = \"error\") {\n for (const key in checkOpts) {\n const opt = key;\n if (opt in options)\n this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);\n }\n}\nfunction getSchEnv(keyRef) {\n keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef];\n}\nfunction addInitialSchemas() {\n const optsSchemas = this.opts.schemas;\n if (!optsSchemas)\n return;\n if (Array.isArray(optsSchemas))\n this.addSchema(optsSchemas);\n else\n for (const key in optsSchemas)\n this.addSchema(optsSchemas[key], key);\n}\nfunction addInitialFormats() {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name];\n if (format)\n this.addFormat(name, format);\n }\n}\nfunction addInitialKeywords(defs) {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs);\n return;\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\");\n for (const keyword in defs) {\n const def = defs[keyword];\n if (!def.keyword)\n def.keyword = keyword;\n this.addKeyword(def);\n }\n}\nfunction getMetaSchemaOptions() {\n const metaOpts = { ...this.opts };\n for (const opt of META_IGNORE_OPTIONS)\n delete metaOpts[opt];\n return metaOpts;\n}\nconst noLogs = { log() { }, warn() { }, error() { } };\nfunction getLogger(logger) {\n if (logger === false)\n return noLogs;\n if (logger === undefined)\n return console;\n if (logger.log && logger.warn && logger.error)\n return logger;\n throw new Error(\"logger must implement log, warn and error methods\");\n}\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;\nfunction checkKeyword(keyword, def) {\n const { RULES } = this;\n (0, util_1.eachItem)(keyword, (kwd) => {\n if (RULES.keywords[kwd])\n throw new Error(`Keyword ${kwd} is already defined`);\n if (!KEYWORD_NAME.test(kwd))\n throw new Error(`Keyword ${kwd} has invalid name`);\n });\n if (!def)\n return;\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function');\n }\n}\nfunction addRule(keyword, definition, dataType) {\n var _a;\n const post = definition === null || definition === void 0 ? void 0 : definition.post;\n if (dataType && post)\n throw new Error('keyword with \"post\" flag cannot have \"type\"');\n const { RULES } = this;\n let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);\n if (!ruleGroup) {\n ruleGroup = { type: dataType, rules: [] };\n RULES.rules.push(ruleGroup);\n }\n RULES.keywords[keyword] = true;\n if (!definition)\n return;\n const rule = {\n keyword,\n definition: {\n ...definition,\n type: (0, dataType_1.getJSONTypes)(definition.type),\n schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),\n },\n };\n if (definition.before)\n addBeforeRule.call(this, ruleGroup, rule, definition.before);\n else\n ruleGroup.rules.push(rule);\n RULES.all[keyword] = rule;\n (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));\n}\nfunction addBeforeRule(ruleGroup, rule, before) {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule);\n }\n else {\n ruleGroup.rules.push(rule);\n this.logger.warn(`rule ${before} is not defined`);\n }\n}\nfunction keywordMetaschema(def) {\n let { metaSchema } = def;\n if (metaSchema === undefined)\n return;\n if (def.$data && this.opts.$data)\n metaSchema = schemaOrData(metaSchema);\n def.validateSchema = this.compile(metaSchema, true);\n}\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n};\nfunction schemaOrData(schema) {\n return { anyOf: [schema, $dataRef] };\n}\n//# sourceMappingURL=core.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst def = {\n keyword: \"id\",\n code() {\n throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID');\n },\n};\nexports.default = def;\n//# sourceMappingURL=id.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.callRef = exports.getValidate = void 0;\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst compile_1 = require(\"../../compile\");\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt) {\n const { gen, schema: $ref, it } = cxt;\n const { baseId, schemaEnv: env, validateName, opts, self } = it;\n const { root } = env;\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId)\n return callRootRef();\n const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);\n if (schOrEnv === undefined)\n throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);\n if (schOrEnv instanceof compile_1.SchemaEnv)\n return callValidate(schOrEnv);\n return inlineRefSchema(schOrEnv);\n function callRootRef() {\n if (env === root)\n return callRef(cxt, validateName, env, env.$async);\n const rootName = gen.scopeValue(\"root\", { ref: root });\n return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);\n }\n function callValidate(sch) {\n const v = getValidate(cxt, sch);\n callRef(cxt, v, sch, sch.$async);\n }\n function inlineRefSchema(sch) {\n const schName = gen.scopeValue(\"schema\", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });\n const valid = gen.name(\"valid\");\n const schCxt = cxt.subschema({\n schema: sch,\n dataTypes: [],\n schemaPath: codegen_1.nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n }, valid);\n cxt.mergeEvaluated(schCxt);\n cxt.ok(valid);\n }\n },\n};\nfunction getValidate(cxt, sch) {\n const { gen } = cxt;\n return sch.validate\n ? gen.scopeValue(\"validate\", { ref: sch.validate })\n : (0, codegen_1._) `${gen.scopeValue(\"wrapper\", { ref: sch })}.validate`;\n}\nexports.getValidate = getValidate;\nfunction callRef(cxt, v, sch, $async) {\n const { gen, it } = cxt;\n const { allErrors, schemaEnv: env, opts } = it;\n const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;\n if ($async)\n callAsyncRef();\n else\n callSyncRef();\n function callAsyncRef() {\n if (!env.$async)\n throw new Error(\"async schema referenced by sync schema\");\n const valid = gen.let(\"valid\");\n gen.try(() => {\n gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);\n addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result\n if (!allErrors)\n gen.assign(valid, true);\n }, (e) => {\n gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));\n addErrorsFrom(e);\n if (!allErrors)\n gen.assign(valid, false);\n });\n cxt.ok(valid);\n }\n function callSyncRef() {\n cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));\n }\n function addErrorsFrom(source) {\n const errs = (0, codegen_1._) `${source}.errors`;\n gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged\n gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n }\n function addEvaluatedFrom(source) {\n var _a;\n if (!it.opts.unevaluated)\n return;\n const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);\n }\n }\n else {\n const props = gen.var(\"props\", (0, codegen_1._) `${source}.evaluated.props`);\n it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);\n }\n }\n else {\n const items = gen.var(\"items\", (0, codegen_1._) `${source}.evaluated.items`);\n it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);\n }\n }\n }\n}\nexports.callRef = callRef;\nexports.default = def;\n//# sourceMappingURL=ref.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst id_1 = require(\"./id\");\nconst ref_1 = require(\"./ref\");\nconst core = [\n \"$schema\",\n \"$id\",\n \"$defs\",\n \"$vocabulary\",\n { keyword: \"$comment\" },\n \"definitions\",\n id_1.default,\n ref_1.default,\n];\nexports.default = core;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n maximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n minimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n exclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n exclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,\n params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode } = cxt;\n cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitNumber.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,\n params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, schemaCode, it } = cxt;\n // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision;\n const res = gen.let(\"res\");\n const invalid = prec\n ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : (0, codegen_1._) `${res} !== parseInt(${res})`;\n cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=multipleOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nfunction ucs2length(str) {\n const len = str.length;\n let length = 0;\n let pos = 0;\n let value;\n while (pos < len) {\n length++;\n value = str.charCodeAt(pos++);\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos);\n if ((value & 0xfc00) === 0xdc00)\n pos++; // low surrogate\n }\n }\n return length;\n}\nexports.default = ucs2length;\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default';\n//# sourceMappingURL=ucs2length.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst ucs2length_1 = require(\"../../runtime/ucs2length\");\nconst error = {\n message({ keyword, schemaCode }) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\";\n return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;\n },\n params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode, it } = cxt;\n const op = keyword === \"maxLength\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;\n cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitLength.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern \"${schemaCode}\"`,\n params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schema, schemaCode, it } = cxt;\n const u = it.opts.unicodeRegExp ? \"u\" : \"\";\n if ($data) {\n const { regExp } = it.opts.code;\n const regExpCode = regExp.code === \"new RegExp\" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);\n const valid = gen.let(\"valid\");\n gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));\n cxt.fail$data((0, codegen_1._) `!${valid}`);\n }\n else {\n const regExp = (0, code_1.usePattern)(cxt, schema);\n cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=pattern.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message({ keyword, schemaCode }) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\";\n return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;\n },\n params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode } = cxt;\n const op = keyword === \"maxProperties\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,\n params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,\n};\nconst def = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt) {\n const { gen, schema, schemaCode, data, $data, it } = cxt;\n const { opts } = it;\n if (!$data && schema.length === 0)\n return;\n const useLoop = schema.length >= opts.loopRequired;\n if (it.allErrors)\n allErrorsMode();\n else\n exitOnErrorMode();\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties;\n const { definedProperties } = cxt.it;\n for (const requiredKey of schema) {\n if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`;\n (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);\n }\n }\n }\n function allErrorsMode() {\n if (useLoop || $data) {\n cxt.block$data(codegen_1.nil, loopAllRequired);\n }\n else {\n for (const prop of schema) {\n (0, code_1.checkReportMissingProp)(cxt, prop);\n }\n }\n }\n function exitOnErrorMode() {\n const missing = gen.let(\"missing\");\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true);\n cxt.block$data(valid, () => loopUntilMissing(missing, valid));\n cxt.ok(valid);\n }\n else {\n gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));\n (0, code_1.reportMissingProp)(cxt, missing);\n gen.else();\n }\n }\n function loopAllRequired() {\n gen.forOf(\"prop\", schemaCode, (prop) => {\n cxt.setParams({ missingProperty: prop });\n gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());\n });\n }\n function loopUntilMissing(missing, valid) {\n cxt.setParams({ missingProperty: missing });\n gen.forOf(missing, schemaCode, () => {\n gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));\n gen.if((0, codegen_1.not)(valid), () => {\n cxt.error();\n gen.break();\n });\n }, codegen_1.nil);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=required.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message({ keyword, schemaCode }) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\";\n return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;\n },\n params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode } = cxt;\n const op = keyword === \"maxItems\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://github.com/ajv-validator/ajv/issues/889\nconst equal = require(\"fast-deep-equal\");\nequal.code = 'require(\"ajv/dist/runtime/equal\").default';\nexports.default = equal;\n//# sourceMappingURL=equal.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dataType_1 = require(\"../../compile/validate/dataType\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,\n};\nconst def = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;\n if (!$data && !schema)\n return;\n const valid = gen.let(\"valid\");\n const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];\n cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);\n cxt.ok(valid);\n function validateUniqueItems() {\n const i = gen.let(\"i\", (0, codegen_1._) `${data}.length`);\n const j = gen.let(\"j\");\n cxt.setParams({ i, j });\n gen.assign(valid, true);\n gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));\n }\n function canOptimize() {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\");\n }\n function loopN(i, j) {\n const item = gen.name(\"item\");\n const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);\n const indices = gen.const(\"indices\", (0, codegen_1._) `{}`);\n gen.for((0, codegen_1._) `;${i}--;`, () => {\n gen.let(item, (0, codegen_1._) `${data}[${i}]`);\n gen.if(wrongType, (0, codegen_1._) `continue`);\n if (itemTypes.length > 1)\n gen.if((0, codegen_1._) `typeof ${item} == \"string\"`, (0, codegen_1._) `${item} += \"_\"`);\n gen\n .if((0, codegen_1._) `typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);\n cxt.error();\n gen.assign(valid, false).break();\n })\n .code((0, codegen_1._) `${indices}[${item}] = ${i}`);\n });\n }\n function loopN2(i, j) {\n const eql = (0, util_1.useFunc)(gen, equal_1.default);\n const outer = gen.name(\"outer\");\n 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}])`, () => {\n cxt.error();\n gen.assign(valid, false).break(outer);\n })));\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=uniqueItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n message: \"must be equal to constant\",\n params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schemaCode, schema } = cxt;\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);\n }\n else {\n cxt.fail((0, codegen_1._) `${schema} !== ${data}`);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=const.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n message: \"must be equal to one of the allowed values\",\n params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schema, schemaCode, it } = cxt;\n if (!$data && schema.length === 0)\n throw new Error(\"enum must have non-empty array\");\n const useLoop = schema.length >= it.opts.loopEnum;\n let eql;\n const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));\n let valid;\n if (useLoop || $data) {\n valid = gen.let(\"valid\");\n cxt.block$data(valid, loopEnum);\n }\n else {\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n const vSchema = gen.const(\"vSchema\", schemaCode);\n valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));\n }\n cxt.pass(valid);\n function loopEnum() {\n gen.assign(valid, false);\n gen.forOf(\"v\", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));\n }\n function equalCode(vSchema, i) {\n const sch = schema[i];\n return typeof sch === \"object\" && sch !== null\n ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`\n : (0, codegen_1._) `${data} === ${sch}`;\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=enum.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst limitNumber_1 = require(\"./limitNumber\");\nconst multipleOf_1 = require(\"./multipleOf\");\nconst limitLength_1 = require(\"./limitLength\");\nconst pattern_1 = require(\"./pattern\");\nconst limitProperties_1 = require(\"./limitProperties\");\nconst required_1 = require(\"./required\");\nconst limitItems_1 = require(\"./limitItems\");\nconst uniqueItems_1 = require(\"./uniqueItems\");\nconst const_1 = require(\"./const\");\nconst enum_1 = require(\"./enum\");\nconst validation = [\n // number\n limitNumber_1.default,\n multipleOf_1.default,\n // string\n limitLength_1.default,\n pattern_1.default,\n // object\n limitProperties_1.default,\n required_1.default,\n // array\n limitItems_1.default,\n uniqueItems_1.default,\n // any\n { keyword: \"type\", schemaType: [\"string\", \"array\"] },\n { keyword: \"nullable\", schemaType: \"boolean\" },\n const_1.default,\n enum_1.default,\n];\nexports.default = validation;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateAdditionalItems = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n keyword: \"additionalItems\",\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt) {\n const { parentSchema, it } = cxt;\n const { items } = parentSchema;\n if (!Array.isArray(items)) {\n (0, util_1.checkStrictMode)(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas');\n return;\n }\n validateAdditionalItems(cxt, items);\n },\n};\nfunction validateAdditionalItems(cxt, items) {\n const { gen, schema, data, keyword, it } = cxt;\n it.items = true;\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n if (schema === false) {\n cxt.setParams({ len: items.length });\n cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);\n }\n else if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n const valid = gen.var(\"valid\", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var\n gen.if((0, codegen_1.not)(valid), () => validateItems(valid));\n cxt.ok(valid);\n }\n function validateItems(valid) {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);\n if (!it.allErrors)\n gen.if((0, codegen_1.not)(valid), () => gen.break());\n });\n }\n}\nexports.validateAdditionalItems = validateAdditionalItems;\nexports.default = def;\n//# sourceMappingURL=additionalItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateTuple = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst def = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt) {\n const { schema, it } = cxt;\n if (Array.isArray(schema))\n return validateTuple(cxt, \"additionalItems\", schema);\n it.items = true;\n if ((0, util_1.alwaysValidSchema)(it, schema))\n return;\n cxt.ok((0, code_1.validateArray)(cxt));\n },\n};\nfunction validateTuple(cxt, extraItems, schArr = cxt.schema) {\n const { gen, parentSchema, data, keyword, it } = cxt;\n checkStrictTuple(parentSchema);\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);\n }\n const valid = gen.name(\"valid\");\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n schArr.forEach((sch, i) => {\n if ((0, util_1.alwaysValidSchema)(it, sch))\n return;\n gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({\n keyword,\n schemaProp: i,\n dataProp: i,\n }, valid));\n cxt.ok(valid);\n });\n function checkStrictTuple(sch) {\n const { opts, errSchemaPath } = it;\n const l = schArr.length;\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`;\n (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);\n }\n }\n}\nexports.validateTuple = validateTuple;\nexports.default = def;\n//# sourceMappingURL=items.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst items_1 = require(\"./items\");\nconst def = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => (0, items_1.validateTuple)(cxt, \"items\"),\n};\nexports.default = def;\n//# sourceMappingURL=prefixItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst additionalItems_1 = require(\"./additionalItems\");\nconst error = {\n message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt) {\n const { schema, parentSchema, it } = cxt;\n const { prefixItems } = parentSchema;\n it.items = true;\n if ((0, util_1.alwaysValidSchema)(it, schema))\n return;\n if (prefixItems)\n (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);\n else\n cxt.ok((0, code_1.validateArray)(cxt));\n },\n};\nexports.default = def;\n//# sourceMappingURL=items2020.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { min, max } }) => max === undefined\n ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`\n : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,\n};\nconst def = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, schema, parentSchema, data, it } = cxt;\n let min;\n let max;\n const { minContains, maxContains } = parentSchema;\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains;\n max = maxContains;\n }\n else {\n min = 1;\n }\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n cxt.setParams({ min, max });\n if (max === undefined && min === 0) {\n (0, util_1.checkStrictMode)(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`);\n return;\n }\n if (max !== undefined && min > max) {\n (0, util_1.checkStrictMode)(it, `\"minContains\" > \"maxContains\" is always invalid`);\n cxt.fail();\n return;\n }\n if ((0, util_1.alwaysValidSchema)(it, schema)) {\n let cond = (0, codegen_1._) `${len} >= ${min}`;\n if (max !== undefined)\n cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;\n cxt.pass(cond);\n return;\n }\n it.items = true;\n const valid = gen.name(\"valid\");\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()));\n }\n else if (min === 0) {\n gen.let(valid, true);\n if (max !== undefined)\n gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);\n }\n else {\n gen.let(valid, false);\n validateItemsWithCount();\n }\n cxt.result(valid, () => cxt.reset());\n function validateItemsWithCount() {\n const schValid = gen.name(\"_valid\");\n const count = gen.let(\"count\", 0);\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));\n }\n function validateItems(_valid, block) {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema({\n keyword: \"contains\",\n dataProp: i,\n dataPropType: util_1.Type.Num,\n compositeRule: true,\n }, _valid);\n block();\n });\n }\n function checkLimits(count) {\n gen.code((0, codegen_1._) `${count}++`);\n if (max === undefined) {\n gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());\n }\n else {\n gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());\n if (min === 1)\n gen.assign(valid, true);\n else\n gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));\n }\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=contains.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nexports.error = {\n message: ({ params: { property, depsCount, deps } }) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\";\n return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;\n },\n params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n};\nconst def = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error: exports.error,\n code(cxt) {\n const [propDeps, schDeps] = splitDependencies(cxt);\n validatePropertyDeps(cxt, propDeps);\n validateSchemaDeps(cxt, schDeps);\n },\n};\nfunction splitDependencies({ schema }) {\n const propertyDeps = {};\n const schemaDeps = {};\n for (const key in schema) {\n if (key === \"__proto__\")\n continue;\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;\n deps[key] = schema[key];\n }\n return [propertyDeps, schemaDeps];\n}\nfunction validatePropertyDeps(cxt, propertyDeps = cxt.schema) {\n const { gen, data, it } = cxt;\n if (Object.keys(propertyDeps).length === 0)\n return;\n const missing = gen.let(\"missing\");\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop];\n if (deps.length === 0)\n continue;\n const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n });\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n (0, code_1.checkReportMissingProp)(cxt, depProp);\n }\n });\n }\n else {\n gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);\n (0, code_1.reportMissingProp)(cxt, missing);\n gen.else();\n }\n }\n}\nexports.validatePropertyDeps = validatePropertyDeps;\nfunction validateSchemaDeps(cxt, schemaDeps = cxt.schema) {\n const { gen, data, keyword, it } = cxt;\n const valid = gen.name(\"valid\");\n for (const prop in schemaDeps) {\n if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))\n continue;\n gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {\n const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);\n cxt.mergeValidEvaluated(schCxt, valid);\n }, () => gen.var(valid, true) // TODO var\n );\n cxt.ok(valid);\n }\n}\nexports.validateSchemaDeps = validateSchemaDeps;\nexports.default = def;\n//# sourceMappingURL=dependencies.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: \"property name must be valid\",\n params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,\n};\nconst def = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt) {\n const { gen, schema, data, it } = cxt;\n if ((0, util_1.alwaysValidSchema)(it, schema))\n return;\n const valid = gen.name(\"valid\");\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({ propertyName: key });\n cxt.subschema({\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n }, valid);\n gen.if((0, codegen_1.not)(valid), () => {\n cxt.error(true);\n if (!it.allErrors)\n gen.break();\n });\n });\n cxt.ok(valid);\n },\n};\nexports.default = def;\n//# sourceMappingURL=propertyNames.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: \"must NOT have additional properties\",\n params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,\n};\nconst def = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, schema, parentSchema, data, errsCount, it } = cxt;\n /* istanbul ignore if */\n if (!errsCount)\n throw new Error(\"ajv implementation error\");\n const { allErrors, opts } = it;\n it.props = true;\n if (opts.removeAdditional !== \"all\" && (0, util_1.alwaysValidSchema)(it, schema))\n return;\n const props = (0, code_1.allSchemaProperties)(parentSchema.properties);\n const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);\n checkAdditionalProperties();\n cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n function checkAdditionalProperties() {\n gen.forIn(\"key\", data, (key) => {\n if (!props.length && !patProps.length)\n additionalPropertyCode(key);\n else\n gen.if(isAdditional(key), () => additionalPropertyCode(key));\n });\n }\n function isAdditional(key) {\n let definedProp;\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, \"properties\");\n definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);\n }\n else if (props.length) {\n definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));\n }\n else {\n definedProp = codegen_1.nil;\n }\n if (patProps.length) {\n definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));\n }\n return (0, codegen_1.not)(definedProp);\n }\n function deleteAdditional(key) {\n gen.code((0, codegen_1._) `delete ${data}[${key}]`);\n }\n function additionalPropertyCode(key) {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key);\n return;\n }\n if (schema === false) {\n cxt.setParams({ additionalProperty: key });\n cxt.error();\n if (!allErrors)\n gen.break();\n return;\n }\n if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n const valid = gen.name(\"valid\");\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false);\n gen.if((0, codegen_1.not)(valid), () => {\n cxt.reset();\n deleteAdditional(key);\n });\n }\n else {\n applyAdditionalSchema(key, valid);\n if (!allErrors)\n gen.if((0, codegen_1.not)(valid), () => gen.break());\n }\n }\n }\n function applyAdditionalSchema(key, valid, errors) {\n const subschema = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: util_1.Type.Str,\n };\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n });\n }\n cxt.subschema(subschema, valid);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=additionalProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst validate_1 = require(\"../../compile/validate\");\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst def = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt) {\n const { gen, schema, parentSchema, data, it } = cxt;\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, \"additionalProperties\"));\n }\n const allProps = (0, code_1.allSchemaProperties)(schema);\n for (const prop of allProps) {\n it.definedProperties.add(prop);\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);\n }\n const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));\n if (properties.length === 0)\n return;\n const valid = gen.name(\"valid\");\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop);\n }\n else {\n gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));\n applyPropertySchema(prop);\n if (!it.allErrors)\n gen.else().var(valid, true);\n gen.endIf();\n }\n cxt.it.definedProperties.add(prop);\n cxt.ok(valid);\n }\n function hasDefault(prop) {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;\n }\n function applyPropertySchema(prop) {\n cxt.subschema({\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n }, valid);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=properties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst util_2 = require(\"../../compile/util\");\nconst def = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt) {\n const { gen, schema, data, parentSchema, it } = cxt;\n const { opts } = it;\n const patterns = (0, code_1.allSchemaProperties)(schema);\n const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));\n if (patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))) {\n return;\n }\n const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;\n const valid = gen.name(\"valid\");\n if (it.props !== true && !(it.props instanceof codegen_1.Name)) {\n it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);\n }\n const { props } = it;\n validatePatternProperties();\n function validatePatternProperties() {\n for (const pat of patterns) {\n if (checkProperties)\n checkMatchingProperties(pat);\n if (it.allErrors) {\n validateProperties(pat);\n }\n else {\n gen.var(valid, true); // TODO var\n validateProperties(pat);\n gen.if(valid);\n }\n }\n }\n function checkMatchingProperties(pat) {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);\n }\n }\n }\n function validateProperties(pat) {\n gen.forIn(\"key\", data, (key) => {\n gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat);\n if (!alwaysValid) {\n cxt.subschema({\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: util_2.Type.Str,\n }, valid);\n }\n if (it.opts.unevaluated && props !== true) {\n gen.assign((0, codegen_1._) `${props}[${key}]`, true);\n }\n else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if((0, codegen_1.not)(valid), () => gen.break());\n }\n });\n });\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=patternProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt) {\n const { gen, schema, it } = cxt;\n if ((0, util_1.alwaysValidSchema)(it, schema)) {\n cxt.fail();\n return;\n }\n const valid = gen.name(\"valid\");\n cxt.subschema({\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n }, valid);\n cxt.failResult(valid, () => cxt.reset(), () => cxt.error());\n },\n error: { message: \"must NOT be valid\" },\n};\nexports.default = def;\n//# sourceMappingURL=not.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst def = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: code_1.validateUnion,\n error: { message: \"must match a schema in anyOf\" },\n};\nexports.default = def;\n//# sourceMappingURL=anyOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: \"must match exactly one schema in oneOf\",\n params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,\n};\nconst def = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, schema, parentSchema, it } = cxt;\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n if (it.opts.discriminator && parentSchema.discriminator)\n return;\n const schArr = schema;\n const valid = gen.let(\"valid\", false);\n const passing = gen.let(\"passing\", null);\n const schValid = gen.name(\"_valid\");\n cxt.setParams({ passing });\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n gen.block(validateOneOf);\n cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n function validateOneOf() {\n schArr.forEach((sch, i) => {\n let schCxt;\n if ((0, util_1.alwaysValidSchema)(it, sch)) {\n gen.var(schValid, true);\n }\n else {\n schCxt = cxt.subschema({\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n }, schValid);\n }\n if (i > 0) {\n gen\n .if((0, codegen_1._) `${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)\n .else();\n }\n gen.if(schValid, () => {\n gen.assign(valid, true);\n gen.assign(passing, i);\n if (schCxt)\n cxt.mergeEvaluated(schCxt, codegen_1.Name);\n });\n });\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=oneOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt) {\n const { gen, schema, it } = cxt;\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n const valid = gen.name(\"valid\");\n schema.forEach((sch, i) => {\n if ((0, util_1.alwaysValidSchema)(it, sch))\n return;\n const schCxt = cxt.subschema({ keyword: \"allOf\", schemaProp: i }, valid);\n cxt.ok(valid);\n cxt.mergeEvaluated(schCxt);\n });\n },\n};\nexports.default = def;\n//# sourceMappingURL=allOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params }) => (0, codegen_1.str) `must match \"${params.ifClause}\" schema`,\n params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,\n};\nconst def = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, parentSchema, it } = cxt;\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n (0, util_1.checkStrictMode)(it, '\"if\" without \"then\" and \"else\" is ignored');\n }\n const hasThen = hasSchema(it, \"then\");\n const hasElse = hasSchema(it, \"else\");\n if (!hasThen && !hasElse)\n return;\n const valid = gen.let(\"valid\", true);\n const schValid = gen.name(\"_valid\");\n validateIf();\n cxt.reset();\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\");\n cxt.setParams({ ifClause });\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause));\n }\n else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"));\n }\n else {\n gen.if((0, codegen_1.not)(schValid), validateClause(\"else\"));\n }\n cxt.pass(valid, () => cxt.error(true));\n function validateIf() {\n const schCxt = cxt.subschema({\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n }, schValid);\n cxt.mergeEvaluated(schCxt);\n }\n function validateClause(keyword, ifClause) {\n return () => {\n const schCxt = cxt.subschema({ keyword }, schValid);\n gen.assign(valid, schValid);\n cxt.mergeValidEvaluated(schCxt, valid);\n if (ifClause)\n gen.assign(ifClause, (0, codegen_1._) `${keyword}`);\n else\n cxt.setParams({ ifClause: keyword });\n };\n }\n },\n};\nfunction hasSchema(it, keyword) {\n const schema = it.schema[keyword];\n return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);\n}\nexports.default = def;\n//# sourceMappingURL=if.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({ keyword, parentSchema, it }) {\n if (parentSchema.if === undefined)\n (0, util_1.checkStrictMode)(it, `\"${keyword}\" without \"if\" is ignored`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=thenElse.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst additionalItems_1 = require(\"./additionalItems\");\nconst prefixItems_1 = require(\"./prefixItems\");\nconst items_1 = require(\"./items\");\nconst items2020_1 = require(\"./items2020\");\nconst contains_1 = require(\"./contains\");\nconst dependencies_1 = require(\"./dependencies\");\nconst propertyNames_1 = require(\"./propertyNames\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst properties_1 = require(\"./properties\");\nconst patternProperties_1 = require(\"./patternProperties\");\nconst not_1 = require(\"./not\");\nconst anyOf_1 = require(\"./anyOf\");\nconst oneOf_1 = require(\"./oneOf\");\nconst allOf_1 = require(\"./allOf\");\nconst if_1 = require(\"./if\");\nconst thenElse_1 = require(\"./thenElse\");\nfunction getApplicator(draft2020 = false) {\n const applicator = [\n // any\n not_1.default,\n anyOf_1.default,\n oneOf_1.default,\n allOf_1.default,\n if_1.default,\n thenElse_1.default,\n // object\n propertyNames_1.default,\n additionalProperties_1.default,\n dependencies_1.default,\n properties_1.default,\n patternProperties_1.default,\n ];\n // array\n if (draft2020)\n applicator.push(prefixItems_1.default, items2020_1.default);\n else\n applicator.push(additionalItems_1.default, items_1.default);\n applicator.push(contains_1.default);\n return applicator;\n}\nexports.default = getApplicator;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message: ({ schemaCode }) => (0, codegen_1.str) `must match format \"${schemaCode}\"`,\n params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt, ruleType) {\n const { gen, data, $data, schema, schemaCode, it } = cxt;\n const { opts, errSchemaPath, schemaEnv, self } = it;\n if (!opts.validateFormats)\n return;\n if ($data)\n validate$DataFormat();\n else\n validateFormat();\n function validate$DataFormat() {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n });\n const fDef = gen.const(\"fDef\", (0, codegen_1._) `${fmts}[${schemaCode}]`);\n const fType = gen.let(\"fType\");\n const format = gen.let(\"format\");\n // TODO simplify\n 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));\n cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));\n function unknownFmt() {\n if (opts.strictSchema === false)\n return codegen_1.nil;\n return (0, codegen_1._) `${schemaCode} && !${format}`;\n }\n function invalidFmt() {\n const callFormat = schemaEnv.$async\n ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : (0, codegen_1._) `${format}(${data})`;\n const validData = (0, codegen_1._) `(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`;\n return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;\n }\n }\n function validateFormat() {\n const formatDef = self.formats[schema];\n if (!formatDef) {\n unknownFormat();\n return;\n }\n if (formatDef === true)\n return;\n const [fmtType, format, fmtRef] = getFormat(formatDef);\n if (fmtType === ruleType)\n cxt.pass(validCondition());\n function unknownFormat() {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg());\n return;\n }\n throw new Error(unknownMsg());\n function unknownMsg() {\n return `unknown format \"${schema}\" ignored in schema at path \"${errSchemaPath}\"`;\n }\n }\n function getFormat(fmtDef) {\n const code = fmtDef instanceof RegExp\n ? (0, codegen_1.regexpCode)(fmtDef)\n : opts.code.formats\n ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`\n : undefined;\n const fmt = gen.scopeValue(\"formats\", { key: schema, ref: fmtDef, code });\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];\n }\n return [\"string\", fmtDef, fmt];\n }\n function validCondition() {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async)\n throw new Error(\"async format in sync schema\");\n return (0, codegen_1._) `await ${fmtRef}(${data})`;\n }\n return typeof format == \"function\" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;\n }\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=format.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst format_1 = require(\"./format\");\nconst format = [format_1.default];\nexports.default = format;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.contentVocabulary = exports.metadataVocabulary = void 0;\nexports.metadataVocabulary = [\n \"title\",\n \"description\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n \"examples\",\n];\nexports.contentVocabulary = [\n \"contentMediaType\",\n \"contentEncoding\",\n \"contentSchema\",\n];\n//# sourceMappingURL=metadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core_1 = require(\"./core\");\nconst validation_1 = require(\"./validation\");\nconst applicator_1 = require(\"./applicator\");\nconst format_1 = require(\"./format\");\nconst metadata_1 = require(\"./metadata\");\nconst draft7Vocabularies = [\n core_1.default,\n validation_1.default,\n (0, applicator_1.default)(),\n format_1.default,\n metadata_1.metadataVocabulary,\n metadata_1.contentVocabulary,\n];\nexports.default = draft7Vocabularies;\n//# sourceMappingURL=draft7.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DiscrError = void 0;\nvar DiscrError;\n(function (DiscrError) {\n DiscrError[\"Tag\"] = \"tag\";\n DiscrError[\"Mapping\"] = \"mapping\";\n})(DiscrError || (exports.DiscrError = DiscrError = {}));\n//# sourceMappingURL=types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst types_1 = require(\"../discriminator/types\");\nconst compile_1 = require(\"../../compile\");\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n};\nconst def = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt) {\n const { gen, data, schema, parentSchema, it } = cxt;\n const { oneOf } = parentSchema;\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\");\n }\n const tagName = schema.propertyName;\n if (typeof tagName != \"string\")\n throw new Error(\"discriminator: requires propertyName\");\n if (schema.mapping)\n throw new Error(\"discriminator: mapping is not supported\");\n if (!oneOf)\n throw new Error(\"discriminator: requires oneOf keyword\");\n const valid = gen.let(\"valid\", false);\n const tag = gen.const(\"tag\", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);\n gen.if((0, codegen_1._) `typeof ${tag} == \"string\"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));\n cxt.ok(valid);\n function validateMapping() {\n const mapping = getMapping();\n gen.if(false);\n for (const tagValue in mapping) {\n gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);\n gen.assign(valid, applyTagSchema(mapping[tagValue]));\n }\n gen.else();\n cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });\n gen.endIf();\n }\n function applyTagSchema(schemaProp) {\n const _valid = gen.name(\"valid\");\n const schCxt = cxt.subschema({ keyword: \"oneOf\", schemaProp }, _valid);\n cxt.mergeEvaluated(schCxt, codegen_1.Name);\n return _valid;\n }\n function getMapping() {\n var _a;\n const oneOfMapping = {};\n const topRequired = hasRequired(parentSchema);\n let tagRequired = true;\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i];\n if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {\n const ref = sch.$ref;\n sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);\n if (sch instanceof compile_1.SchemaEnv)\n sch = sch.schema;\n if (sch === undefined)\n throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);\n }\n const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];\n if (typeof propSch != \"object\") {\n throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`);\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch));\n addMappings(propSch, i);\n }\n if (!tagRequired)\n throw new Error(`discriminator: \"${tagName}\" must be required`);\n return oneOfMapping;\n function hasRequired({ required }) {\n return Array.isArray(required) && required.includes(tagName);\n }\n function addMappings(sch, i) {\n if (sch.const) {\n addMapping(sch.const, i);\n }\n else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i);\n }\n }\n else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`);\n }\n }\n function addMapping(tagValue, i) {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`);\n }\n oneOfMapping[tagValue] = i;\n }\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=index.js.map","","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;\nconst core_1 = require(\"./core\");\nconst draft7_1 = require(\"./vocabularies/draft7\");\nconst discriminator_1 = require(\"./vocabularies/discriminator\");\nconst draft7MetaSchema = require(\"./refs/json-schema-draft-07.json\");\nconst META_SUPPORT_DATA = [\"/properties\"];\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\";\nclass Ajv extends core_1.default {\n _addVocabularies() {\n super._addVocabularies();\n draft7_1.default.forEach((v) => this.addVocabulary(v));\n if (this.opts.discriminator)\n this.addKeyword(discriminator_1.default);\n }\n _addDefaultMetaSchema() {\n super._addDefaultMetaSchema();\n if (!this.opts.meta)\n return;\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n : draft7MetaSchema;\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID;\n }\n defaultMeta() {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));\n }\n}\nexports.Ajv = Ajv;\nmodule.exports = exports = Ajv;\nmodule.exports.Ajv = Ajv;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = Ajv;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nvar validation_error_1 = require(\"./runtime/validation_error\");\nObject.defineProperty(exports, \"ValidationError\", { enumerable: true, get: function () { return validation_error_1.default; } });\nvar ref_error_1 = require(\"./compile/ref_error\");\nObject.defineProperty(exports, \"MissingRefError\", { enumerable: true, get: function () { return ref_error_1.default; } });\n//# sourceMappingURL=ajv.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatNames = exports.fastFormats = exports.fullFormats = void 0;\nfunction fmtDef(validate, compare) {\n return { validate, compare };\n}\nexports.fullFormats = {\n // date: http://tools.ietf.org/html/rfc3339#section-5.6\n date: fmtDef(date, compareDate),\n // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n time: fmtDef(getTime(true), compareTime),\n \"date-time\": fmtDef(getDateTime(true), compareDateTime),\n \"iso-time\": fmtDef(getTime(), compareIsoTime),\n \"iso-date-time\": fmtDef(getDateTime(), compareIsoDateTime),\n // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n duration: /^P(?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[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,\n // uri-template: https://tools.ietf.org/html/rfc6570\n \"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,\n // For the source: https://gist.github.com/dperini/729294\n // For test cases: https://mathiasbynens.be/demo/url-regex\n 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,\n 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,\n 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,\n // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n 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)$/,\n 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,\n regex,\n // uuid: http://tools.ietf.org/html/rfc4122\n uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n // JSON-pointer: https://tools.ietf.org/html/rfc6901\n // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n // byte: https://github.com/miguelmota/is-base64\n byte,\n // signed 32 bit integer\n int32: { type: \"number\", validate: validateInt32 },\n // signed 64 bit integer\n int64: { type: \"number\", validate: validateInt64 },\n // C-type float\n float: { type: \"number\", validate: validateNumber },\n // C-type double\n double: { type: \"number\", validate: validateNumber },\n // hint to the UI to hide input strings\n password: true,\n // unchecked string payload\n binary: true,\n};\nexports.fastFormats = {\n ...exports.fullFormats,\n date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n time: fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i, compareTime),\n \"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),\n \"iso-time\": fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i, compareIsoTime),\n \"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),\n // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n // email (sources from jsen validator):\n // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n 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,\n};\nexports.formatNames = Object.keys(exports.fullFormats);\nfunction isLeapYear(year) {\n // https://tools.ietf.org/html/rfc3339#appendix-C\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nfunction date(str) {\n // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n const matches = DATE.exec(str);\n if (!matches)\n return false;\n const year = +matches[1];\n const month = +matches[2];\n const day = +matches[3];\n return (month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));\n}\nfunction compareDate(d1, d2) {\n if (!(d1 && d2))\n return undefined;\n if (d1 > d2)\n return 1;\n if (d1 < d2)\n return -1;\n return 0;\n}\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i;\nfunction getTime(strictTimeZone) {\n return function time(str) {\n const matches = TIME.exec(str);\n if (!matches)\n return false;\n const hr = +matches[1];\n const min = +matches[2];\n const sec = +matches[3];\n const tz = matches[4];\n const tzSign = matches[5] === \"-\" ? -1 : 1;\n const tzH = +(matches[6] || 0);\n const tzM = +(matches[7] || 0);\n if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz))\n return false;\n if (hr <= 23 && min <= 59 && sec < 60)\n return true;\n // leap second\n const utcMin = min - tzM * tzSign;\n const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);\n return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;\n };\n}\nfunction compareTime(s1, s2) {\n if (!(s1 && s2))\n return undefined;\n const t1 = new Date(\"2020-01-01T\" + s1).valueOf();\n const t2 = new Date(\"2020-01-01T\" + s2).valueOf();\n if (!(t1 && t2))\n return undefined;\n return t1 - t2;\n}\nfunction compareIsoTime(t1, t2) {\n if (!(t1 && t2))\n return undefined;\n const a1 = TIME.exec(t1);\n const a2 = TIME.exec(t2);\n if (!(a1 && a2))\n return undefined;\n t1 = a1[1] + a1[2] + a1[3];\n t2 = a2[1] + a2[2] + a2[3];\n if (t1 > t2)\n return 1;\n if (t1 < t2)\n return -1;\n return 0;\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction getDateTime(strictTimeZone) {\n const time = getTime(strictTimeZone);\n return function date_time(str) {\n // http://tools.ietf.org/html/rfc3339#section-5.6\n const dateTime = str.split(DATE_TIME_SEPARATOR);\n return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);\n };\n}\nfunction compareDateTime(dt1, dt2) {\n if (!(dt1 && dt2))\n return undefined;\n const d1 = new Date(dt1).valueOf();\n const d2 = new Date(dt2).valueOf();\n if (!(d1 && d2))\n return undefined;\n return d1 - d2;\n}\nfunction compareIsoDateTime(dt1, dt2) {\n if (!(dt1 && dt2))\n return undefined;\n const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);\n const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);\n const res = compareDate(d1, d2);\n if (res === undefined)\n return undefined;\n return res || compareTime(t1, t2);\n}\nconst NOT_URI_FRAGMENT = /\\/|:/;\nconst 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;\nfunction uri(str) {\n // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n return NOT_URI_FRAGMENT.test(str) && URI.test(str);\n}\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;\nfunction byte(str) {\n BYTE.lastIndex = 0;\n return BYTE.test(str);\n}\nconst MIN_INT32 = -(2 ** 31);\nconst MAX_INT32 = 2 ** 31 - 1;\nfunction validateInt32(value) {\n return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;\n}\nfunction validateInt64(value) {\n // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n return Number.isInteger(value);\n}\nfunction validateNumber() {\n return true;\n}\nconst Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n if (Z_ANCHOR.test(str))\n return false;\n try {\n new RegExp(str);\n return true;\n }\n catch (e) {\n return false;\n }\n}\n//# sourceMappingURL=formats.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatLimitDefinition = void 0;\nconst ajv_1 = require(\"ajv\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n formatMaximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n formatMinimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n formatExclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n formatExclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`,\n params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nexports.formatLimitDefinition = {\n keyword: Object.keys(KWDs),\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, schemaCode, keyword, it } = cxt;\n const { opts, self } = it;\n if (!opts.validateFormats)\n return;\n const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, \"format\");\n if (fCxt.$data)\n validate$DataFormat();\n else\n validateFormat();\n function validate$DataFormat() {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n });\n const fmt = gen.const(\"fmt\", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`);\n 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)));\n }\n function validateFormat() {\n const format = fCxt.schema;\n const fmtDef = self.formats[format];\n if (!fmtDef || fmtDef === true)\n return;\n if (typeof fmtDef != \"object\" ||\n fmtDef instanceof RegExp ||\n typeof fmtDef.compare != \"function\") {\n throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`);\n }\n const fmt = gen.scopeValue(\"formats\", {\n key: format,\n ref: fmtDef,\n code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined,\n });\n cxt.fail$data(compareCode(fmt));\n }\n function compareCode(fmt) {\n return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;\n }\n },\n dependencies: [\"format\"],\n};\nconst formatLimitPlugin = (ajv) => {\n ajv.addKeyword(exports.formatLimitDefinition);\n return ajv;\n};\nexports.default = formatLimitPlugin;\n//# sourceMappingURL=limit.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst formats_1 = require(\"./formats\");\nconst limit_1 = require(\"./limit\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst fullName = new codegen_1.Name(\"fullFormats\");\nconst fastName = new codegen_1.Name(\"fastFormats\");\nconst formatsPlugin = (ajv, opts = { keywords: true }) => {\n if (Array.isArray(opts)) {\n addFormats(ajv, opts, formats_1.fullFormats, fullName);\n return ajv;\n }\n const [formats, exportName] = opts.mode === \"fast\" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];\n const list = opts.formats || formats_1.formatNames;\n addFormats(ajv, list, formats, exportName);\n if (opts.keywords)\n (0, limit_1.default)(ajv);\n return ajv;\n};\nformatsPlugin.get = (name, mode = \"full\") => {\n const formats = mode === \"fast\" ? formats_1.fastFormats : formats_1.fullFormats;\n const f = formats[name];\n if (!f)\n throw new Error(`Unknown format \"${name}\"`);\n return f;\n};\nfunction addFormats(ajv, list, fs, exportName) {\n var _a;\n var _b;\n (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require(\"ajv-formats/dist/formats\").${exportName}`);\n for (const f of list)\n ajv.addFormat(f, fs[f]);\n}\nmodule.exports = exports = formatsPlugin;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = formatsPlugin;\n//# sourceMappingURL=index.js.map","/**\n * AJV-based JSON Schema validator provider\n */\nimport Ajv from 'ajv';\nimport _addFormats from 'ajv-formats';\nfunction createDefaultAjvInstance() {\n const ajv = new Ajv({\n strict: false,\n validateFormats: true,\n validateSchema: false,\n allErrors: true\n });\n const addFormats = _addFormats;\n addFormats(ajv);\n return ajv;\n}\n/**\n * @example\n * ```typescript\n * // Use with default AJV instance (recommended)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Use with custom AJV instance\n * import { Ajv } from 'ajv';\n * const ajv = new Ajv({ strict: true, allErrors: true });\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\nexport class AjvJsonSchemaValidator {\n /**\n * Create an AJV validator\n *\n * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.\n *\n * @example\n * ```typescript\n * // Use default configuration (recommended for most cases)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Or provide custom AJV instance for advanced configuration\n * import { Ajv } from 'ajv';\n * import addFormats from 'ajv-formats';\n *\n * const ajv = new Ajv({ validateFormats: true });\n * addFormats(ajv);\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\n constructor(ajv) {\n this._ajv = ajv ?? createDefaultAjvInstance();\n }\n /**\n * Create a validator for the given JSON Schema\n *\n * The validator is compiled once and can be reused multiple times.\n * If the schema has an $id, it will be cached by AJV automatically.\n *\n * @param schema - Standard JSON Schema object\n * @returns A validator function that validates input data\n */\n getValidator(schema) {\n // Check if schema has $id and is already compiled/cached\n const ajvValidator = '$id' in schema && typeof schema.$id === 'string'\n ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema))\n : this._ajv.compile(schema);\n return (input) => {\n const valid = ajvValidator(input);\n if (valid) {\n return {\n valid: true,\n data: input,\n errorMessage: undefined\n };\n }\n else {\n return {\n valid: false,\n data: undefined,\n errorMessage: this._ajv.errorsText(ajvValidator.errors)\n };\n }\n };\n }\n}\n//# sourceMappingURL=ajv-provider.js.map","/**\n * Experimental client task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CallToolResultSchema, McpError, ErrorCode } from '../../types.js';\n/**\n * Experimental task features for MCP clients.\n *\n * Access via `client.experimental.tasks`:\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });\n * const task = await client.experimental.tasks.getTask(taskId);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalClientTasks {\n constructor(_client) {\n this._client = _client;\n }\n /**\n * Calls a tool and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to tool execution, allowing you to\n * observe intermediate task status updates for long-running tool calls.\n * Automatically validates structured output if the tool has an outputSchema.\n *\n * @example\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Tool execution started:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Tool status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Tool result:', message.result);\n * break;\n * case 'error':\n * console.error('Tool error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - Tool call parameters (name and arguments)\n * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n async *callToolStream(params, resultSchema = CallToolResultSchema, options) {\n // Access Client's internal methods\n const clientInternal = this._client;\n // Add task creation parameters if server supports it and not explicitly provided\n const optionsWithTask = {\n ...options,\n // We check if the tool is known to be a task during auto-configuration, but assume\n // the caller knows what they're doing if they pass this explicitly\n task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)\n };\n const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);\n // Get the validator for this tool (if it has an output schema)\n const validator = clientInternal.getToolOutputValidator(params.name);\n // Iterate through the stream and validate the final result if needed\n for await (const message of stream) {\n // If this is a result message and the tool has an output schema, validate it\n if (message.type === 'result' && validator) {\n const result = message.result;\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)\n };\n return;\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)\n };\n return;\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n yield { type: 'error', error };\n return;\n }\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)\n };\n return;\n }\n }\n }\n // Yield the message (either validated result or any other message type)\n yield message;\n }\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._client.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.cancelTask({ taskId }, options);\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._client.requestStream(request, resultSchema, options);\n }\n}\n//# sourceMappingURL=client.js.map","/**\n * Experimental task capability assertion helpers.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n/**\n * Asserts that task creation is supported for tools/call.\n * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertToolsCallTaskCapability(requests, method, entityName) {\n if (!requests) {\n throw new Error(`${entityName} does not support task creation (required for ${method})`);\n }\n switch (method) {\n case 'tools/call':\n if (!requests.tools?.call) {\n throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);\n }\n break;\n default:\n // Method doesn't support tasks, which is fine - no error\n break;\n }\n}\n/**\n * Asserts that task creation is supported for sampling/createMessage or elicitation/create.\n * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertClientRequestTaskCapability(requests, method, entityName) {\n if (!requests) {\n throw new Error(`${entityName} does not support task creation (required for ${method})`);\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!requests.sampling?.createMessage) {\n throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!requests.elicitation?.create) {\n throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);\n }\n break;\n default:\n // Method doesn't support tasks, which is fine - no error\n break;\n }\n}\n//# sourceMappingURL=helpers.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js';\nimport { ExperimentalClientTasks } from '../experimental/tasks/client.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * Elicitation default application helper. Applies defaults to the data based on the schema.\n *\n * @param schema - The schema to apply defaults to.\n * @param data - The data to apply defaults to.\n */\nfunction applyElicitationDefaults(schema, data) {\n if (!schema || data === null || typeof data !== 'object')\n return;\n // Handle object properties\n if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {\n const obj = data;\n const props = schema.properties;\n for (const key of Object.keys(props)) {\n const propSchema = props[key];\n // If missing or explicitly undefined, apply default if present\n if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {\n obj[key] = propSchema.default;\n }\n // Recurse into existing nested objects/arrays\n if (obj[key] !== undefined) {\n applyElicitationDefaults(propSchema, obj[key]);\n }\n }\n }\n if (Array.isArray(schema.anyOf)) {\n for (const sub of schema.anyOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n // Combine schemas\n if (Array.isArray(schema.oneOf)) {\n for (const sub of schema.oneOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n}\n/**\n * Determines which elicitation modes are supported based on declared client capabilities.\n *\n * According to the spec:\n * - An empty elicitation capability object defaults to form mode support (backwards compatibility)\n * - URL mode is only supported if explicitly declared\n *\n * @param capabilities - The client's elicitation capabilities\n * @returns An object indicating which modes are supported\n */\nexport function getSupportedElicitationModes(capabilities) {\n if (!capabilities) {\n return { supportsFormMode: false, supportsUrlMode: false };\n }\n const hasFormCapability = capabilities.form !== undefined;\n const hasUrlCapability = capabilities.url !== undefined;\n // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)\n const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);\n const supportsUrlMode = hasUrlCapability;\n return { supportsFormMode, supportsUrlMode };\n}\n/**\n * An MCP client on top of a pluggable transport.\n *\n * The client will automatically begin the initialization flow with the server when connect() is called.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed client\n * const client = new Client<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomClient\",\n * version: \"1.0.0\"\n * })\n * ```\n */\nexport class Client extends Protocol {\n /**\n * Initializes this client with the given name and version information.\n */\n constructor(_clientInfo, options) {\n super(options);\n this._clientInfo = _clientInfo;\n this._cachedToolOutputValidators = new Map();\n this._cachedKnownTaskTools = new Set();\n this._cachedRequiredTaskTools = new Set();\n this._listChangedDebounceTimers = new Map();\n this._capabilities = options?.capabilities ?? {};\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n // Store list changed config for setup after connection (when we know server capabilities)\n if (options?.listChanged) {\n this._pendingListChangedConfig = options.listChanged;\n }\n }\n /**\n * Set up handlers for list changed notifications based on config and server capabilities.\n * This should only be called after initialization when server capabilities are known.\n * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.\n * @internal\n */\n _setupListChangedHandlers(config) {\n if (config.tools && this._serverCapabilities?.tools?.listChanged) {\n this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {\n const result = await this.listTools();\n return result.tools;\n });\n }\n if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {\n this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {\n const result = await this.listPrompts();\n return result.prompts;\n });\n }\n if (config.resources && this._serverCapabilities?.resources?.listChanged) {\n this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {\n const result = await this.listResources();\n return result.resources;\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalClientTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce client-side validation for elicitation.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value using type-safe property access\n let methodValue;\n if (isZ4Schema(methodSchema)) {\n const v4Schema = methodSchema;\n const v4Def = v4Schema._zod?.def;\n methodValue = v4Def?.value ?? v4Schema.value;\n }\n else {\n const v3Schema = methodSchema;\n const legacyDef = v3Schema._def;\n methodValue = legacyDef?.value ?? v3Schema.value;\n }\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'elicitation/create') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(ElicitRequestSchema, request);\n if (!validatedRequest.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n params.mode = params.mode ?? 'form';\n const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);\n if (params.mode === 'form' && !supportsFormMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');\n }\n if (params.mode === 'url' && !supportsUrlMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');\n }\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against ElicitResultSchema\n const validationResult = safeParse(ElicitResultSchema, result);\n if (!validationResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);\n }\n const validatedResult = validationResult.data;\n const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;\n if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {\n if (this._capabilities.elicitation?.form?.applyDefaults) {\n try {\n applyElicitationDefaults(requestedSchema, validatedResult.content);\n }\n catch {\n // gracefully ignore errors in default application\n }\n }\n }\n return validatedResult;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n if (method === 'sampling/createMessage') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CreateMessageRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against CreateMessageResultSchema\n const validationResult = safeParse(CreateMessageResultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapability(capability, method) {\n if (!this._serverCapabilities?.[capability]) {\n throw new Error(`Server does not support ${capability} (required for ${method})`);\n }\n }\n async connect(transport, options) {\n await super.connect(transport);\n // When transport sessionId is already set this means we are trying to reconnect.\n // In this case we don't need to initialize again.\n if (transport.sessionId !== undefined) {\n return;\n }\n try {\n const result = await this.request({\n method: 'initialize',\n params: {\n protocolVersion: LATEST_PROTOCOL_VERSION,\n capabilities: this._capabilities,\n clientInfo: this._clientInfo\n }\n }, InitializeResultSchema, options);\n if (result === undefined) {\n throw new Error(`Server sent invalid initialize result: ${result}`);\n }\n if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {\n throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);\n }\n this._serverCapabilities = result.capabilities;\n this._serverVersion = result.serverInfo;\n // HTTP transports must set the protocol version in each header after initialization.\n if (transport.setProtocolVersion) {\n transport.setProtocolVersion(result.protocolVersion);\n }\n this._instructions = result.instructions;\n await this.notification({\n method: 'notifications/initialized'\n });\n // Set up list changed handlers now that we know server capabilities\n if (this._pendingListChangedConfig) {\n this._setupListChangedHandlers(this._pendingListChangedConfig);\n this._pendingListChangedConfig = undefined;\n }\n }\n catch (error) {\n // Disconnect if initialization fails.\n void this.close();\n throw error;\n }\n }\n /**\n * After initialization has completed, this will be populated with the server's reported capabilities.\n */\n getServerCapabilities() {\n return this._serverCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the server's name and version.\n */\n getServerVersion() {\n return this._serverVersion;\n }\n /**\n * After initialization has completed, this may be populated with information about the server's instructions.\n */\n getInstructions() {\n return this._instructions;\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'logging/setLevel':\n if (!this._serverCapabilities?.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._serverCapabilities?.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n case 'resources/subscribe':\n case 'resources/unsubscribe':\n if (!this._serverCapabilities?.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {\n throw new Error(`Server does not support resource subscriptions (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._serverCapabilities?.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'completion/complete':\n if (!this._serverCapabilities?.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'initialize':\n // No specific capability required for initialize\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/roots/list_changed':\n if (!this._capabilities.roots?.listChanged) {\n throw new Error(`Client does not support roots list changed notifications (required for ${method})`);\n }\n break;\n case 'notifications/initialized':\n // No specific capability required for initialized\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!this._capabilities.sampling) {\n throw new Error(`Client does not support sampling capability (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._capabilities.elicitation) {\n throw new Error(`Client does not support elicitation capability (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._capabilities.roots) {\n throw new Error(`Client does not support roots capability (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Client does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertTaskCapability(method) {\n assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');\n }\n async ping(options) {\n return this.request({ method: 'ping' }, EmptyResultSchema, options);\n }\n async complete(params, options) {\n return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);\n }\n async setLoggingLevel(level, options) {\n return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);\n }\n async getPrompt(params, options) {\n return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);\n }\n async listPrompts(params, options) {\n return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);\n }\n async listResources(params, options) {\n return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);\n }\n async listResourceTemplates(params, options) {\n return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);\n }\n async readResource(params, options) {\n return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);\n }\n async subscribeResource(params, options) {\n return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);\n }\n async unsubscribeResource(params, options) {\n return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);\n }\n /**\n * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.\n *\n * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.\n */\n async callTool(params, resultSchema = CallToolResultSchema, options) {\n // Guard: required-task tools need experimental API\n if (this.isToolTaskRequired(params.name)) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool \"${params.name}\" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);\n }\n const result = await this.request({ method: 'tools/call', params }, resultSchema, options);\n // Check if the tool has an outputSchema\n const validator = this.getToolOutputValidator(params.name);\n if (validator) {\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n return result;\n }\n isToolTask(toolName) {\n if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {\n return false;\n }\n return this._cachedKnownTaskTools.has(toolName);\n }\n /**\n * Check if a tool requires task-based execution.\n * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.\n */\n isToolTaskRequired(toolName) {\n return this._cachedRequiredTaskTools.has(toolName);\n }\n /**\n * Cache validators for tool output schemas.\n * Called after listTools() to pre-compile validators for better performance.\n */\n cacheToolMetadata(tools) {\n this._cachedToolOutputValidators.clear();\n this._cachedKnownTaskTools.clear();\n this._cachedRequiredTaskTools.clear();\n for (const tool of tools) {\n // If the tool has an outputSchema, create and cache the validator\n if (tool.outputSchema) {\n const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);\n this._cachedToolOutputValidators.set(tool.name, toolValidator);\n }\n // If the tool supports task-based execution, cache that information\n const taskSupport = tool.execution?.taskSupport;\n if (taskSupport === 'required' || taskSupport === 'optional') {\n this._cachedKnownTaskTools.add(tool.name);\n }\n if (taskSupport === 'required') {\n this._cachedRequiredTaskTools.add(tool.name);\n }\n }\n }\n /**\n * Get cached validator for a tool\n */\n getToolOutputValidator(toolName) {\n return this._cachedToolOutputValidators.get(toolName);\n }\n async listTools(params, options) {\n const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);\n // Cache the tools and their output schemas for future validation\n this.cacheToolMetadata(result.tools);\n return result;\n }\n /**\n * Set up a single list changed handler.\n * @internal\n */\n _setupListChangedHandler(listType, notificationSchema, options, fetcher) {\n // Validate options using Zod schema (validates autoRefresh and debounceMs)\n const parseResult = ListChangedOptionsBaseSchema.safeParse(options);\n if (!parseResult.success) {\n throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);\n }\n // Validate callback\n if (typeof options.onChanged !== 'function') {\n throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);\n }\n const { autoRefresh, debounceMs } = parseResult.data;\n const { onChanged } = options;\n const refresh = async () => {\n if (!autoRefresh) {\n onChanged(null, null);\n return;\n }\n try {\n const items = await fetcher();\n onChanged(null, items);\n }\n catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n onChanged(error, null);\n }\n };\n const handler = () => {\n if (debounceMs) {\n // Clear any pending debounce timer for this list type\n const existingTimer = this._listChangedDebounceTimers.get(listType);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n // Set up debounced refresh\n const timer = setTimeout(refresh, debounceMs);\n this._listChangedDebounceTimers.set(listType, timer);\n }\n else {\n // No debounce, refresh immediately\n refresh();\n }\n };\n // Register notification handler\n this.setNotificationHandler(notificationSchema, handler);\n }\n async sendRootsListChanged() {\n return this.notification({ method: 'notifications/roots/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * Normalizes HeadersInit to a plain Record<string, string> for manipulation.\n * Handles Headers objects, arrays of tuples, and plain objects.\n */\nexport function normalizeHeaders(headers) {\n if (!headers)\n return {};\n if (headers instanceof Headers) {\n return Object.fromEntries(headers.entries());\n }\n if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n }\n return { ...headers };\n}\n/**\n * Creates a fetch function that includes base RequestInit options.\n * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.\n *\n * @param baseFetch - The base fetch function to wrap (defaults to global fetch)\n * @param baseInit - The base RequestInit to merge with each request\n * @returns A wrapped fetch function that merges base options with call-specific options\n */\nexport function createFetchWithInit(baseFetch = fetch, baseInit) {\n if (!baseInit) {\n return baseFetch;\n }\n // Return a wrapped fetch that merges base RequestInit with call-specific init\n return async (url, init) => {\n const mergedInit = {\n ...baseInit,\n ...init,\n // Headers need special handling - merge instead of replace\n headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers\n };\n return baseFetch(url, mergedInit);\n };\n}\n//# sourceMappingURL=transport.js.map","let crypto;\ncrypto =\n globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL\n globalThis.crypto ?? // Node.js >18\n import(\"node:crypto\").then(m => m.webcrypto); // Node.js <18 Non-REPL\n/**\n * Creates an array of length `size` of random bytes\n * @param size\n * @returns Array of random ints (0 to 255)\n */\nasync function getRandomValues(size) {\n return (await crypto).getRandomValues(new Uint8Array(size));\n}\n/** Generate cryptographically strong random string\n * @param size The desired length of the string\n * @returns The random string\n */\nasync function random(size) {\n const mask = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\";\n const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;\n let result = \"\";\n while (result.length < size) {\n const randomBytes = await getRandomValues(size - result.length);\n for (const randomByte of randomBytes) {\n if (randomByte < evenDistCutoff) {\n result += mask[randomByte % mask.length];\n }\n }\n }\n return result;\n}\n/** Generate a PKCE challenge verifier\n * @param length Length of the verifier\n * @returns A random verifier `length` characters long\n */\nasync function generateVerifier(length) {\n return await random(length);\n}\n/** Generate a PKCE code challenge from a code verifier\n * @param code_verifier\n * @returns The base64 url encoded code challenge\n */\nexport async function generateChallenge(code_verifier) {\n const buffer = await (await crypto).subtle.digest(\"SHA-256\", new TextEncoder().encode(code_verifier));\n // Generate base64url string\n // btoa is deprecated in Node.js but is used here for web browser compatibility\n // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811)\n return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n .replace(/=/g, '');\n}\n/** Generate a PKCE challenge pair\n * @param length Length of the verifer (between 43-128). Defaults to 43.\n * @returns PKCE challenge pair\n */\nexport default async function pkceChallenge(length) {\n if (!length)\n length = 43;\n if (length < 43 || length > 128) {\n throw `Expected a length between 43 and 128. Received ${length}.`;\n }\n const verifier = await generateVerifier(length);\n const challenge = await generateChallenge(verifier);\n return {\n code_verifier: verifier,\n code_challenge: challenge,\n };\n}\n/** Verify that a code_verifier produces the expected code challenge\n * @param code_verifier\n * @param expectedChallenge The code challenge to verify\n * @returns True if challenges are equal. False otherwise.\n */\nexport async function verifyChallenge(code_verifier, expectedChallenge) {\n const actualChallenge = await generateChallenge(code_verifier);\n return actualChallenge === expectedChallenge;\n}\n","import * as z from 'zod/v4';\n/**\n * Reusable URL validation that disallows javascript: scheme\n */\nexport const SafeUrlSchema = z\n .url()\n .superRefine((val, ctx) => {\n if (!URL.canParse(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL must be parseable',\n fatal: true\n });\n return z.NEVER;\n }\n})\n .refine(url => {\n const u = new URL(url);\n return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' });\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n resource: z.string().url(),\n authorization_servers: z.array(SafeUrlSchema).optional(),\n jwks_uri: z.string().url().optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n resource_signing_alg_values_supported: z.array(z.string()).optional(),\n resource_name: z.string().optional(),\n resource_documentation: z.string().optional(),\n resource_policy_uri: z.string().url().optional(),\n resource_tos_uri: z.string().url().optional(),\n tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n authorization_details_types_supported: z.array(z.string()).optional(),\n dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n dpop_bound_access_tokens_required: z.boolean().optional()\n});\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n service_documentation: SafeUrlSchema.optional(),\n revocation_endpoint: SafeUrlSchema.optional(),\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n userinfo_endpoint: SafeUrlSchema.optional(),\n jwks_uri: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n acr_values_supported: z.array(z.string()).optional(),\n subject_types_supported: z.array(z.string()),\n id_token_signing_alg_values_supported: z.array(z.string()),\n id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n display_values_supported: z.array(z.string()).optional(),\n claim_types_supported: z.array(z.string()).optional(),\n claims_supported: z.array(z.string()).optional(),\n service_documentation: z.string().optional(),\n claims_locales_supported: z.array(z.string()).optional(),\n ui_locales_supported: z.array(z.string()).optional(),\n claims_parameter_supported: z.boolean().optional(),\n request_parameter_supported: z.boolean().optional(),\n request_uri_parameter_supported: z.boolean().optional(),\n require_request_uri_registration: z.boolean().optional(),\n op_policy_uri: SafeUrlSchema.optional(),\n op_tos_uri: SafeUrlSchema.optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n ...OpenIdProviderMetadataSchema.shape,\n ...OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true\n }).shape\n});\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n .object({\n access_token: z.string(),\n id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n token_type: z.string(),\n expires_in: z.coerce.number().optional(),\n scope: z.string().optional(),\n refresh_token: z.string().optional()\n})\n .strip();\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional()\n});\n/**\n * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri\n */\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n .object({\n redirect_uris: z.array(SafeUrlSchema),\n token_endpoint_auth_method: z.string().optional(),\n grant_types: z.array(z.string()).optional(),\n response_types: z.array(z.string()).optional(),\n client_name: z.string().optional(),\n client_uri: SafeUrlSchema.optional(),\n logo_uri: OptionalSafeUrlSchema,\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: OptionalSafeUrlSchema,\n policy_uri: z.string().optional(),\n jwks_uri: SafeUrlSchema.optional(),\n jwks: z.any().optional(),\n software_id: z.string().optional(),\n software_version: z.string().optional(),\n software_statement: z.string().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n .object({\n client_id: z.string(),\n client_secret: z.string().optional(),\n client_id_issued_at: z.number().optional(),\n client_secret_expires_at: z.number().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional()\n})\n .strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n .object({\n token: z.string(),\n token_type_hint: z.string().optional()\n})\n .strip();\n//# sourceMappingURL=auth.js.map","/**\n * Utilities for handling OAuth resource URIs.\n */\n/**\n * Converts a server URL to a resource URL by removing the fragment.\n * RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n * Keeps everything else unchanged (scheme, domain, port, path, query).\n */\nexport function resourceUrlFromServerUrl(url) {\n const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);\n resourceURL.hash = ''; // Remove fragment\n return resourceURL;\n}\n/**\n * Checks if a requested resource URL matches a configured resource URL.\n * A requested resource matches if it has the same scheme, domain, port,\n * and its path starts with the configured resource's path.\n *\n * @param requestedResource The resource URL being requested\n * @param configuredResource The resource URL that has been configured\n * @returns true if the requested resource matches the configured resource, false otherwise\n */\nexport function checkResourceAllowed({ requestedResource, configuredResource }) {\n const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);\n const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);\n // Compare the origin (scheme, domain, and port)\n if (requested.origin !== configured.origin) {\n return false;\n }\n // Handle cases like requested=/foo and configured=/foo/\n if (requested.pathname.length < configured.pathname.length) {\n return false;\n }\n // Check if the requested path starts with the configured path\n // Ensure both paths end with / for proper comparison\n // This ensures that if we have paths like \"/api\" and \"/api/users\",\n // we properly detect that \"/api/users\" is a subpath of \"/api\"\n // By adding a trailing slash if missing, we avoid false positives\n // where paths like \"/api123\" would incorrectly match \"/api\"\n const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';\n const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';\n return requestedPath.startsWith(configuredPath);\n}\n//# sourceMappingURL=auth-utils.js.map","/**\n * Base class for all OAuth errors\n */\nexport class OAuthError extends Error {\n constructor(message, errorUri) {\n super(message);\n this.errorUri = errorUri;\n this.name = this.constructor.name;\n }\n /**\n * Converts the error to a standard OAuth error response object\n */\n toResponseObject() {\n const response = {\n error: this.errorCode,\n error_description: this.message\n };\n if (this.errorUri) {\n response.error_uri = this.errorUri;\n }\n return response;\n }\n get errorCode() {\n return this.constructor.errorCode;\n }\n}\n/**\n * Invalid request error - The request is missing a required parameter,\n * includes an invalid parameter value, includes a parameter more than once,\n * or is otherwise malformed.\n */\nexport class InvalidRequestError extends OAuthError {\n}\nInvalidRequestError.errorCode = 'invalid_request';\n/**\n * Invalid client error - Client authentication failed (e.g., unknown client, no client\n * authentication included, or unsupported authentication method).\n */\nexport class InvalidClientError extends OAuthError {\n}\nInvalidClientError.errorCode = 'invalid_client';\n/**\n * Invalid grant error - The provided authorization grant or refresh token is\n * invalid, expired, revoked, does not match the redirection URI used in the\n * authorization request, or was issued to another client.\n */\nexport class InvalidGrantError extends OAuthError {\n}\nInvalidGrantError.errorCode = 'invalid_grant';\n/**\n * Unauthorized client error - The authenticated client is not authorized to use\n * this authorization grant type.\n */\nexport class UnauthorizedClientError extends OAuthError {\n}\nUnauthorizedClientError.errorCode = 'unauthorized_client';\n/**\n * Unsupported grant type error - The authorization grant type is not supported\n * by the authorization server.\n */\nexport class UnsupportedGrantTypeError extends OAuthError {\n}\nUnsupportedGrantTypeError.errorCode = 'unsupported_grant_type';\n/**\n * Invalid scope error - The requested scope is invalid, unknown, malformed, or\n * exceeds the scope granted by the resource owner.\n */\nexport class InvalidScopeError extends OAuthError {\n}\nInvalidScopeError.errorCode = 'invalid_scope';\n/**\n * Access denied error - The resource owner or authorization server denied the request.\n */\nexport class AccessDeniedError extends OAuthError {\n}\nAccessDeniedError.errorCode = 'access_denied';\n/**\n * Server error - The authorization server encountered an unexpected condition\n * that prevented it from fulfilling the request.\n */\nexport class ServerError extends OAuthError {\n}\nServerError.errorCode = 'server_error';\n/**\n * Temporarily unavailable error - The authorization server is currently unable to\n * handle the request due to a temporary overloading or maintenance of the server.\n */\nexport class TemporarilyUnavailableError extends OAuthError {\n}\nTemporarilyUnavailableError.errorCode = 'temporarily_unavailable';\n/**\n * Unsupported response type error - The authorization server does not support\n * obtaining an authorization code using this method.\n */\nexport class UnsupportedResponseTypeError extends OAuthError {\n}\nUnsupportedResponseTypeError.errorCode = 'unsupported_response_type';\n/**\n * Unsupported token type error - The authorization server does not support\n * the requested token type.\n */\nexport class UnsupportedTokenTypeError extends OAuthError {\n}\nUnsupportedTokenTypeError.errorCode = 'unsupported_token_type';\n/**\n * Invalid token error - The access token provided is expired, revoked, malformed,\n * or invalid for other reasons.\n */\nexport class InvalidTokenError extends OAuthError {\n}\nInvalidTokenError.errorCode = 'invalid_token';\n/**\n * Method not allowed error - The HTTP method used is not allowed for this endpoint.\n * (Custom, non-standard error)\n */\nexport class MethodNotAllowedError extends OAuthError {\n}\nMethodNotAllowedError.errorCode = 'method_not_allowed';\n/**\n * Too many requests error - Rate limit exceeded.\n * (Custom, non-standard error based on RFC 6585)\n */\nexport class TooManyRequestsError extends OAuthError {\n}\nTooManyRequestsError.errorCode = 'too_many_requests';\n/**\n * Invalid client metadata error - The client metadata is invalid.\n * (Custom error for dynamic client registration - RFC 7591)\n */\nexport class InvalidClientMetadataError extends OAuthError {\n}\nInvalidClientMetadataError.errorCode = 'invalid_client_metadata';\n/**\n * Insufficient scope error - The request requires higher privileges than provided by the access token.\n */\nexport class InsufficientScopeError extends OAuthError {\n}\nInsufficientScopeError.errorCode = 'insufficient_scope';\n/**\n * Invalid target error - The requested resource is invalid, missing, unknown, or malformed.\n * (Custom error for resource indicators - RFC 8707)\n */\nexport class InvalidTargetError extends OAuthError {\n}\nInvalidTargetError.errorCode = 'invalid_target';\n/**\n * A utility class for defining one-off error codes\n */\nexport class CustomOAuthError extends OAuthError {\n constructor(customErrorCode, message, errorUri) {\n super(message, errorUri);\n this.customErrorCode = customErrorCode;\n }\n get errorCode() {\n return this.customErrorCode;\n }\n}\n/**\n * A full list of all OAuthErrors, enabling parsing from error responses\n */\nexport const OAUTH_ERRORS = {\n [InvalidRequestError.errorCode]: InvalidRequestError,\n [InvalidClientError.errorCode]: InvalidClientError,\n [InvalidGrantError.errorCode]: InvalidGrantError,\n [UnauthorizedClientError.errorCode]: UnauthorizedClientError,\n [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,\n [InvalidScopeError.errorCode]: InvalidScopeError,\n [AccessDeniedError.errorCode]: AccessDeniedError,\n [ServerError.errorCode]: ServerError,\n [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,\n [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,\n [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,\n [InvalidTokenError.errorCode]: InvalidTokenError,\n [MethodNotAllowedError.errorCode]: MethodNotAllowedError,\n [TooManyRequestsError.errorCode]: TooManyRequestsError,\n [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,\n [InsufficientScopeError.errorCode]: InsufficientScopeError,\n [InvalidTargetError.errorCode]: InvalidTargetError\n};\n//# sourceMappingURL=errors.js.map","import pkceChallenge from 'pkce-challenge';\nimport { LATEST_PROTOCOL_VERSION } from '../types.js';\nimport { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js';\nimport { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js';\nimport { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js';\nimport { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js';\nexport class UnauthorizedError extends Error {\n constructor(message) {\n super(message ?? 'Unauthorized');\n }\n}\nfunction isClientAuthMethod(method) {\n return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);\n}\nconst AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';\nconst AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';\n/**\n * Determines the best client authentication method to use based on server support and client configuration.\n *\n * Priority order (highest to lowest):\n * 1. client_secret_basic (if client secret is available)\n * 2. client_secret_post (if client secret is available)\n * 3. none (for public clients)\n *\n * @param clientInformation - OAuth client information containing credentials\n * @param supportedMethods - Authentication methods supported by the authorization server\n * @returns The selected authentication method\n */\nexport function selectClientAuthMethod(clientInformation, supportedMethods) {\n const hasClientSecret = clientInformation.client_secret !== undefined;\n // If server doesn't specify supported methods, use RFC 6749 defaults\n if (supportedMethods.length === 0) {\n return hasClientSecret ? 'client_secret_post' : 'none';\n }\n // Prefer the method returned by the server during client registration if valid and supported\n if ('token_endpoint_auth_method' in clientInformation &&\n clientInformation.token_endpoint_auth_method &&\n isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&\n supportedMethods.includes(clientInformation.token_endpoint_auth_method)) {\n return clientInformation.token_endpoint_auth_method;\n }\n // Try methods in priority order (most secure first)\n if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {\n return 'client_secret_basic';\n }\n if (hasClientSecret && supportedMethods.includes('client_secret_post')) {\n return 'client_secret_post';\n }\n if (supportedMethods.includes('none')) {\n return 'none';\n }\n // Fallback: use what we have\n return hasClientSecret ? 'client_secret_post' : 'none';\n}\n/**\n * Applies client authentication to the request based on the specified method.\n *\n * Implements OAuth 2.1 client authentication methods:\n * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)\n * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)\n * - none: Public client authentication (RFC 6749 Section 2.1)\n *\n * @param method - The authentication method to use\n * @param clientInformation - OAuth client information containing credentials\n * @param headers - HTTP headers object to modify\n * @param params - URL search parameters to modify\n * @throws {Error} When required credentials are missing\n */\nfunction applyClientAuthentication(method, clientInformation, headers, params) {\n const { client_id, client_secret } = clientInformation;\n switch (method) {\n case 'client_secret_basic':\n applyBasicAuth(client_id, client_secret, headers);\n return;\n case 'client_secret_post':\n applyPostAuth(client_id, client_secret, params);\n return;\n case 'none':\n applyPublicAuth(client_id, params);\n return;\n default:\n throw new Error(`Unsupported client authentication method: ${method}`);\n }\n}\n/**\n * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyBasicAuth(clientId, clientSecret, headers) {\n if (!clientSecret) {\n throw new Error('client_secret_basic authentication requires a client_secret');\n }\n const credentials = btoa(`${clientId}:${clientSecret}`);\n headers.set('Authorization', `Basic ${credentials}`);\n}\n/**\n * Applies POST body authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyPostAuth(clientId, clientSecret, params) {\n params.set('client_id', clientId);\n if (clientSecret) {\n params.set('client_secret', clientSecret);\n }\n}\n/**\n * Applies public client authentication (RFC 6749 Section 2.1)\n */\nfunction applyPublicAuth(clientId, params) {\n params.set('client_id', clientId);\n}\n/**\n * Parses an OAuth error response from a string or Response object.\n *\n * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec\n * and an instance of the appropriate OAuthError subclass will be returned.\n * If parsing fails, it falls back to a generic ServerError that includes\n * the response status (if available) and original content.\n *\n * @param input - A Response object or string containing the error response\n * @returns A Promise that resolves to an OAuthError instance\n */\nexport async function parseErrorResponse(input) {\n const statusCode = input instanceof Response ? input.status : undefined;\n const body = input instanceof Response ? await input.text() : input;\n try {\n const result = OAuthErrorResponseSchema.parse(JSON.parse(body));\n const { error, error_description, error_uri } = result;\n const errorClass = OAUTH_ERRORS[error] || ServerError;\n return new errorClass(error_description || '', error_uri);\n }\n catch (error) {\n // Not a valid OAuth error response, but try to inform the user of the raw data anyway\n const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`;\n return new ServerError(errorMessage);\n }\n}\n/**\n * Orchestrates the full auth flow with a server.\n *\n * This can be used as a single entry point for all authorization functionality,\n * instead of linking together the other lower-level functions in this module.\n */\nexport async function auth(provider, options) {\n try {\n return await authInternal(provider, options);\n }\n catch (error) {\n // Handle recoverable error types by invalidating credentials and retrying\n if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {\n await provider.invalidateCredentials?.('all');\n return await authInternal(provider, options);\n }\n else if (error instanceof InvalidGrantError) {\n await provider.invalidateCredentials?.('tokens');\n return await authInternal(provider, options);\n }\n // Throw otherwise\n throw error;\n }\n}\nasync function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {\n let resourceMetadata;\n let authorizationServerUrl;\n try {\n resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn);\n if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {\n authorizationServerUrl = resourceMetadata.authorization_servers[0];\n }\n }\n catch {\n // Ignore errors and fall back to /.well-known/oauth-authorization-server\n }\n /**\n * If we don't get a valid authorization server metadata from protected resource metadata,\n * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server.\n */\n if (!authorizationServerUrl) {\n authorizationServerUrl = new URL('/', serverUrl);\n }\n const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);\n const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, {\n fetchFn\n });\n // Handle client registration if needed\n let clientInformation = await Promise.resolve(provider.clientInformation());\n if (!clientInformation) {\n if (authorizationCode !== undefined) {\n throw new Error('Existing OAuth client information is required when exchanging an authorization code');\n }\n const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;\n const clientMetadataUrl = provider.clientMetadataUrl;\n if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {\n throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);\n }\n const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;\n if (shouldUseUrlBasedClientId) {\n // SEP-991: URL-based Client IDs\n clientInformation = {\n client_id: clientMetadataUrl\n };\n await provider.saveClientInformation?.(clientInformation);\n }\n else {\n // Fallback to dynamic registration\n if (!provider.saveClientInformation) {\n throw new Error('OAuth client information must be saveable for dynamic registration');\n }\n const fullInformation = await registerClient(authorizationServerUrl, {\n metadata,\n clientMetadata: provider.clientMetadata,\n fetchFn\n });\n await provider.saveClientInformation(fullInformation);\n clientInformation = fullInformation;\n }\n }\n // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL\n const nonInteractiveFlow = !provider.redirectUrl;\n // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows\n if (authorizationCode !== undefined || nonInteractiveFlow) {\n const tokens = await fetchToken(provider, authorizationServerUrl, {\n metadata,\n resource,\n authorizationCode,\n fetchFn\n });\n await provider.saveTokens(tokens);\n return 'AUTHORIZED';\n }\n const tokens = await provider.tokens();\n // Handle token refresh or new authorization\n if (tokens?.refresh_token) {\n try {\n // Attempt to refresh the token\n const newTokens = await refreshAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n refreshToken: tokens.refresh_token,\n resource,\n addClientAuthentication: provider.addClientAuthentication,\n fetchFn\n });\n await provider.saveTokens(newTokens);\n return 'AUTHORIZED';\n }\n catch (error) {\n // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.\n if (!(error instanceof OAuthError) || error instanceof ServerError) {\n // Could not refresh OAuth tokens\n }\n else {\n // Refresh failed for another reason, re-throw\n throw error;\n }\n }\n }\n const state = provider.state ? await provider.state() : undefined;\n // Start new authorization flow\n const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {\n metadata,\n clientInformation,\n state,\n redirectUrl: provider.redirectUrl,\n scope: scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope,\n resource\n });\n await provider.saveCodeVerifier(codeVerifier);\n await provider.redirectToAuthorization(authorizationUrl);\n return 'REDIRECT';\n}\n/**\n * SEP-991: URL-based Client IDs\n * Validate that the client_id is a valid URL with https scheme\n */\nexport function isHttpsUrl(value) {\n if (!value)\n return false;\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && url.pathname !== '/';\n }\n catch {\n return false;\n }\n}\nexport async function selectResourceURL(serverUrl, provider, resourceMetadata) {\n const defaultResource = resourceUrlFromServerUrl(serverUrl);\n // If provider has custom validation, delegate to it\n if (provider.validateResourceURL) {\n return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);\n }\n // Only include resource parameter when Protected Resource Metadata is present\n if (!resourceMetadata) {\n return undefined;\n }\n // Validate that the metadata's resource is compatible with our request\n if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {\n throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);\n }\n // Prefer the resource from metadata since it's what the server is telling us to request\n return new URL(resourceMetadata.resource);\n}\n/**\n * Extract resource_metadata, scope, and error from WWW-Authenticate header.\n */\nexport function extractWWWAuthenticateParams(res) {\n const authenticateHeader = res.headers.get('WWW-Authenticate');\n if (!authenticateHeader) {\n return {};\n }\n const [type, scheme] = authenticateHeader.split(' ');\n if (type.toLowerCase() !== 'bearer' || !scheme) {\n return {};\n }\n const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined;\n let resourceMetadataUrl;\n if (resourceMetadataMatch) {\n try {\n resourceMetadataUrl = new URL(resourceMetadataMatch);\n }\n catch {\n // Ignore invalid URL\n }\n }\n const scope = extractFieldFromWwwAuth(res, 'scope') || undefined;\n const error = extractFieldFromWwwAuth(res, 'error') || undefined;\n return {\n resourceMetadataUrl,\n scope,\n error\n };\n}\n/**\n * Extracts a specific field's value from the WWW-Authenticate header string.\n *\n * @param response The HTTP response object containing the headers.\n * @param fieldName The name of the field to extract (e.g., \"realm\", \"nonce\").\n * @returns The field value\n */\nfunction extractFieldFromWwwAuth(response, fieldName) {\n const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n if (!wwwAuthHeader) {\n return null;\n }\n const pattern = new RegExp(`${fieldName}=(?:\"([^\"]+)\"|([^\\\\s,]+))`);\n const match = wwwAuthHeader.match(pattern);\n if (match) {\n // Pattern matches: field_name=\"value\" or field_name=value (unquoted)\n return match[1] || match[2];\n }\n return null;\n}\n/**\n * Extract resource_metadata from response header.\n * @deprecated Use `extractWWWAuthenticateParams` instead.\n */\nexport function extractResourceMetadataUrl(res) {\n const authenticateHeader = res.headers.get('WWW-Authenticate');\n if (!authenticateHeader) {\n return undefined;\n }\n const [type, scheme] = authenticateHeader.split(' ');\n if (type.toLowerCase() !== 'bearer' || !scheme) {\n return undefined;\n }\n const regex = /resource_metadata=\"([^\"]*)\"/;\n const match = regex.exec(authenticateHeader);\n if (!match) {\n return undefined;\n }\n try {\n return new URL(match[1]);\n }\n catch {\n return undefined;\n }\n}\n/**\n * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n */\nexport async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {\n const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, {\n protocolVersion: opts?.protocolVersion,\n metadataUrl: opts?.resourceMetadataUrl\n });\n if (!response || response.status === 404) {\n await response?.body?.cancel();\n throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);\n }\n return OAuthProtectedResourceMetadataSchema.parse(await response.json());\n}\n/**\n * Helper function to handle fetch with CORS retry logic\n */\nasync function fetchWithCorsRetry(url, headers, fetchFn = fetch) {\n try {\n return await fetchFn(url, { headers });\n }\n catch (error) {\n if (error instanceof TypeError) {\n if (headers) {\n // CORS errors come back as TypeError, retry without headers\n return fetchWithCorsRetry(url, undefined, fetchFn);\n }\n else {\n // We're getting CORS errors on retry too, return undefined\n return undefined;\n }\n }\n throw error;\n }\n}\n/**\n * Constructs the well-known path for auth-related metadata discovery\n */\nfunction buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) {\n // Strip trailing slash from pathname to avoid double slashes\n if (pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;\n}\n/**\n * Tries to discover OAuth metadata at a specific URL\n */\nasync function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {\n const headers = {\n 'MCP-Protocol-Version': protocolVersion\n };\n return await fetchWithCorsRetry(url, headers, fetchFn);\n}\n/**\n * Determines if fallback to root discovery should be attempted\n */\nfunction shouldAttemptFallback(response, pathname) {\n return !response || (response.status >= 400 && response.status < 500 && pathname !== '/');\n}\n/**\n * Generic function for discovering OAuth metadata with fallback support\n */\nasync function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {\n const issuer = new URL(serverUrl);\n const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;\n let url;\n if (opts?.metadataUrl) {\n url = new URL(opts.metadataUrl);\n }\n else {\n // Try path-aware discovery first\n const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);\n url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);\n url.search = issuer.search;\n }\n let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);\n // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery\n if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {\n const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);\n response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);\n }\n return response;\n}\n/**\n * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n *\n * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.\n */\nexport async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) {\n if (typeof issuer === 'string') {\n issuer = new URL(issuer);\n }\n if (!authorizationServerUrl) {\n authorizationServerUrl = issuer;\n }\n if (typeof authorizationServerUrl === 'string') {\n authorizationServerUrl = new URL(authorizationServerUrl);\n }\n protocolVersion ?? (protocolVersion = LATEST_PROTOCOL_VERSION);\n const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, {\n protocolVersion,\n metadataServerUrl: authorizationServerUrl\n });\n if (!response || response.status === 404) {\n await response?.body?.cancel();\n return undefined;\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);\n }\n return OAuthMetadataSchema.parse(await response.json());\n}\n/**\n * Builds a list of discovery URLs to try for authorization server metadata.\n * URLs are returned in priority order:\n * 1. OAuth metadata at the given URL\n * 2. OIDC metadata endpoints at the given URL\n */\nexport function buildDiscoveryUrls(authorizationServerUrl) {\n const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl;\n const hasPath = url.pathname !== '/';\n const urlsToTry = [];\n if (!hasPath) {\n // Root path: https://example.com/.well-known/oauth-authorization-server\n urlsToTry.push({\n url: new URL('/.well-known/oauth-authorization-server', url.origin),\n type: 'oauth'\n });\n // OIDC: https://example.com/.well-known/openid-configuration\n urlsToTry.push({\n url: new URL(`/.well-known/openid-configuration`, url.origin),\n type: 'oidc'\n });\n return urlsToTry;\n }\n // Strip trailing slash from pathname to avoid double slashes\n let pathname = url.pathname;\n if (pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n // 1. OAuth metadata at the given URL\n // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1\n urlsToTry.push({\n url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),\n type: 'oauth'\n });\n // 2. OIDC metadata endpoints\n // RFC 8414 style: Insert /.well-known/openid-configuration before the path\n urlsToTry.push({\n url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),\n type: 'oidc'\n });\n // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path\n urlsToTry.push({\n url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),\n type: 'oidc'\n });\n return urlsToTry;\n}\n/**\n * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata\n * and OpenID Connect Discovery 1.0 specifications.\n *\n * This function implements a fallback strategy for authorization server discovery:\n * 1. Attempts RFC 8414 OAuth metadata discovery first\n * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery\n *\n * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's\n * protected resource metadata, or the MCP server's URL if the\n * metadata was not found.\n * @param options - Configuration options\n * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch\n * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION\n * @returns Promise resolving to authorization server metadata, or undefined if discovery fails\n */\nexport async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {\n const headers = {\n 'MCP-Protocol-Version': protocolVersion,\n Accept: 'application/json'\n };\n // Get the list of URLs to try\n const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);\n // Try each URL in order\n for (const { url: endpointUrl, type } of urlsToTry) {\n const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);\n if (!response) {\n /**\n * CORS error occurred - don't throw as the endpoint may not allow CORS,\n * continue trying other possible endpoints\n */\n continue;\n }\n if (!response.ok) {\n await response.body?.cancel();\n // Continue looking for any 4xx response code.\n if (response.status >= 400 && response.status < 500) {\n continue; // Try next URL\n }\n throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`);\n }\n // Parse and validate based on type\n if (type === 'oauth') {\n return OAuthMetadataSchema.parse(await response.json());\n }\n else {\n return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());\n }\n }\n return undefined;\n}\n/**\n * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.\n */\nexport async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {\n let authorizationUrl;\n if (metadata) {\n authorizationUrl = new URL(metadata.authorization_endpoint);\n if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {\n throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);\n }\n if (metadata.code_challenge_methods_supported &&\n !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {\n throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);\n }\n }\n else {\n authorizationUrl = new URL('/authorize', authorizationServerUrl);\n }\n // Generate PKCE challenge\n const challenge = await pkceChallenge();\n const codeVerifier = challenge.code_verifier;\n const codeChallenge = challenge.code_challenge;\n authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE);\n authorizationUrl.searchParams.set('client_id', clientInformation.client_id);\n authorizationUrl.searchParams.set('code_challenge', codeChallenge);\n authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD);\n authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl));\n if (state) {\n authorizationUrl.searchParams.set('state', state);\n }\n if (scope) {\n authorizationUrl.searchParams.set('scope', scope);\n }\n if (scope?.includes('offline_access')) {\n // if the request includes the OIDC-only \"offline_access\" scope,\n // we need to set the prompt to \"consent\" to ensure the user is prompted to grant offline access\n // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess\n authorizationUrl.searchParams.append('prompt', 'consent');\n }\n if (resource) {\n authorizationUrl.searchParams.set('resource', resource.href);\n }\n return { authorizationUrl, codeVerifier };\n}\n/**\n * Prepares token request parameters for an authorization code exchange.\n *\n * This is the default implementation used by fetchToken when the provider\n * doesn't implement prepareTokenRequest.\n *\n * @param authorizationCode - The authorization code received from the authorization endpoint\n * @param codeVerifier - The PKCE code verifier\n * @param redirectUri - The redirect URI used in the authorization request\n * @returns URLSearchParams for the authorization_code grant\n */\nexport function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {\n return new URLSearchParams({\n grant_type: 'authorization_code',\n code: authorizationCode,\n code_verifier: codeVerifier,\n redirect_uri: String(redirectUri)\n });\n}\n/**\n * Internal helper to execute a token request with the given parameters.\n * Used by exchangeAuthorization, refreshAuthorization, and fetchToken.\n */\nasync function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {\n const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl);\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json'\n });\n if (resource) {\n tokenRequestParams.set('resource', resource.href);\n }\n if (addClientAuthentication) {\n await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);\n }\n else if (clientInformation) {\n const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];\n const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);\n applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);\n }\n const response = await (fetchFn ?? fetch)(tokenUrl, {\n method: 'POST',\n headers,\n body: tokenRequestParams\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthTokensSchema.parse(await response.json());\n}\n/**\n * Exchanges an authorization code for an access token with the given server.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Falls back to appropriate defaults when server metadata is unavailable\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, auth code, etc.\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When token exchange fails or authentication is invalid\n */\nexport async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {\n const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);\n return executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation,\n addClientAuthentication,\n resource,\n fetchFn\n });\n}\n/**\n * Exchange a refresh token for an updated access token.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Preserves the original refresh token if a new one is not returned\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, refresh token, etc.\n * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)\n * @throws {Error} When token refresh fails or authentication is invalid\n */\nexport async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {\n const tokenRequestParams = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken\n });\n const tokens = await executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation,\n addClientAuthentication,\n resource,\n fetchFn\n });\n // Preserve original refresh token if server didn't return a new one\n return { refresh_token: refreshToken, ...tokens };\n}\n/**\n * Unified token fetching that works with any grant type via provider.prepareTokenRequest().\n *\n * This function provides a single entry point for obtaining tokens regardless of the\n * OAuth grant type. The provider's prepareTokenRequest() method determines which grant\n * to use and supplies the grant-specific parameters.\n *\n * @param provider - OAuth client provider that implements prepareTokenRequest()\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration for the token request\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails\n *\n * @example\n * // Provider for client_credentials:\n * class MyProvider implements OAuthClientProvider {\n * prepareTokenRequest(scope) {\n * const params = new URLSearchParams({ grant_type: 'client_credentials' });\n * if (scope) params.set('scope', scope);\n * return params;\n * }\n * // ... other methods\n * }\n *\n * const tokens = await fetchToken(provider, authServerUrl, { metadata });\n */\nexport async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {\n const scope = provider.clientMetadata.scope;\n // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code\n let tokenRequestParams;\n if (provider.prepareTokenRequest) {\n tokenRequestParams = await provider.prepareTokenRequest(scope);\n }\n // Default to authorization_code grant if no custom prepareTokenRequest\n if (!tokenRequestParams) {\n if (!authorizationCode) {\n throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required');\n }\n if (!provider.redirectUrl) {\n throw new Error('redirectUrl is required for authorization_code flow');\n }\n const codeVerifier = await provider.codeVerifier();\n tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);\n }\n const clientInformation = await provider.clientInformation();\n return executeTokenRequest(authorizationServerUrl, {\n metadata,\n tokenRequestParams,\n clientInformation: clientInformation ?? undefined,\n addClientAuthentication: provider.addClientAuthentication,\n resource,\n fetchFn\n });\n}\n/**\n * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.\n */\nexport async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) {\n let registrationUrl;\n if (metadata) {\n if (!metadata.registration_endpoint) {\n throw new Error('Incompatible auth server: does not support dynamic client registration');\n }\n registrationUrl = new URL(metadata.registration_endpoint);\n }\n else {\n registrationUrl = new URL('/register', authorizationServerUrl);\n }\n const response = await (fetchFn ?? fetch)(registrationUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(clientMetadata)\n });\n if (!response.ok) {\n throw await parseErrorResponse(response);\n }\n return OAuthClientInformationFullSchema.parse(await response.json());\n}\n//# sourceMappingURL=auth.js.map","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\n if (typeof callbacks == \"function\")\n throw new TypeError(\n \"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;\n let incompleteLine = \"\", isFirstChunk = !0, id, data = \"\", eventType = \"\";\n function feed(newChunk) {\n const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, \"\") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);\n for (const line of complete)\n parseLine(line);\n incompleteLine = incomplete, isFirstChunk = !1;\n }\n function parseLine(line) {\n if (line === \"\") {\n dispatchEvent();\n return;\n }\n if (line.startsWith(\":\")) {\n onComment && onComment(line.slice(line.startsWith(\": \") ? 2 : 1));\n return;\n }\n const fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex !== -1) {\n const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === \" \" ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n return;\n }\n processField(line, \"\", line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value;\n break;\n case \"data\":\n data = `${data}${value}\n`;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n data.length > 0 && onEvent({\n id,\n event: eventType || void 0,\n // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n // then remove the last character from the data buffer.\n data: data.endsWith(`\n`) ? data.slice(0, -1) : data\n }), id = void 0, data = \"\", eventType = \"\";\n }\n function reset(options = {}) {\n incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = \"\", eventType = \"\", incompleteLine = \"\";\n }\n return { feed, reset };\n}\nfunction splitLines(chunk) {\n const lines = [];\n let incompleteLine = \"\", searchIndex = 0;\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n 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) {\n incompleteLine = chunk.slice(searchIndex);\n break;\n } else {\n const line = chunk.slice(searchIndex, lineEnd);\n lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === \"\\r\" && chunk[searchIndex] === `\n` && searchIndex++;\n }\n }\n return [lines, incompleteLine];\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n },\n onRetry,\n onComment\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js';\nimport { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js';\nimport { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';\nimport { EventSourceParserStream } from 'eventsource-parser/stream';\n// Default reconnection options for StreamableHTTP connections\nconst DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {\n initialReconnectionDelay: 1000,\n maxReconnectionDelay: 30000,\n reconnectionDelayGrowFactor: 1.5,\n maxRetries: 2\n};\nexport class StreamableHTTPError extends Error {\n constructor(code, message) {\n super(`Streamable HTTP error: ${message}`);\n this.code = code;\n }\n}\n/**\n * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events\n * for receiving messages.\n */\nexport class StreamableHTTPClientTransport {\n constructor(url, opts) {\n this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401\n this._url = url;\n this._resourceMetadataUrl = undefined;\n this._scope = undefined;\n this._requestInit = opts?.requestInit;\n this._authProvider = opts?.authProvider;\n this._fetch = opts?.fetch;\n this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);\n this._sessionId = opts?.sessionId;\n this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;\n }\n async _authThenStart() {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n let result;\n try {\n result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return await this._startOrAuthSse({ resumptionToken: undefined });\n }\n async _commonHeaders() {\n const headers = {};\n if (this._authProvider) {\n const tokens = await this._authProvider.tokens();\n if (tokens) {\n headers['Authorization'] = `Bearer ${tokens.access_token}`;\n }\n }\n if (this._sessionId) {\n headers['mcp-session-id'] = this._sessionId;\n }\n if (this._protocolVersion) {\n headers['mcp-protocol-version'] = this._protocolVersion;\n }\n const extraHeaders = normalizeHeaders(this._requestInit?.headers);\n return new Headers({\n ...headers,\n ...extraHeaders\n });\n }\n async _startOrAuthSse(options) {\n const { resumptionToken } = options;\n try {\n // Try to open an initial SSE stream with GET to listen for server messages\n // This is optional according to the spec - server may not support it\n const headers = await this._commonHeaders();\n headers.set('Accept', 'text/event-stream');\n // Include Last-Event-ID header for resumable streams if provided\n if (resumptionToken) {\n headers.set('last-event-id', resumptionToken);\n }\n const response = await (this._fetch ?? fetch)(this._url, {\n method: 'GET',\n headers,\n signal: this._abortController?.signal\n });\n if (!response.ok) {\n await response.body?.cancel();\n if (response.status === 401 && this._authProvider) {\n // Need to authenticate\n return await this._authThenStart();\n }\n // 405 indicates that the server does not offer an SSE stream at GET endpoint\n // This is an expected case that should not trigger an error\n if (response.status === 405) {\n return;\n }\n throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);\n }\n this._handleSseStream(response.body, options, true);\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n }\n /**\n * Calculates the next reconnection delay using backoff algorithm\n *\n * @param attempt Current reconnection attempt count for the specific stream\n * @returns Time to wait in milliseconds before next reconnection attempt\n */\n _getNextReconnectionDelay(attempt) {\n // Use server-provided retry value if available\n if (this._serverRetryMs !== undefined) {\n return this._serverRetryMs;\n }\n // Fall back to exponential backoff\n const initialDelay = this._reconnectionOptions.initialReconnectionDelay;\n const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;\n const maxDelay = this._reconnectionOptions.maxReconnectionDelay;\n // Cap at maximum delay\n return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);\n }\n /**\n * Schedule a reconnection attempt using server-provided retry interval or backoff\n *\n * @param lastEventId The ID of the last received event for resumability\n * @param attemptCount Current reconnection attempt count for this specific stream\n */\n _scheduleReconnection(options, attemptCount = 0) {\n // Use provided options or default options\n const maxRetries = this._reconnectionOptions.maxRetries;\n // Check if we've exceeded maximum retry attempts\n if (attemptCount >= maxRetries) {\n this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));\n return;\n }\n // Calculate next delay based on current attempt count\n const delay = this._getNextReconnectionDelay(attemptCount);\n // Schedule the reconnection\n this._reconnectionTimeout = setTimeout(() => {\n // Use the last event ID to resume where we left off\n this._startOrAuthSse(options).catch(error => {\n this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));\n // Schedule another attempt if this one failed, incrementing the attempt counter\n this._scheduleReconnection(options, attemptCount + 1);\n });\n }, delay);\n }\n _handleSseStream(stream, options, isReconnectable) {\n if (!stream) {\n return;\n }\n const { onresumptiontoken, replayMessageId } = options;\n let lastEventId;\n // Track whether we've received a priming event (event with ID)\n // Per spec, server SHOULD send a priming event with ID before closing\n let hasPrimingEvent = false;\n // Track whether we've received a response - if so, no need to reconnect\n // Reconnection is for when server disconnects BEFORE sending response\n let receivedResponse = false;\n const processStream = async () => {\n // this is the closest we can get to trying to catch network errors\n // if something happens reader will throw\n try {\n // Create a pipeline: binary stream -> text decoder -> SSE parser\n const reader = stream\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream({\n onRetry: (retryMs) => {\n // Capture server-provided retry value for reconnection timing\n this._serverRetryMs = retryMs;\n }\n }))\n .getReader();\n while (true) {\n const { value: event, done } = await reader.read();\n if (done) {\n break;\n }\n // Update last event ID if provided\n if (event.id) {\n lastEventId = event.id;\n // Mark that we've received a priming event - stream is now resumable\n hasPrimingEvent = true;\n onresumptiontoken?.(event.id);\n }\n // Skip events with no data (priming events, keep-alives)\n if (!event.data) {\n continue;\n }\n if (!event.event || event.event === 'message') {\n try {\n const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));\n if (isJSONRPCResultResponse(message)) {\n // Mark that we received a response - no need to reconnect for this request\n receivedResponse = true;\n if (replayMessageId !== undefined) {\n message.id = replayMessageId;\n }\n }\n this.onmessage?.(message);\n }\n catch (error) {\n this.onerror?.(error);\n }\n }\n }\n // Handle graceful server-side disconnect\n // Server may close connection after sending event ID and retry field\n // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n // BUT don't reconnect if we already received a response - the request is complete\n const canResume = isReconnectable || hasPrimingEvent;\n const needsReconnect = canResume && !receivedResponse;\n if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n this._scheduleReconnection({\n resumptionToken: lastEventId,\n onresumptiontoken,\n replayMessageId\n }, 0);\n }\n }\n catch (error) {\n // Handle stream errors - likely a network disconnect\n this.onerror?.(new Error(`SSE stream disconnected: ${error}`));\n // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing\n // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n // BUT don't reconnect if we already received a response - the request is complete\n const canResume = isReconnectable || hasPrimingEvent;\n const needsReconnect = canResume && !receivedResponse;\n if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n // Use the exponential backoff reconnection strategy\n try {\n this._scheduleReconnection({\n resumptionToken: lastEventId,\n onresumptiontoken,\n replayMessageId\n }, 0);\n }\n catch (error) {\n this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));\n }\n }\n }\n };\n processStream();\n }\n async start() {\n if (this._abortController) {\n throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n this._abortController = new AbortController();\n }\n /**\n * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n */\n async finishAuth(authorizationCode) {\n if (!this._authProvider) {\n throw new UnauthorizedError('No auth provider');\n }\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n authorizationCode,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError('Failed to authorize');\n }\n }\n async close() {\n if (this._reconnectionTimeout) {\n clearTimeout(this._reconnectionTimeout);\n this._reconnectionTimeout = undefined;\n }\n this._abortController?.abort();\n this.onclose?.();\n }\n async send(message, options) {\n try {\n const { resumptionToken, onresumptiontoken } = options || {};\n if (resumptionToken) {\n // If we have at last event ID, we need to reconnect the SSE stream\n this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => this.onerror?.(err));\n return;\n }\n const headers = await this._commonHeaders();\n headers.set('content-type', 'application/json');\n headers.set('accept', 'application/json, text/event-stream');\n const init = {\n ...this._requestInit,\n method: 'POST',\n headers,\n body: JSON.stringify(message),\n signal: this._abortController?.signal\n };\n const response = await (this._fetch ?? fetch)(this._url, init);\n // Handle session ID received during initialization\n const sessionId = response.headers.get('mcp-session-id');\n if (sessionId) {\n this._sessionId = sessionId;\n }\n if (!response.ok) {\n const text = await response.text().catch(() => null);\n if (response.status === 401 && this._authProvider) {\n // Prevent infinite recursion when server returns 401 after successful auth\n if (this._hasCompletedAuthFlow) {\n throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication');\n }\n const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n this._resourceMetadataUrl = resourceMetadataUrl;\n this._scope = scope;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetchWithInit\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n // Mark that we completed auth flow\n this._hasCompletedAuthFlow = true;\n // Purposely _not_ awaited, so we don't call onerror twice\n return this.send(message);\n }\n if (response.status === 403 && this._authProvider) {\n const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);\n if (error === 'insufficient_scope') {\n const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n // Check if we've already tried upscoping with this header to prevent infinite loops.\n if (this._lastUpscopingHeader === wwwAuthHeader) {\n throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping');\n }\n if (scope) {\n this._scope = scope;\n }\n if (resourceMetadataUrl) {\n this._resourceMetadataUrl = resourceMetadataUrl;\n }\n // Mark that upscoping was tried.\n this._lastUpscopingHeader = wwwAuthHeader ?? undefined;\n const result = await auth(this._authProvider, {\n serverUrl: this._url,\n resourceMetadataUrl: this._resourceMetadataUrl,\n scope: this._scope,\n fetchFn: this._fetch\n });\n if (result !== 'AUTHORIZED') {\n throw new UnauthorizedError();\n }\n return this.send(message);\n }\n }\n throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);\n }\n // Reset auth loop flag on successful response\n this._hasCompletedAuthFlow = false;\n this._lastUpscopingHeader = undefined;\n // If the response is 202 Accepted, there's no body to process\n if (response.status === 202) {\n await response.body?.cancel();\n // if the accepted notification is initialized, we start the SSE stream\n // if it's supported by the server\n if (isInitializedNotification(message)) {\n // Start without a lastEventId since this is a fresh connection\n this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err));\n }\n return;\n }\n // Get original message(s) for detecting request IDs\n const messages = Array.isArray(message) ? message : [message];\n const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0;\n // Check the response type\n const contentType = response.headers.get('content-type');\n if (hasRequests) {\n if (contentType?.includes('text/event-stream')) {\n // Handle SSE stream responses for requests\n // We use the same handler as standalone streams, which now supports\n // reconnection with the last event ID\n this._handleSseStream(response.body, { onresumptiontoken }, false);\n }\n else if (contentType?.includes('application/json')) {\n // For non-streaming servers, we might get direct JSON responses\n const data = await response.json();\n const responseMessages = Array.isArray(data)\n ? data.map(msg => JSONRPCMessageSchema.parse(msg))\n : [JSONRPCMessageSchema.parse(data)];\n for (const msg of responseMessages) {\n this.onmessage?.(msg);\n }\n }\n else {\n await response.body?.cancel();\n throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);\n }\n }\n else {\n // No requests in message but got 200 OK - still need to release connection\n await response.body?.cancel();\n }\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n }\n get sessionId() {\n return this._sessionId;\n }\n /**\n * Terminates the current session by sending a DELETE request to the server.\n *\n * Clients that no longer need a particular session\n * (e.g., because the user is leaving the client application) SHOULD send an\n * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly\n * terminate the session.\n *\n * The server MAY respond with HTTP 405 Method Not Allowed, indicating that\n * the server does not allow clients to terminate sessions.\n */\n async terminateSession() {\n if (!this._sessionId) {\n return; // No session to terminate\n }\n try {\n const headers = await this._commonHeaders();\n const init = {\n ...this._requestInit,\n method: 'DELETE',\n headers,\n signal: this._abortController?.signal\n };\n const response = await (this._fetch ?? fetch)(this._url, init);\n await response.body?.cancel();\n // We specifically handle 405 as a valid response according to the spec,\n // meaning the server does not support explicit session termination\n if (!response.ok && response.status !== 405) {\n throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);\n }\n this._sessionId = undefined;\n }\n catch (error) {\n this.onerror?.(error);\n throw error;\n }\n }\n setProtocolVersion(version) {\n this._protocolVersion = version;\n }\n get protocolVersion() {\n return this._protocolVersion;\n }\n /**\n * Resume an SSE stream from a previous event ID.\n * Opens a GET SSE connection with Last-Event-ID header to replay missed events.\n *\n * @param lastEventId The event ID to resume from\n * @param options Optional callback to receive new resumption tokens\n */\n async resumeStream(lastEventId, options) {\n await this._startOrAuthSse({\n resumptionToken: lastEventId,\n onresumptiontoken: options?.onresumptiontoken\n });\n }\n}\n//# sourceMappingURL=streamableHttp.js.map","import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport {\n McpError,\n isJSONRPCErrorResponse,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { Result } from 'better-result';\n\nimport type { RemoteErrorSource } from '../shared/types.js';\n\nimport { RemoteRequestError } from '../shared/errors.js';\nimport { isRecord } from '../shared/guards.js';\n\ninterface MappedRemoteError {\n body?: string;\n httpStatus?: number;\n mcpCode?: number;\n mcpData?: unknown;\n raw: unknown;\n retryable?: boolean;\n source: RemoteErrorSource;\n}\n\ninterface CreateRemoteRequestErrorOptions {\n cause: unknown;\n message: string;\n operation: string;\n}\n\nconst toSerializable = (value: unknown): unknown => {\n if (value instanceof Error) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n };\n }\n\n try {\n return structuredClone(value);\n } catch {\n return String(value);\n }\n};\n\nconst toJsonRpcErrorPayload = (\n payload: unknown,\n): {\n code: number;\n data: unknown;\n raw: unknown;\n} | null => {\n if (isJSONRPCErrorResponse(payload)) {\n return {\n code: payload.error.code,\n data: payload.error.data,\n raw: toSerializable(payload),\n };\n }\n\n if (!isRecord(payload) || !Object.hasOwn(payload, 'error')) {\n return null;\n }\n\n const errorRecord = payload['error'];\n if (!isRecord(errorRecord)) {\n return null;\n }\n\n const code = errorRecord['code'];\n if (typeof code !== 'number') {\n return null;\n }\n\n return {\n code,\n data: errorRecord['data'],\n raw: toSerializable(payload),\n };\n};\n\nconst extractStreamableBody = (message: string): string | undefined => {\n const marker = 'Error POSTing to endpoint:';\n const markerIndex = message.indexOf(marker);\n if (markerIndex === -1) {\n return undefined;\n }\n\n const body = message.slice(markerIndex + marker.length).trim();\n return body.length > 0 ? body : undefined;\n};\n\nconst mapStreamableHttpError = (\n error: StreamableHTTPError,\n): MappedRemoteError => {\n const body = extractStreamableBody(error.message);\n const parsedBody =\n body === undefined\n ? null\n : (() => {\n const parsed = Result.try({\n catch: () => null,\n try: () => {\n const value: unknown = JSON.parse(body);\n return value;\n },\n });\n return Result.isError(parsed) ? null : parsed.value;\n })();\n\n const jsonRpcPayload =\n parsedBody === null ? null : toJsonRpcErrorPayload(parsedBody);\n\n const httpStatus =\n typeof error.code === 'number' && error.code >= 100\n ? error.code\n : undefined;\n const retryable =\n httpStatus === undefined\n ? undefined\n : httpStatus === 429 || httpStatus >= 500 || httpStatus === 408;\n return {\n ...(body === undefined ? {} : { body }),\n ...(httpStatus === undefined ? {} : { httpStatus }),\n ...(jsonRpcPayload === null ? {} : { mcpCode: jsonRpcPayload.code }),\n ...(jsonRpcPayload === null ? {} : { mcpData: jsonRpcPayload.data }),\n raw: jsonRpcPayload?.raw ?? toSerializable(parsedBody ?? error),\n ...(retryable === undefined ? {} : { retryable }),\n source: 'mcp_transport_http',\n };\n};\n\nconst mapMcpError = (error: McpError): MappedRemoteError => {\n return {\n mcpCode: error.code,\n mcpData: toSerializable(error.data),\n raw: toSerializable({\n code: error.code,\n data: error.data,\n message: error.message,\n name: error.name,\n }),\n retryable: error.code === -32_001,\n source: 'mcp_jsonrpc',\n };\n};\n\nconst mapUnknownError = (cause: unknown): MappedRemoteError => {\n if (cause instanceof Error) {\n return {\n raw: toSerializable(cause),\n source: 'network',\n };\n }\n\n return {\n raw: toSerializable(cause),\n source: 'unknown',\n };\n};\n\nconst mapCause = (cause: unknown): MappedRemoteError => {\n if (cause instanceof StreamableHTTPError) {\n return mapStreamableHttpError(cause);\n }\n\n if (cause instanceof McpError) {\n return mapMcpError(cause);\n }\n\n return mapUnknownError(cause);\n};\n\nexport const createRemoteRequestErrorFromMcpCause = (\n options: CreateRemoteRequestErrorOptions,\n): RemoteRequestError => {\n const mapped = mapCause(options.cause);\n return new RemoteRequestError({\n ...(mapped.body === undefined ? {} : { body: mapped.body }),\n ...(mapped.httpStatus === undefined\n ? {}\n : { httpStatus: mapped.httpStatus }),\n ...(mapped.mcpCode === undefined ? {} : { mcpCode: mapped.mcpCode }),\n ...(mapped.mcpData === undefined ? {} : { mcpData: mapped.mcpData }),\n message: options.message,\n operation: options.operation,\n raw: mapped.raw,\n ...(mapped.retryable === undefined ? {} : { retryable: mapped.retryable }),\n source: mapped.source,\n });\n};\n","import { Client } from '@modelcontextprotocol/sdk/client';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport {\n CompatibilityCallToolResultSchema,\n ListToolsResultSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { Result } from 'better-result';\nimport type { Result as ResultType } from 'better-result';\n\nimport type { RemoteRequestError, ValidationError } from '../shared/errors.js';\nimport type { McpToolSummary, ToolCallResult } from '../shared/types.js';\n\nimport { ERROR_CODE } from '../shared/error-codes.js';\nimport { parseJsonUnknown, parseWithSchema } from '../shared/guards.js';\nimport { createRemoteRequestErrorFromMcpCause } from './mcp-error-mapping.js';\n\nconst MCP_CONNECT_TIMEOUT_MS = 10_000;\nconst MCP_DISCOVERY_TIMEOUT_MS = 10_000;\nconst MCP_INVOKE_TIMEOUT_MS = 45_000;\n\ninterface McpTarget {\n orgSlug: string;\n serverPath: string;\n}\n\ninterface McpClientLike {\n callTool(\n params: { arguments: Record<string, unknown>; name: string },\n resultSchema?: unknown,\n options?: { timeout?: number },\n ): Promise<unknown>;\n close(): Promise<void>;\n connect(transport: unknown, options?: { timeout?: number }): Promise<void>;\n listTools(\n params?: unknown,\n options?: { timeout?: number },\n ): Promise<{\n tools: Array<Record<string, unknown>>;\n }>;\n}\n\ninterface McpServiceDeps {\n baseUrl: string;\n createClient?: () => McpClientLike;\n createTransport?: (url: URL, apiKey: string) => unknown;\n version: string;\n}\n\nexport type McpServiceError = RemoteRequestError | ValidationError;\n\nexport interface McpService {\n callTool(\n target: McpTarget,\n apiKey: string,\n toolName: string,\n args: Record<string, unknown>,\n ): Promise<ResultType<ToolCallResult, McpServiceError>>;\n listTools(\n target: McpTarget,\n apiKey: string,\n ): Promise<ResultType<McpToolSummary[], McpServiceError>>;\n}\n\nconst defaultCreateClient = (version: string): McpClientLike => {\n return new Client(\n {\n name: 'ogment-cli',\n version,\n },\n {\n capabilities: {},\n },\n );\n};\n\nconst defaultCreateTransport = (url: URL, apiKey: string): unknown => {\n return new StreamableHTTPClientTransport(url, {\n requestInit: {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n },\n });\n};\n\nconst parseToolCallContent = (\n result: unknown,\n): ResultType<ToolCallResult, McpServiceError> => {\n const parsedResult = parseWithSchema(\n CompatibilityCallToolResultSchema,\n result,\n 'MCP tool call result',\n {\n code: ERROR_CODE.toolInputSchemaViolation,\n recovery: { command: 'ogment catalog' },\n },\n );\n\n if (Result.isError(parsedResult)) {\n return parsedResult;\n }\n\n const payload = parsedResult.value;\n\n if ('toolResult' in payload) {\n return Result.ok({\n isError: false,\n structuredContent: payload.toolResult,\n });\n }\n\n if (payload.structuredContent !== undefined) {\n return Result.ok({\n isError: payload.isError === true,\n structuredContent: payload.structuredContent,\n });\n }\n\n const firstContent = payload.content[0];\n if (firstContent?.type === 'text') {\n const parsedText = parseJsonUnknown(firstContent.text, 'MCP text content');\n if (Result.isError(parsedText)) {\n return Result.ok({\n isError: payload.isError === true,\n structuredContent: firstContent.text,\n });\n }\n\n return Result.ok({\n isError: payload.isError === true,\n structuredContent: parsedText.value,\n });\n }\n\n return Result.ok({\n isError: payload.isError === true,\n structuredContent: payload,\n });\n};\n\nexport const createMcpService = (deps: McpServiceDeps): McpService => {\n const createClient =\n deps.createClient ?? (() => defaultCreateClient(deps.version));\n const createTransport = deps.createTransport ?? defaultCreateTransport;\n\n const withClient = async <T>(\n target: McpTarget,\n apiKey: string,\n handler: (client: McpClientLike) => Promise<ResultType<T, McpServiceError>>,\n ): Promise<ResultType<T, McpServiceError>> => {\n const endpoint = `${deps.baseUrl}/api/v1/mcp/${target.orgSlug}/${target.serverPath}`;\n const url = new URL(endpoint);\n const transport = createTransport(url, apiKey);\n const client = createClient();\n\n const connectResult = await Result.tryPromise({\n catch: (cause) =>\n createRemoteRequestErrorFromMcpCause({\n cause,\n message: 'Failed to connect to MCP server',\n operation: 'connect',\n }),\n try: async () => {\n await client.connect(transport, {\n timeout: MCP_CONNECT_TIMEOUT_MS,\n });\n },\n });\n\n if (Result.isError(connectResult)) {\n return connectResult;\n }\n\n try {\n return await handler(client);\n } finally {\n await Result.tryPromise({\n catch: () => undefined,\n try: async () => {\n await client.close();\n },\n });\n }\n };\n\n const withRemoteCall = async <T>(\n action: () => Promise<T>,\n message: string,\n operation: string,\n ): Promise<ResultType<T, RemoteRequestError>> => {\n return Result.tryPromise({\n catch: (cause) =>\n createRemoteRequestErrorFromMcpCause({\n cause,\n message,\n operation,\n }),\n try: action,\n });\n };\n\n return {\n callTool: async (target, apiKey, toolName, args) => {\n return withClient<ToolCallResult>(target, apiKey, async (client) => {\n const toolCallResult = await withRemoteCall(\n async () => {\n return client.callTool(\n {\n arguments: args,\n name: toolName,\n },\n CompatibilityCallToolResultSchema,\n {\n timeout: MCP_INVOKE_TIMEOUT_MS,\n },\n );\n },\n 'MCP tool call failed',\n 'tools/call',\n );\n\n if (Result.isError(toolCallResult)) {\n return toolCallResult;\n }\n\n return parseToolCallContent(toolCallResult.value);\n });\n },\n listTools: async (target, apiKey) => {\n return withClient<McpToolSummary[]>(target, apiKey, async (client) => {\n const toolsResult = await withRemoteCall(\n async () =>\n client.listTools(undefined, {\n timeout: MCP_DISCOVERY_TIMEOUT_MS,\n }),\n 'MCP tools/list failed',\n 'tools/list',\n );\n\n if (Result.isError(toolsResult)) {\n return toolsResult;\n }\n\n const parsedToolsResult = parseWithSchema(\n ListToolsResultSchema,\n toolsResult.value,\n 'MCP tools/list response',\n {\n code: ERROR_CODE.toolInputSchemaViolation,\n recovery: { command: 'ogment catalog' },\n },\n );\n if (Result.isError(parsedToolsResult)) {\n return parsedToolsResult;\n }\n\n const parsedTools: McpToolSummary[] = [];\n\n for (const tool of parsedToolsResult.value.tools) {\n const normalizedTool: McpToolSummary = {\n description: tool.description ?? null,\n inputSchema: tool.inputSchema,\n name: tool.name,\n };\n\n if (tool.outputSchema !== undefined) {\n normalizedTool.outputSchema = tool.outputSchema;\n }\n\n parsedTools.push(normalizedTool);\n }\n\n return Result.ok(parsedTools);\n });\n },\n };\n};\n","import type { Command } from 'commander';\n\nimport type { CommandContext, CommandServices } from '../commands/context.js';\n\nimport { createFileCredentialsStore } from '../infra/credentials.js';\nimport { createRuntimeConfig } from '../infra/env.js';\nimport { createHttpClient } from '../infra/http.js';\nimport { OutputManager, type OutputInitOptions } from '../output/manager.js';\nimport { createAccountService } from '../services/account.js';\nimport { createAuthService } from '../services/auth.js';\nimport { createInfoService, type InfoService } from '../services/info.js';\nimport { createMcpService } from '../services/mcp.js';\n\nexport interface GlobalCliOptions {\n apiKey: string | undefined;\n debug: boolean | undefined;\n quiet: boolean | undefined;\n yes: boolean | undefined;\n}\n\nexport interface Runtime {\n context: CommandContext;\n infoService?: InfoService;\n output: OutputManager;\n}\n\nexport const createRuntime = (): Runtime => {\n const runtimeConfig = createRuntimeConfig();\n const output = new OutputManager();\n const credentialsStore = createFileCredentialsStore({\n configDir: runtimeConfig.configDir,\n credentialsPath: runtimeConfig.credentialsPath,\n });\n const httpClient = createHttpClient();\n\n const services: CommandServices = {\n account: createAccountService({\n baseUrl: runtimeConfig.baseUrl,\n httpClient,\n }),\n auth: createAuthService({\n baseUrl: runtimeConfig.baseUrl,\n credentialsStore,\n envApiKey: runtimeConfig.envApiKey,\n httpClient,\n }),\n mcp: createMcpService({\n baseUrl: runtimeConfig.baseUrl,\n version: runtimeConfig.version,\n }),\n };\n\n const infoService = createInfoService({\n accountService: services.account,\n baseUrl: runtimeConfig.baseUrl,\n baseUrlSource: runtimeConfig.baseUrlSource,\n configDir: runtimeConfig.configDir,\n credentialsPath: runtimeConfig.credentialsPath,\n credentialsStore,\n envApiKey: runtimeConfig.envApiKey,\n httpClient,\n version: runtimeConfig.version,\n });\n\n return {\n context: {\n apiKeyOverride: undefined,\n output,\n services,\n },\n infoService,\n output,\n };\n};\n\nexport const asGlobalOptions = (command: Command): GlobalCliOptions => {\n const options = command.optsWithGlobals<GlobalCliOptions>();\n\n return {\n apiKey: options.apiKey,\n debug: options.debug,\n quiet: options.quiet,\n yes: options.yes,\n };\n};\n\nexport const mapGlobalOutputOptions = (\n options: GlobalCliOptions,\n): OutputInitOptions => {\n return {\n debug: options.debug,\n quiet: options.quiet,\n yes: options.yes,\n };\n};\n\nexport const parseOutputOptionsFromArgv = (\n argv: readonly string[],\n): OutputInitOptions => {\n const hasFlag = (flag: string): boolean => argv.includes(flag);\n\n return {\n debug: hasFlag('--debug'),\n quiet: hasFlag('--quiet'),\n yes: hasFlag('--yes'),\n };\n};\n","import { Command, InvalidArgumentError, Option } from 'commander';\n\nimport type { CliInvocation } from './invocations.js';\nimport type { CommanderParseState } from './parse-errors.js';\n\nimport { APP_DESCRIPTION, APP_NAME, VERSION } from '../shared/constants.js';\nimport {\n asGlobalOptions,\n mapGlobalOutputOptions,\n type Runtime,\n} from './runtime.js';\n\nexport interface ProgramCreationResult {\n program: Command;\n readInvocation: () => CliInvocation | null;\n}\n\nconst positiveIntegerPattern = /^\\d+$/;\n\nconst parseCatalogLimitOption = (value: string): number => {\n if (!positiveIntegerPattern.test(value)) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n\n const parsed = Number.parseInt(value, 10);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n\n return parsed;\n};\n\nconst parseInvokeTarget = (value: string): string => {\n const separatorIndex = value.lastIndexOf('/');\n if (\n separatorIndex <= 0 ||\n separatorIndex >= value.length - 1 ||\n /\\s/.test(value)\n ) {\n throw new InvalidArgumentError('Expected <server-id>/<tool-name>.');\n }\n\n return value;\n};\n\nexport const createProgram = (\n runtime: Runtime,\n parseState: CommanderParseState,\n): ProgramCreationResult => {\n const program = new Command();\n let invocation: CliInvocation | null = null;\n const setInvocation = (next: CliInvocation): void => {\n invocation = next;\n };\n\n program.exitOverride();\n program.configureOutput({\n writeErr: (chunk: string) => {\n parseState.stderrChunks.push(chunk);\n },\n writeOut: (chunk: string) => {\n parseState.stdoutChunks.push(chunk);\n runtime.output.writeStdout(chunk);\n },\n });\n program.configureHelp({\n showGlobalOptions: true,\n sortOptions: true,\n sortSubcommands: true,\n });\n program.showHelpAfterError();\n program.showSuggestionAfterError();\n program.helpCommand('help [command]', 'Display help for a command');\n program.addHelpText('after', ({ error }) => {\n if (error) {\n return '';\n }\n\n return [\n '',\n 'Examples:',\n ' $ ogment auth login',\n ' $ ogment catalog billing create_invoice --example',\n ' $ ogment invoke billing/create_invoice --input \\'{\"amount\":100}\\'',\n '',\n 'Run `ogment help <command>` for command-specific usage.',\n ].join('\\n');\n });\n\n program\n .name(APP_NAME)\n .description(APP_DESCRIPTION)\n .version(VERSION)\n .optionsGroup('Connection Options:')\n .option('--api-key <key>', 'API key override')\n .optionsGroup('Output Options:')\n .option('--debug', 'Include debug metadata and diagnostics in JSON output')\n .option('--quiet', 'Emit minimal JSON output (ok + data/error)')\n .optionsGroup('Automation Options:')\n .option('--yes', 'Assume yes for any confirmation')\n .hook('preAction', (thisCommand) => {\n const options = asGlobalOptions(thisCommand);\n runtime.output.configure(mapGlobalOutputOptions(options));\n runtime.context.apiKeyOverride = options.apiKey;\n });\n\n const authCommand = program\n .command('auth')\n .summary('Authenticate, inspect auth state, and logout')\n .description('Authentication workflows')\n .helpGroup('Authentication Commands:')\n .helpCommand('help [command]', 'Display help for auth commands')\n .addHelpText('after', ({ error }) => {\n if (error) {\n return '';\n }\n\n return [\n '',\n 'Examples:',\n ' $ ogment auth login',\n ' $ ogment auth status',\n ].join('\\n');\n });\n\n authCommand\n .command('login')\n .summary('Login with device flow (default)')\n .description('Authenticate with Ogment using device flow (recommended)')\n .action((_: object, command: Command) => {\n const { apiKey } = asGlobalOptions(command);\n setInvocation({\n apiKey,\n kind: 'auth_login',\n });\n });\n\n authCommand\n .command('status')\n .summary('Show current auth state')\n .description('Show local authentication status')\n .action(() => {\n setInvocation({\n kind: 'auth_status',\n });\n });\n\n authCommand\n .command('logout')\n .summary('Delete local credentials and revoke token')\n .description('Revoke token and delete local credentials')\n .action(() => {\n setInvocation({\n kind: 'auth_logout',\n });\n });\n\n program\n .command('catalog [serverId] [toolName]')\n .summary('Discover servers and inspect tools')\n .description('Discover servers and tools with progressive disclosure')\n .helpGroup('Discovery Commands:')\n .addOption(\n new Option(\n '--cursor <cursor>',\n 'Pagination cursor (catalog summary only)',\n ).conflicts('example'),\n )\n .addOption(\n new Option(\n '--limit <limit>',\n 'Maximum servers to return (catalog summary only)',\n )\n .argParser(parseCatalogLimitOption)\n .conflicts('example'),\n )\n .addOption(\n new Option(\n '--example',\n 'Include a generated example input payload (tool details only)',\n ).conflicts(['cursor', 'limit']),\n )\n .action(\n (\n serverId: string | undefined,\n toolName: string | undefined,\n options: { cursor?: string; example?: boolean; limit?: number },\n ) => {\n setInvocation({\n cursor: options.cursor,\n example: options.example === true,\n kind: 'catalog',\n limit: options.limit,\n serverId,\n toolName,\n });\n },\n );\n\n program\n .command('invoke')\n .summary('Invoke a tool by <server-id>/<tool-name>')\n .description('Invoke a tool using <server-id>/<tool-name>')\n .helpGroup('Execution Commands:')\n .argument(\n '<target>',\n 'Target tool in the form <server-id>/<tool-name>',\n parseInvokeTarget,\n )\n .option(\n '--input <value>',\n 'Input payload: inline JSON object, @path, or - for stdin',\n )\n .action((target: string, options: { input?: string }) => {\n setInvocation({\n input: options.input,\n kind: 'invoke',\n target,\n });\n });\n\n program\n .command('status')\n .summary('Show runtime diagnostics')\n .description('Show runtime configuration and connectivity diagnostics')\n .helpGroup('Diagnostics Commands:')\n .action(() => {\n setInvocation({\n kind: 'status',\n });\n });\n\n program.action(() => {\n setInvocation({\n kind: 'root',\n });\n });\n\n return {\n program,\n readInvocation: () => invocation,\n };\n};\n","import { realpathSync } from 'node:fs';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\n\nimport { CommanderError } from 'commander';\n\nimport {\n EXIT_CODE,\n type ExitCode,\n exitCodeForError,\n} from '../shared/exit-codes.js';\nimport {\n executeInvocation,\n CliExitError,\n normalizeCliRuntimeError,\n} from './execute.js';\nimport { createCommanderParseState, toParseCliError } from './parse-errors.js';\nimport { createProgram } from './program.js';\nimport {\n createRuntime,\n parseOutputOptionsFromArgv,\n type Runtime,\n} from './runtime.js';\n\nconst normalizeCliArgv = (argv: readonly string[]): readonly string[] => {\n if (argv[0] === '--') {\n return argv.slice(1);\n }\n\n return argv;\n};\n\nconst commandFromArgv = (argv: readonly string[]): string => {\n const normalized = normalizeCliArgv(argv);\n if (normalized.length === 0) {\n return 'ogment';\n }\n\n return `ogment ${normalized.join(' ')}`;\n};\n\nexport const runCli = async (\n argv: readonly string[] = process.argv.slice(2),\n runtime: Runtime = createRuntime(),\n): Promise<ExitCode> => {\n const normalizedArgv = normalizeCliArgv(argv);\n runtime.output.configure(parseOutputOptionsFromArgv(normalizedArgv));\n\n const parseState = createCommanderParseState();\n const { program, readInvocation } = createProgram(runtime, parseState);\n\n try {\n await program.parseAsync(normalizedArgv, { from: 'user' });\n\n const invocation = readInvocation();\n if (invocation !== null) {\n await executeInvocation(runtime, invocation);\n }\n\n return EXIT_CODE.success;\n } catch (error: unknown) {\n if (error instanceof CliExitError) {\n return error.exitCode;\n }\n\n if (error instanceof CommanderError) {\n if (error.exitCode === EXIT_CODE.success) {\n return EXIT_CODE.success;\n }\n\n const parseError = toParseCliError(error, parseState, {\n includeDebug: runtime.output.debug,\n });\n runtime.output.parseError(parseError.payload, {\n command: commandFromArgv(argv),\n entity: null,\n nextActions: parseError.nextActions,\n });\n return EXIT_CODE.validation;\n }\n\n const normalized = normalizeCliRuntimeError(error);\n runtime.output.error(normalized, {\n command: commandFromArgv(argv),\n entity: null,\n });\n return exitCodeForError(normalized);\n }\n};\n\nexport const executeCli = async (): Promise<void> => {\n const code = await runCli();\n process.exitCode = code;\n};\n\nconst toCanonicalFileHref = (path: string): string => {\n return pathToFileURL(realpathSync(path)).href;\n};\n\nexport const shouldExecuteCli = (\n importMetaUrl: string,\n argv1: string | undefined,\n): boolean => {\n if (argv1 === undefined) {\n return false;\n }\n\n try {\n const invokedFileHref = toCanonicalFileHref(argv1);\n const moduleFileHref = toCanonicalFileHref(fileURLToPath(importMetaUrl));\n return invokedFileHref === moduleFileHref;\n } catch {\n return false;\n }\n};\n","#!/usr/bin/env node\n\nimport { executeCli, runCli, shouldExecuteCli } from './cli/run.js';\n\nexport { executeCli, runCli, shouldExecuteCli };\n\nif (shouldExecuteCli(import.meta.url, process.argv[1])) {\n await executeCli();\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,9,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAGA,IAAM,iBAAN,cAA6B,MAAM;;;;;;;EAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,SAAM,QAAQ;AAEd,SAAM,kBAAkB,MAAM,KAAK,YAAY;AAC/C,QAAK,OAAO,KAAK,YAAY;AAC7B,QAAK,OAAO;AACZ,QAAK,WAAW;AAChB,QAAK,cAAc;;;;;;CAOvB,IAAM,uBAAN,cAAmC,eAAe;;;;;EAKhD,YAAY,SAAS;AACnB,SAAM,GAAG,6BAA6B,QAAQ;AAE9C,SAAM,kBAAkB,MAAM,KAAK,YAAY;AAC/C,QAAK,OAAO,KAAK,YAAY;;;AAIjC,SAAQ,iBAAiB;AACzB,SAAQ,uBAAuB;;;;;;CCtC/B,MAAM,EAAE;CAER,IAAM,WAAN,MAAe;;;;;;;;;EAUb,YAAY,MAAM,aAAa;AAC7B,QAAK,cAAc,eAAe;AAClC,QAAK,WAAW;AAChB,QAAK,WAAW;AA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