spb/tendril Public
Tendril — web ingestion platform (scrape/crawl/map/search) on macOS Apple Silicon: WebKit fidelity, authenticated pages, deterministic testable extraction. A self-hosted Firecrawl alternative.
JavaScript 82.6%
TypeScript 11.8%
HTML 5.3%
1#!/usr/bin/env node2var __create = Object.create;3var __defProp = Object.defineProperty;4var __getOwnPropDesc = Object.getOwnPropertyDescriptor;5var __getOwnPropNames = Object.getOwnPropertyNames;6var __getProtoOf = Object.getPrototypeOf;7var __hasOwnProp = Object.prototype.hasOwnProperty;8var __commonJS = (cb, mod) => function __require() {9 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;10};11var __export = (target, all) => {12 for (var name in all)13 __defProp(target, name, { get: all[name], enumerable: true });14};15var __copyProps = (to, from, except, desc) => {16 if (from && typeof from === "object" || typeof from === "function") {17 for (let key of __getOwnPropNames(from))18 if (!__hasOwnProp.call(to, key) && key !== except)19 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });20 }21 return to;22};23var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(24 // If the importer is in node compatibility mode or this is not an ESM25 // file that has been converted to a CommonJS file using a Babel-26 // compatible transform (i.e. "__esModule" has not been set), then set27 // "default" to the CommonJS "module.exports" for node compatibility.28 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,29 mod30));3132// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js33var require_code = __commonJS({34 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js"(exports) {35 "use strict";36 Object.defineProperty(exports, "__esModule", { value: true });37 exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;38 var _CodeOrName = class {39 };40 exports._CodeOrName = _CodeOrName;41 exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;42 var Name = class extends _CodeOrName {43 constructor(s) {44 super();45 if (!exports.IDENTIFIER.test(s))46 throw new Error("CodeGen: name must be a valid identifier");47 this.str = s;48 }49 toString() {50 return this.str;51 }52 emptyStr() {53 return false;54 }55 get names() {56 return { [this.str]: 1 };57 }58 };59 exports.Name = Name;60 var _Code = class extends _CodeOrName {61 constructor(code) {62 super();63 this._items = typeof code === "string" ? [code] : code;64 }65 toString() {66 return this.str;67 }68 emptyStr() {69 if (this._items.length > 1)70 return false;71 const item = this._items[0];72 return item === "" || item === '""';73 }74 get str() {75 var _a;76 return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");77 }78 get names() {79 var _a;80 return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => {81 if (c instanceof Name)82 names[c.str] = (names[c.str] || 0) + 1;83 return names;84 }, {});85 }86 };87 exports._Code = _Code;88 exports.nil = new _Code("");89 function _(strs, ...args) {90 const code = [strs[0]];91 let i = 0;92 while (i < args.length) {93 addCodeArg(code, args[i]);94 code.push(strs[++i]);95 }96 return new _Code(code);97 }98 exports._ = _;99 var plus = new _Code("+");100 function str(strs, ...args) {101 const expr = [safeStringify(strs[0])];102 let i = 0;103 while (i < args.length) {104 expr.push(plus);105 addCodeArg(expr, args[i]);106 expr.push(plus, safeStringify(strs[++i]));107 }108 optimize(expr);109 return new _Code(expr);110 }111 exports.str = str;112 function addCodeArg(code, arg) {113 if (arg instanceof _Code)114 code.push(...arg._items);115 else if (arg instanceof Name)116 code.push(arg);117 else118 code.push(interpolate(arg));119 }120 exports.addCodeArg = addCodeArg;121 function optimize(expr) {122 let i = 1;123 while (i < expr.length - 1) {124 if (expr[i] === plus) {125 const res = mergeExprItems(expr[i - 1], expr[i + 1]);126 if (res !== void 0) {127 expr.splice(i - 1, 3, res);128 continue;129 }130 expr[i++] = "+";131 }132 i++;133 }134 }135 function mergeExprItems(a, b) {136 if (b === '""')137 return a;138 if (a === '""')139 return b;140 if (typeof a == "string") {141 if (b instanceof Name || a[a.length - 1] !== '"')142 return;143 if (typeof b != "string")144 return `${a.slice(0, -1)}${b}"`;145 if (b[0] === '"')146 return a.slice(0, -1) + b.slice(1);147 return;148 }149 if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))150 return `"${a}${b.slice(1)}`;151 return;152 }153 function strConcat(c1, c2) {154 return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;155 }156 exports.strConcat = strConcat;157 function interpolate(x) {158 return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);159 }160 function stringify(x) {161 return new _Code(safeStringify(x));162 }163 exports.stringify = stringify;164 function safeStringify(x) {165 return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");166 }167 exports.safeStringify = safeStringify;168 function getProperty(key) {169 return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;170 }171 exports.getProperty = getProperty;172 function getEsmExportName(key) {173 if (typeof key == "string" && exports.IDENTIFIER.test(key)) {174 return new _Code(`${key}`);175 }176 throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);177 }178 exports.getEsmExportName = getEsmExportName;179 function regexpCode(rx) {180 return new _Code(rx.toString());181 }182 exports.regexpCode = regexpCode;183 }184});185186// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js187var require_scope = __commonJS({188 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js"(exports) {189 "use strict";190 Object.defineProperty(exports, "__esModule", { value: true });191 exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;192 var code_1 = require_code();193 var ValueError = class extends Error {194 constructor(name) {195 super(`CodeGen: "code" for ${name} not defined`);196 this.value = name.value;197 }198 };199 var UsedValueState;200 (function(UsedValueState2) {201 UsedValueState2[UsedValueState2["Started"] = 0] = "Started";202 UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";203 })(UsedValueState || (exports.UsedValueState = UsedValueState = {}));204 exports.varKinds = {205 const: new code_1.Name("const"),206 let: new code_1.Name("let"),207 var: new code_1.Name("var")208 };209 var Scope = class {210 constructor({ prefixes, parent } = {}) {211 this._names = {};212 this._prefixes = prefixes;213 this._parent = parent;214 }215 toName(nameOrPrefix) {216 return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);217 }218 name(prefix) {219 return new code_1.Name(this._newName(prefix));220 }221 _newName(prefix) {222 const ng = this._names[prefix] || this._nameGroup(prefix);223 return `${prefix}${ng.index++}`;224 }225 _nameGroup(prefix) {226 var _a, _b;227 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)) {228 throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);229 }230 return this._names[prefix] = { prefix, index: 0 };231 }232 };233 exports.Scope = Scope;234 var ValueScopeName = class extends code_1.Name {235 constructor(prefix, nameStr) {236 super(nameStr);237 this.prefix = prefix;238 }239 setValue(value, { property, itemIndex }) {240 this.value = value;241 this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;242 }243 };244 exports.ValueScopeName = ValueScopeName;245 var line = (0, code_1._)`\n`;246 var ValueScope = class extends Scope {247 constructor(opts) {248 super(opts);249 this._values = {};250 this._scope = opts.scope;251 this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };252 }253 get() {254 return this._scope;255 }256 name(prefix) {257 return new ValueScopeName(prefix, this._newName(prefix));258 }259 value(nameOrPrefix, value) {260 var _a;261 if (value.ref === void 0)262 throw new Error("CodeGen: ref must be passed in value");263 const name = this.toName(nameOrPrefix);264 const { prefix } = name;265 const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;266 let vs = this._values[prefix];267 if (vs) {268 const _name = vs.get(valueKey);269 if (_name)270 return _name;271 } else {272 vs = this._values[prefix] = /* @__PURE__ */ new Map();273 }274 vs.set(valueKey, name);275 const s = this._scope[prefix] || (this._scope[prefix] = []);276 const itemIndex = s.length;277 s[itemIndex] = value.ref;278 name.setValue(value, { property: prefix, itemIndex });279 return name;280 }281 getValue(prefix, keyOrRef) {282 const vs = this._values[prefix];283 if (!vs)284 return;285 return vs.get(keyOrRef);286 }287 scopeRefs(scopeName, values = this._values) {288 return this._reduceValues(values, (name) => {289 if (name.scopePath === void 0)290 throw new Error(`CodeGen: name "${name}" has no value`);291 return (0, code_1._)`${scopeName}${name.scopePath}`;292 });293 }294 scopeCode(values = this._values, usedValues, getCode) {295 return this._reduceValues(values, (name) => {296 if (name.value === void 0)297 throw new Error(`CodeGen: name "${name}" has no value`);298 return name.value.code;299 }, usedValues, getCode);300 }301 _reduceValues(values, valueCode, usedValues = {}, getCode) {302 let code = code_1.nil;303 for (const prefix in values) {304 const vs = values[prefix];305 if (!vs)306 continue;307 const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();308 vs.forEach((name) => {309 if (nameSet.has(name))310 return;311 nameSet.set(name, UsedValueState.Started);312 let c = valueCode(name);313 if (c) {314 const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;315 code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`;316 } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) {317 code = (0, code_1._)`${code}${c}${this.opts._n}`;318 } else {319 throw new ValueError(name);320 }321 nameSet.set(name, UsedValueState.Completed);322 });323 }324 return code;325 }326 };327 exports.ValueScope = ValueScope;328 }329});330331// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js332var require_codegen = __commonJS({333 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js"(exports) {334 "use strict";335 Object.defineProperty(exports, "__esModule", { value: true });336 exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;337 var code_1 = require_code();338 var scope_1 = require_scope();339 var code_2 = require_code();340 Object.defineProperty(exports, "_", { enumerable: true, get: function() {341 return code_2._;342 } });343 Object.defineProperty(exports, "str", { enumerable: true, get: function() {344 return code_2.str;345 } });346 Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() {347 return code_2.strConcat;348 } });349 Object.defineProperty(exports, "nil", { enumerable: true, get: function() {350 return code_2.nil;351 } });352 Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() {353 return code_2.getProperty;354 } });355 Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {356 return code_2.stringify;357 } });358 Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() {359 return code_2.regexpCode;360 } });361 Object.defineProperty(exports, "Name", { enumerable: true, get: function() {362 return code_2.Name;363 } });364 var scope_2 = require_scope();365 Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {366 return scope_2.Scope;367 } });368 Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() {369 return scope_2.ValueScope;370 } });371 Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() {372 return scope_2.ValueScopeName;373 } });374 Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() {375 return scope_2.varKinds;376 } });377 exports.operators = {378 GT: new code_1._Code(">"),379 GTE: new code_1._Code(">="),380 LT: new code_1._Code("<"),381 LTE: new code_1._Code("<="),382 EQ: new code_1._Code("==="),383 NEQ: new code_1._Code("!=="),384 NOT: new code_1._Code("!"),385 OR: new code_1._Code("||"),386 AND: new code_1._Code("&&"),387 ADD: new code_1._Code("+")388 };389 var Node = class {390 optimizeNodes() {391 return this;392 }393 optimizeNames(_names, _constants) {394 return this;395 }396 };397 var Def = class extends Node {398 constructor(varKind, name, rhs) {399 super();400 this.varKind = varKind;401 this.name = name;402 this.rhs = rhs;403 }404 render({ es5, _n }) {405 const varKind = es5 ? scope_1.varKinds.var : this.varKind;406 const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;407 return `${varKind} ${this.name}${rhs};` + _n;408 }409 optimizeNames(names, constants) {410 if (!names[this.name.str])411 return;412 if (this.rhs)413 this.rhs = optimizeExpr(this.rhs, names, constants);414 return this;415 }416 get names() {417 return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};418 }419 };420 var Assign = class extends Node {421 constructor(lhs, rhs, sideEffects) {422 super();423 this.lhs = lhs;424 this.rhs = rhs;425 this.sideEffects = sideEffects;426 }427 render({ _n }) {428 return `${this.lhs} = ${this.rhs};` + _n;429 }430 optimizeNames(names, constants) {431 if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)432 return;433 this.rhs = optimizeExpr(this.rhs, names, constants);434 return this;435 }436 get names() {437 const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };438 return addExprNames(names, this.rhs);439 }440 };441 var AssignOp = class extends Assign {442 constructor(lhs, op, rhs, sideEffects) {443 super(lhs, rhs, sideEffects);444 this.op = op;445 }446 render({ _n }) {447 return `${this.lhs} ${this.op}= ${this.rhs};` + _n;448 }449 };450 var Label = class extends Node {451 constructor(label) {452 super();453 this.label = label;454 this.names = {};455 }456 render({ _n }) {457 return `${this.label}:` + _n;458 }459 };460 var Break = class extends Node {461 constructor(label) {462 super();463 this.label = label;464 this.names = {};465 }466 render({ _n }) {467 const label = this.label ? ` ${this.label}` : "";468 return `break${label};` + _n;469 }470 };471 var Throw = class extends Node {472 constructor(error2) {473 super();474 this.error = error2;475 }476 render({ _n }) {477 return `throw ${this.error};` + _n;478 }479 get names() {480 return this.error.names;481 }482 };483 var AnyCode = class extends Node {484 constructor(code) {485 super();486 this.code = code;487 }488 render({ _n }) {489 return `${this.code};` + _n;490 }491 optimizeNodes() {492 return `${this.code}` ? this : void 0;493 }494 optimizeNames(names, constants) {495 this.code = optimizeExpr(this.code, names, constants);496 return this;497 }498 get names() {499 return this.code instanceof code_1._CodeOrName ? this.code.names : {};500 }501 };502 var ParentNode = class extends Node {503 constructor(nodes = []) {504 super();505 this.nodes = nodes;506 }507 render(opts) {508 return this.nodes.reduce((code, n) => code + n.render(opts), "");509 }510 optimizeNodes() {511 const { nodes } = this;512 let i = nodes.length;513 while (i--) {514 const n = nodes[i].optimizeNodes();515 if (Array.isArray(n))516 nodes.splice(i, 1, ...n);517 else if (n)518 nodes[i] = n;519 else520 nodes.splice(i, 1);521 }522 return nodes.length > 0 ? this : void 0;523 }524 optimizeNames(names, constants) {525 const { nodes } = this;526 let i = nodes.length;527 while (i--) {528 const n = nodes[i];529 if (n.optimizeNames(names, constants))530 continue;531 subtractNames(names, n.names);532 nodes.splice(i, 1);533 }534 return nodes.length > 0 ? this : void 0;535 }536 get names() {537 return this.nodes.reduce((names, n) => addNames(names, n.names), {});538 }539 };540 var BlockNode = class extends ParentNode {541 render(opts) {542 return "{" + opts._n + super.render(opts) + "}" + opts._n;543 }544 };545 var Root = class extends ParentNode {546 };547 var Else = class extends BlockNode {548 };549 Else.kind = "else";550 var If = class _If extends BlockNode {551 constructor(condition, nodes) {552 super(nodes);553 this.condition = condition;554 }555 render(opts) {556 let code = `if(${this.condition})` + super.render(opts);557 if (this.else)558 code += "else " + this.else.render(opts);559 return code;560 }561 optimizeNodes() {562 super.optimizeNodes();563 const cond = this.condition;564 if (cond === true)565 return this.nodes;566 let e = this.else;567 if (e) {568 const ns = e.optimizeNodes();569 e = this.else = Array.isArray(ns) ? new Else(ns) : ns;570 }571 if (e) {572 if (cond === false)573 return e instanceof _If ? e : e.nodes;574 if (this.nodes.length)575 return this;576 return new _If(not(cond), e instanceof _If ? [e] : e.nodes);577 }578 if (cond === false || !this.nodes.length)579 return void 0;580 return this;581 }582 optimizeNames(names, constants) {583 var _a;584 this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);585 if (!(super.optimizeNames(names, constants) || this.else))586 return;587 this.condition = optimizeExpr(this.condition, names, constants);588 return this;589 }590 get names() {591 const names = super.names;592 addExprNames(names, this.condition);593 if (this.else)594 addNames(names, this.else.names);595 return names;596 }597 };598 If.kind = "if";599 var For = class extends BlockNode {600 };601 For.kind = "for";602 var ForLoop = class extends For {603 constructor(iteration) {604 super();605 this.iteration = iteration;606 }607 render(opts) {608 return `for(${this.iteration})` + super.render(opts);609 }610 optimizeNames(names, constants) {611 if (!super.optimizeNames(names, constants))612 return;613 this.iteration = optimizeExpr(this.iteration, names, constants);614 return this;615 }616 get names() {617 return addNames(super.names, this.iteration.names);618 }619 };620 var ForRange = class extends For {621 constructor(varKind, name, from, to) {622 super();623 this.varKind = varKind;624 this.name = name;625 this.from = from;626 this.to = to;627 }628 render(opts) {629 const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;630 const { name, from, to } = this;631 return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);632 }633 get names() {634 const names = addExprNames(super.names, this.from);635 return addExprNames(names, this.to);636 }637 };638 var ForIter = class extends For {639 constructor(loop, varKind, name, iterable) {640 super();641 this.loop = loop;642 this.varKind = varKind;643 this.name = name;644 this.iterable = iterable;645 }646 render(opts) {647 return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);648 }649 optimizeNames(names, constants) {650 if (!super.optimizeNames(names, constants))651 return;652 this.iterable = optimizeExpr(this.iterable, names, constants);653 return this;654 }655 get names() {656 return addNames(super.names, this.iterable.names);657 }658 };659 var Func = class extends BlockNode {660 constructor(name, args, async) {661 super();662 this.name = name;663 this.args = args;664 this.async = async;665 }666 render(opts) {667 const _async = this.async ? "async " : "";668 return `${_async}function ${this.name}(${this.args})` + super.render(opts);669 }670 };671 Func.kind = "func";672 var Return = class extends ParentNode {673 render(opts) {674 return "return " + super.render(opts);675 }676 };677 Return.kind = "return";678 var Try = class extends BlockNode {679 render(opts) {680 let code = "try" + super.render(opts);681 if (this.catch)682 code += this.catch.render(opts);683 if (this.finally)684 code += this.finally.render(opts);685 return code;686 }687 optimizeNodes() {688 var _a, _b;689 super.optimizeNodes();690 (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();691 (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();692 return this;693 }694 optimizeNames(names, constants) {695 var _a, _b;696 super.optimizeNames(names, constants);697 (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);698 (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);699 return this;700 }701 get names() {702 const names = super.names;703 if (this.catch)704 addNames(names, this.catch.names);705 if (this.finally)706 addNames(names, this.finally.names);707 return names;708 }709 };710 var Catch = class extends BlockNode {711 constructor(error2) {712 super();713 this.error = error2;714 }715 render(opts) {716 return `catch(${this.error})` + super.render(opts);717 }718 };719 Catch.kind = "catch";720 var Finally = class extends BlockNode {721 render(opts) {722 return "finally" + super.render(opts);723 }724 };725 Finally.kind = "finally";726 var CodeGen = class {727 constructor(extScope, opts = {}) {728 this._values = {};729 this._blockStarts = [];730 this._constants = {};731 this.opts = { ...opts, _n: opts.lines ? "\n" : "" };732 this._extScope = extScope;733 this._scope = new scope_1.Scope({ parent: extScope });734 this._nodes = [new Root()];735 }736 toString() {737 return this._root.render(this.opts);738 }739 // returns unique name in the internal scope740 name(prefix) {741 return this._scope.name(prefix);742 }743 // reserves unique name in the external scope744 scopeName(prefix) {745 return this._extScope.name(prefix);746 }747 // reserves unique name in the external scope and assigns value to it748 scopeValue(prefixOrName, value) {749 const name = this._extScope.value(prefixOrName, value);750 const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set());751 vs.add(name);752 return name;753 }754 getScopeValue(prefix, keyOrRef) {755 return this._extScope.getValue(prefix, keyOrRef);756 }757 // return code that assigns values in the external scope to the names that are used internally758 // (same names that were returned by gen.scopeName or gen.scopeValue)759 scopeRefs(scopeName) {760 return this._extScope.scopeRefs(scopeName, this._values);761 }762 scopeCode() {763 return this._extScope.scopeCode(this._values);764 }765 _def(varKind, nameOrPrefix, rhs, constant) {766 const name = this._scope.toName(nameOrPrefix);767 if (rhs !== void 0 && constant)768 this._constants[name.str] = rhs;769 this._leafNode(new Def(varKind, name, rhs));770 return name;771 }772 // `const` declaration (`var` in es5 mode)773 const(nameOrPrefix, rhs, _constant) {774 return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);775 }776 // `let` declaration with optional assignment (`var` in es5 mode)777 let(nameOrPrefix, rhs, _constant) {778 return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);779 }780 // `var` declaration with optional assignment781 var(nameOrPrefix, rhs, _constant) {782 return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);783 }784 // assignment code785 assign(lhs, rhs, sideEffects) {786 return this._leafNode(new Assign(lhs, rhs, sideEffects));787 }788 // `+=` code789 add(lhs, rhs) {790 return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));791 }792 // appends passed SafeExpr to code or executes Block793 code(c) {794 if (typeof c == "function")795 c();796 else if (c !== code_1.nil)797 this._leafNode(new AnyCode(c));798 return this;799 }800 // returns code for object literal for the passed argument list of key-value pairs801 object(...keyValues) {802 const code = ["{"];803 for (const [key, value] of keyValues) {804 if (code.length > 1)805 code.push(",");806 code.push(key);807 if (key !== value || this.opts.es5) {808 code.push(":");809 (0, code_1.addCodeArg)(code, value);810 }811 }812 code.push("}");813 return new code_1._Code(code);814 }815 // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)816 if(condition, thenBody, elseBody) {817 this._blockNode(new If(condition));818 if (thenBody && elseBody) {819 this.code(thenBody).else().code(elseBody).endIf();820 } else if (thenBody) {821 this.code(thenBody).endIf();822 } else if (elseBody) {823 throw new Error('CodeGen: "else" body without "then" body');824 }825 return this;826 }827 // `else if` clause - invalid without `if` or after `else` clauses828 elseIf(condition) {829 return this._elseNode(new If(condition));830 }831 // `else` clause - only valid after `if` or `else if` clauses832 else() {833 return this._elseNode(new Else());834 }835 // end `if` statement (needed if gen.if was used only with condition)836 endIf() {837 return this._endBlockNode(If, Else);838 }839 _for(node, forBody) {840 this._blockNode(node);841 if (forBody)842 this.code(forBody).endFor();843 return this;844 }845 // a generic `for` clause (or statement if `forBody` is passed)846 for(iteration, forBody) {847 return this._for(new ForLoop(iteration), forBody);848 }849 // `for` statement for a range of values850 forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {851 const name = this._scope.toName(nameOrPrefix);852 return this._for(new ForRange(varKind, name, from, to), () => forBody(name));853 }854 // `for-of` statement (in es5 mode replace with a normal for loop)855 forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {856 const name = this._scope.toName(nameOrPrefix);857 if (this.opts.es5) {858 const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);859 return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => {860 this.var(name, (0, code_1._)`${arr}[${i}]`);861 forBody(name);862 });863 }864 return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));865 }866 // `for-in` statement.867 // With option `ownProperties` replaced with a `for-of` loop for object keys868 forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {869 if (this.opts.ownProperties) {870 return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);871 }872 const name = this._scope.toName(nameOrPrefix);873 return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));874 }875 // end `for` loop876 endFor() {877 return this._endBlockNode(For);878 }879 // `label` statement880 label(label) {881 return this._leafNode(new Label(label));882 }883 // `break` statement884 break(label) {885 return this._leafNode(new Break(label));886 }887 // `return` statement888 return(value) {889 const node = new Return();890 this._blockNode(node);891 this.code(value);892 if (node.nodes.length !== 1)893 throw new Error('CodeGen: "return" should have one node');894 return this._endBlockNode(Return);895 }896 // `try` statement897 try(tryBody, catchCode, finallyCode) {898 if (!catchCode && !finallyCode)899 throw new Error('CodeGen: "try" without "catch" and "finally"');900 const node = new Try();901 this._blockNode(node);902 this.code(tryBody);903 if (catchCode) {904 const error2 = this.name("e");905 this._currNode = node.catch = new Catch(error2);906 catchCode(error2);907 }908 if (finallyCode) {909 this._currNode = node.finally = new Finally();910 this.code(finallyCode);911 }912 return this._endBlockNode(Catch, Finally);913 }914 // `throw` statement915 throw(error2) {916 return this._leafNode(new Throw(error2));917 }918 // start self-balancing block919 block(body, nodeCount) {920 this._blockStarts.push(this._nodes.length);921 if (body)922 this.code(body).endBlock(nodeCount);923 return this;924 }925 // end the current self-balancing block926 endBlock(nodeCount) {927 const len = this._blockStarts.pop();928 if (len === void 0)929 throw new Error("CodeGen: not in self-balancing block");930 const toClose = this._nodes.length - len;931 if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {932 throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);933 }934 this._nodes.length = len;935 return this;936 }937 // `function` heading (or definition if funcBody is passed)938 func(name, args = code_1.nil, async, funcBody) {939 this._blockNode(new Func(name, args, async));940 if (funcBody)941 this.code(funcBody).endFunc();942 return this;943 }944 // end function definition945 endFunc() {946 return this._endBlockNode(Func);947 }948 optimize(n = 1) {949 while (n-- > 0) {950 this._root.optimizeNodes();951 this._root.optimizeNames(this._root.names, this._constants);952 }953 }954 _leafNode(node) {955 this._currNode.nodes.push(node);956 return this;957 }958 _blockNode(node) {959 this._currNode.nodes.push(node);960 this._nodes.push(node);961 }962 _endBlockNode(N1, N2) {963 const n = this._currNode;964 if (n instanceof N1 || N2 && n instanceof N2) {965 this._nodes.pop();966 return this;967 }968 throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);969 }970 _elseNode(node) {971 const n = this._currNode;972 if (!(n instanceof If)) {973 throw new Error('CodeGen: "else" without "if"');974 }975 this._currNode = n.else = node;976 return this;977 }978 get _root() {979 return this._nodes[0];980 }981 get _currNode() {982 const ns = this._nodes;983 return ns[ns.length - 1];984 }985 set _currNode(node) {986 const ns = this._nodes;987 ns[ns.length - 1] = node;988 }989 };990 exports.CodeGen = CodeGen;991 function addNames(names, from) {992 for (const n in from)993 names[n] = (names[n] || 0) + (from[n] || 0);994 return names;995 }996 function addExprNames(names, from) {997 return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;998 }999 function optimizeExpr(expr, names, constants) {1000 if (expr instanceof code_1.Name)1001 return replaceName(expr);1002 if (!canOptimize(expr))1003 return expr;1004 return new code_1._Code(expr._items.reduce((items, c) => {1005 if (c instanceof code_1.Name)1006 c = replaceName(c);1007 if (c instanceof code_1._Code)1008 items.push(...c._items);1009 else1010 items.push(c);1011 return items;1012 }, []));1013 function replaceName(n) {1014 const c = constants[n.str];1015 if (c === void 0 || names[n.str] !== 1)1016 return n;1017 delete names[n.str];1018 return c;1019 }1020 function canOptimize(e) {1021 return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);1022 }1023 }1024 function subtractNames(names, from) {1025 for (const n in from)1026 names[n] = (names[n] || 0) - (from[n] || 0);1027 }1028 function not(x) {1029 return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;1030 }1031 exports.not = not;1032 var andCode = mappend(exports.operators.AND);1033 function and(...args) {1034 return args.reduce(andCode);1035 }1036 exports.and = and;1037 var orCode = mappend(exports.operators.OR);1038 function or(...args) {1039 return args.reduce(orCode);1040 }1041 exports.or = or;1042 function mappend(op) {1043 return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;1044 }1045 function par(x) {1046 return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;1047 }1048 }1049});10501051// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js1052var require_util = __commonJS({1053 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js"(exports) {1054 "use strict";1055 Object.defineProperty(exports, "__esModule", { value: true });1056 exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;1057 var codegen_1 = require_codegen();1058 var code_1 = require_code();1059 function toHash(arr) {1060 const hash = {};1061 for (const item of arr)1062 hash[item] = true;1063 return hash;1064 }1065 exports.toHash = toHash;1066 function alwaysValidSchema(it, schema) {1067 if (typeof schema == "boolean")1068 return schema;1069 if (Object.keys(schema).length === 0)1070 return true;1071 checkUnknownRules(it, schema);1072 return !schemaHasRules(schema, it.self.RULES.all);1073 }1074 exports.alwaysValidSchema = alwaysValidSchema;1075 function checkUnknownRules(it, schema = it.schema) {1076 const { opts, self } = it;1077 if (!opts.strictSchema)1078 return;1079 if (typeof schema === "boolean")1080 return;1081 const rules = self.RULES.keywords;1082 for (const key in schema) {1083 if (!rules[key])1084 checkStrictMode(it, `unknown keyword: "${key}"`);1085 }1086 }1087 exports.checkUnknownRules = checkUnknownRules;1088 function schemaHasRules(schema, rules) {1089 if (typeof schema == "boolean")1090 return !schema;1091 for (const key in schema)1092 if (rules[key])1093 return true;1094 return false;1095 }1096 exports.schemaHasRules = schemaHasRules;1097 function schemaHasRulesButRef(schema, RULES) {1098 if (typeof schema == "boolean")1099 return !schema;1100 for (const key in schema)1101 if (key !== "$ref" && RULES.all[key])1102 return true;1103 return false;1104 }1105 exports.schemaHasRulesButRef = schemaHasRulesButRef;1106 function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {1107 if (!$data) {1108 if (typeof schema == "number" || typeof schema == "boolean")1109 return schema;1110 if (typeof schema == "string")1111 return (0, codegen_1._)`${schema}`;1112 }1113 return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;1114 }1115 exports.schemaRefOrVal = schemaRefOrVal;1116 function unescapeFragment(str) {1117 return unescapeJsonPointer(decodeURIComponent(str));1118 }1119 exports.unescapeFragment = unescapeFragment;1120 function escapeFragment(str) {1121 return encodeURIComponent(escapeJsonPointer(str));1122 }1123 exports.escapeFragment = escapeFragment;1124 function escapeJsonPointer(str) {1125 if (typeof str == "number")1126 return `${str}`;1127 return str.replace(/~/g, "~0").replace(/\//g, "~1");1128 }1129 exports.escapeJsonPointer = escapeJsonPointer;1130 function unescapeJsonPointer(str) {1131 return str.replace(/~1/g, "/").replace(/~0/g, "~");1132 }1133 exports.unescapeJsonPointer = unescapeJsonPointer;1134 function eachItem(xs, f) {1135 if (Array.isArray(xs)) {1136 for (const x of xs)1137 f(x);1138 } else {1139 f(xs);1140 }1141 }1142 exports.eachItem = eachItem;1143 function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) {1144 return (gen, from, to, toName) => {1145 const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to);1146 return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;1147 };1148 }1149 exports.mergeEvaluated = {1150 props: makeMergeEvaluated({1151 mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {1152 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})`));1153 }),1154 mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {1155 if (from === true) {1156 gen.assign(to, true);1157 } else {1158 gen.assign(to, (0, codegen_1._)`${to} || {}`);1159 setEvaluated(gen, to, from);1160 }1161 }),1162 mergeValues: (from, to) => from === true ? true : { ...from, ...to },1163 resultToName: evaluatedPropsToName1164 }),1165 items: makeMergeEvaluated({1166 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}`)),1167 mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),1168 mergeValues: (from, to) => from === true ? true : Math.max(from, to),1169 resultToName: (gen, items) => gen.var("items", items)1170 })1171 };1172 function evaluatedPropsToName(gen, ps) {1173 if (ps === true)1174 return gen.var("props", true);1175 const props = gen.var("props", (0, codegen_1._)`{}`);1176 if (ps !== void 0)1177 setEvaluated(gen, props, ps);1178 return props;1179 }1180 exports.evaluatedPropsToName = evaluatedPropsToName;1181 function setEvaluated(gen, props, ps) {1182 Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));1183 }1184 exports.setEvaluated = setEvaluated;1185 var snippets = {};1186 function useFunc(gen, f) {1187 return gen.scopeValue("func", {1188 ref: f,1189 code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))1190 });1191 }1192 exports.useFunc = useFunc;1193 var Type;1194 (function(Type2) {1195 Type2[Type2["Num"] = 0] = "Num";1196 Type2[Type2["Str"] = 1] = "Str";1197 })(Type || (exports.Type = Type = {}));1198 function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {1199 if (dataProp instanceof codegen_1.Name) {1200 const isNumber = dataPropType === Type.Num;1201 return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;1202 }1203 return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);1204 }1205 exports.getErrorPath = getErrorPath;1206 function checkStrictMode(it, msg, mode = it.opts.strictSchema) {1207 if (!mode)1208 return;1209 msg = `strict mode: ${msg}`;1210 if (mode === true)1211 throw new Error(msg);1212 it.self.logger.warn(msg);1213 }1214 exports.checkStrictMode = checkStrictMode;1215 }1216});12171218// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js1219var require_names = __commonJS({1220 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js"(exports) {1221 "use strict";1222 Object.defineProperty(exports, "__esModule", { value: true });1223 var codegen_1 = require_codegen();1224 var names = {1225 // validation function arguments1226 data: new codegen_1.Name("data"),1227 // data passed to validation function1228 // args passed from referencing schema1229 valCxt: new codegen_1.Name("valCxt"),1230 // validation/data context - should not be used directly, it is destructured to the names below1231 instancePath: new codegen_1.Name("instancePath"),1232 parentData: new codegen_1.Name("parentData"),1233 parentDataProperty: new codegen_1.Name("parentDataProperty"),1234 rootData: new codegen_1.Name("rootData"),1235 // root data - same as the data passed to the first/top validation function1236 dynamicAnchors: new codegen_1.Name("dynamicAnchors"),1237 // used to support recursiveRef and dynamicRef1238 // function scoped variables1239 vErrors: new codegen_1.Name("vErrors"),1240 // null or array of validation errors1241 errors: new codegen_1.Name("errors"),1242 // counter of validation errors1243 this: new codegen_1.Name("this"),1244 // "globals"1245 self: new codegen_1.Name("self"),1246 scope: new codegen_1.Name("scope"),1247 // JTD serialize/parse name for JSON string and position1248 json: new codegen_1.Name("json"),1249 jsonPos: new codegen_1.Name("jsonPos"),1250 jsonLen: new codegen_1.Name("jsonLen"),1251 jsonPart: new codegen_1.Name("jsonPart")1252 };1253 exports.default = names;1254 }1255});12561257// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js1258var require_errors = __commonJS({1259 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js"(exports) {1260 "use strict";1261 Object.defineProperty(exports, "__esModule", { value: true });1262 exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;1263 var codegen_1 = require_codegen();1264 var util_1 = require_util();1265 var names_1 = require_names();1266 exports.keywordError = {1267 message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`1268 };1269 exports.keyword$DataError = {1270 message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`1271 };1272 function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) {1273 const { it } = cxt;1274 const { gen, compositeRule, allErrors } = it;1275 const errObj = errorObjectCode(cxt, error2, errorPaths);1276 if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {1277 addError(gen, errObj);1278 } else {1279 returnErrors(it, (0, codegen_1._)`[${errObj}]`);1280 }1281 }1282 exports.reportError = reportError;1283 function reportExtraError(cxt, error2 = exports.keywordError, errorPaths) {1284 const { it } = cxt;1285 const { gen, compositeRule, allErrors } = it;1286 const errObj = errorObjectCode(cxt, error2, errorPaths);1287 addError(gen, errObj);1288 if (!(compositeRule || allErrors)) {1289 returnErrors(it, names_1.default.vErrors);1290 }1291 }1292 exports.reportExtraError = reportExtraError;1293 function resetErrorsCount(gen, errsCount) {1294 gen.assign(names_1.default.errors, errsCount);1295 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)));1296 }1297 exports.resetErrorsCount = resetErrorsCount;1298 function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {1299 if (errsCount === void 0)1300 throw new Error("ajv implementation error");1301 const err = gen.name("err");1302 gen.forRange("i", errsCount, names_1.default.errors, (i) => {1303 gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);1304 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)));1305 gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);1306 if (it.opts.verbose) {1307 gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);1308 gen.assign((0, codegen_1._)`${err}.data`, data);1309 }1310 });1311 }1312 exports.extendErrors = extendErrors;1313 function addError(gen, errObj) {1314 const err = gen.const("err", errObj);1315 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})`);1316 gen.code((0, codegen_1._)`${names_1.default.errors}++`);1317 }1318 function returnErrors(it, errs) {1319 const { gen, validateName, schemaEnv } = it;1320 if (schemaEnv.$async) {1321 gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);1322 } else {1323 gen.assign((0, codegen_1._)`${validateName}.errors`, errs);1324 gen.return(false);1325 }1326 }1327 var E = {1328 keyword: new codegen_1.Name("keyword"),1329 schemaPath: new codegen_1.Name("schemaPath"),1330 // also used in JTD errors1331 params: new codegen_1.Name("params"),1332 propertyName: new codegen_1.Name("propertyName"),1333 message: new codegen_1.Name("message"),1334 schema: new codegen_1.Name("schema"),1335 parentSchema: new codegen_1.Name("parentSchema")1336 };1337 function errorObjectCode(cxt, error2, errorPaths) {1338 const { createErrors } = cxt.it;1339 if (createErrors === false)1340 return (0, codegen_1._)`{}`;1341 return errorObject(cxt, error2, errorPaths);1342 }1343 function errorObject(cxt, error2, errorPaths = {}) {1344 const { gen, it } = cxt;1345 const keyValues = [1346 errorInstancePath(it, errorPaths),1347 errorSchemaPath(cxt, errorPaths)1348 ];1349 extraErrorProps(cxt, error2, keyValues);1350 return gen.object(...keyValues);1351 }1352 function errorInstancePath({ errorPath }, { instancePath }) {1353 const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;1354 return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];1355 }1356 function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {1357 let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;1358 if (schemaPath) {1359 schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;1360 }1361 return [E.schemaPath, schPath];1362 }1363 function extraErrorProps(cxt, { params, message }, keyValues) {1364 const { keyword, data, schemaValue, it } = cxt;1365 const { opts, propertyName, topSchemaRef, schemaPath } = it;1366 keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);1367 if (opts.messages) {1368 keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);1369 }1370 if (opts.verbose) {1371 keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);1372 }1373 if (propertyName)1374 keyValues.push([E.propertyName, propertyName]);1375 }1376 }1377});13781379// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js1380var require_boolSchema = __commonJS({1381 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) {1382 "use strict";1383 Object.defineProperty(exports, "__esModule", { value: true });1384 exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;1385 var errors_1 = require_errors();1386 var codegen_1 = require_codegen();1387 var names_1 = require_names();1388 var boolError = {1389 message: "boolean schema is false"1390 };1391 function topBoolOrEmptySchema(it) {1392 const { gen, schema, validateName } = it;1393 if (schema === false) {1394 falseSchemaError(it, false);1395 } else if (typeof schema == "object" && schema.$async === true) {1396 gen.return(names_1.default.data);1397 } else {1398 gen.assign((0, codegen_1._)`${validateName}.errors`, null);1399 gen.return(true);1400 }1401 }1402 exports.topBoolOrEmptySchema = topBoolOrEmptySchema;1403 function boolOrEmptySchema(it, valid) {1404 const { gen, schema } = it;1405 if (schema === false) {1406 gen.var(valid, false);1407 falseSchemaError(it);1408 } else {1409 gen.var(valid, true);1410 }1411 }1412 exports.boolOrEmptySchema = boolOrEmptySchema;1413 function falseSchemaError(it, overrideAllErrors) {1414 const { gen, data } = it;1415 const cxt = {1416 gen,1417 keyword: "false schema",1418 data,1419 schema: false,1420 schemaCode: false,1421 schemaValue: false,1422 params: {},1423 it1424 };1425 (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);1426 }1427 }1428});14291430// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js1431var require_rules = __commonJS({1432 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js"(exports) {1433 "use strict";1434 Object.defineProperty(exports, "__esModule", { value: true });1435 exports.getRules = exports.isJSONType = void 0;1436 var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];1437 var jsonTypes = new Set(_jsonTypes);1438 function isJSONType(x) {1439 return typeof x == "string" && jsonTypes.has(x);1440 }1441 exports.isJSONType = isJSONType;1442 function getRules() {1443 const groups = {1444 number: { type: "number", rules: [] },1445 string: { type: "string", rules: [] },1446 array: { type: "array", rules: [] },1447 object: { type: "object", rules: [] }1448 };1449 return {1450 types: { ...groups, integer: true, boolean: true, null: true },1451 rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],1452 post: { rules: [] },1453 all: {},1454 keywords: {}1455 };1456 }1457 exports.getRules = getRules;1458 }1459});14601461// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/applicability.js1462var require_applicability = __commonJS({1463 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/applicability.js"(exports) {1464 "use strict";1465 Object.defineProperty(exports, "__esModule", { value: true });1466 exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;1467 function schemaHasRulesForType({ schema, self }, type) {1468 const group = self.RULES.types[type];1469 return group && group !== true && shouldUseGroup(schema, group);1470 }1471 exports.schemaHasRulesForType = schemaHasRulesForType;1472 function shouldUseGroup(schema, group) {1473 return group.rules.some((rule) => shouldUseRule(schema, rule));1474 }1475 exports.shouldUseGroup = shouldUseGroup;1476 function shouldUseRule(schema, rule) {1477 var _a;1478 return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0));1479 }1480 exports.shouldUseRule = shouldUseRule;1481 }1482});14831484// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js1485var require_dataType = __commonJS({1486 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js"(exports) {1487 "use strict";1488 Object.defineProperty(exports, "__esModule", { value: true });1489 exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;1490 var rules_1 = require_rules();1491 var applicability_1 = require_applicability();1492 var errors_1 = require_errors();1493 var codegen_1 = require_codegen();1494 var util_1 = require_util();1495 var DataType;1496 (function(DataType2) {1497 DataType2[DataType2["Correct"] = 0] = "Correct";1498 DataType2[DataType2["Wrong"] = 1] = "Wrong";1499 })(DataType || (exports.DataType = DataType = {}));1500 function getSchemaTypes(schema) {1501 const types = getJSONTypes(schema.type);1502 const hasNull = types.includes("null");1503 if (hasNull) {1504 if (schema.nullable === false)1505 throw new Error("type: null contradicts nullable: false");1506 } else {1507 if (!types.length && schema.nullable !== void 0) {1508 throw new Error('"nullable" cannot be used without "type"');1509 }1510 if (schema.nullable === true)1511 types.push("null");1512 }1513 return types;1514 }1515 exports.getSchemaTypes = getSchemaTypes;1516 function getJSONTypes(ts) {1517 const types = Array.isArray(ts) ? ts : ts ? [ts] : [];1518 if (types.every(rules_1.isJSONType))1519 return types;1520 throw new Error("type must be JSONType or JSONType[]: " + types.join(","));1521 }1522 exports.getJSONTypes = getJSONTypes;1523 function coerceAndCheckDataType(it, types) {1524 const { gen, data, opts } = it;1525 const coerceTo = coerceToTypes(types, opts.coerceTypes);1526 const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));1527 if (checkTypes) {1528 const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);1529 gen.if(wrongType, () => {1530 if (coerceTo.length)1531 coerceData(it, types, coerceTo);1532 else1533 reportTypeError(it);1534 });1535 }1536 return checkTypes;1537 }1538 exports.coerceAndCheckDataType = coerceAndCheckDataType;1539 var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);1540 function coerceToTypes(types, coerceTypes) {1541 return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];1542 }1543 function coerceData(it, types, coerceTo) {1544 const { gen, data, opts } = it;1545 const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);1546 const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);1547 if (opts.coerceTypes === "array") {1548 gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));1549 }1550 gen.if((0, codegen_1._)`${coerced} !== undefined`);1551 for (const t of coerceTo) {1552 if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") {1553 coerceSpecificType(t);1554 }1555 }1556 gen.else();1557 reportTypeError(it);1558 gen.endIf();1559 gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {1560 gen.assign(data, coerced);1561 assignParentData(it, coerced);1562 });1563 function coerceSpecificType(t) {1564 switch (t) {1565 case "string":1566 gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);1567 return;1568 case "number":1569 gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null1570 || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);1571 return;1572 case "integer":1573 gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null1574 || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);1575 return;1576 case "boolean":1577 gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);1578 return;1579 case "null":1580 gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);1581 gen.assign(coerced, null);1582 return;1583 case "array":1584 gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number"1585 || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);1586 }1587 }1588 }1589 function assignParentData({ gen, parentData, parentDataProperty }, expr) {1590 gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));1591 }1592 function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {1593 const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;1594 let cond;1595 switch (dataType) {1596 case "null":1597 return (0, codegen_1._)`${data} ${EQ} null`;1598 case "array":1599 cond = (0, codegen_1._)`Array.isArray(${data})`;1600 break;1601 case "object":1602 cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;1603 break;1604 case "integer":1605 cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);1606 break;1607 case "number":1608 cond = numCond();1609 break;1610 default:1611 return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`;1612 }1613 return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);1614 function numCond(_cond = codegen_1.nil) {1615 return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);1616 }1617 }1618 exports.checkDataType = checkDataType;1619 function checkDataTypes(dataTypes, data, strictNums, correct) {1620 if (dataTypes.length === 1) {1621 return checkDataType(dataTypes[0], data, strictNums, correct);1622 }1623 let cond;1624 const types = (0, util_1.toHash)(dataTypes);1625 if (types.array && types.object) {1626 const notObj = (0, codegen_1._)`typeof ${data} != "object"`;1627 cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;1628 delete types.null;1629 delete types.array;1630 delete types.object;1631 } else {1632 cond = codegen_1.nil;1633 }1634 if (types.number)1635 delete types.integer;1636 for (const t in types)1637 cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));1638 return cond;1639 }1640 exports.checkDataTypes = checkDataTypes;1641 var typeError = {1642 message: ({ schema }) => `must be ${schema}`,1643 params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`1644 };1645 function reportTypeError(it) {1646 const cxt = getTypeErrorContext(it);1647 (0, errors_1.reportError)(cxt, typeError);1648 }1649 exports.reportTypeError = reportTypeError;1650 function getTypeErrorContext(it) {1651 const { gen, data, schema } = it;1652 const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");1653 return {1654 gen,1655 keyword: "type",1656 data,1657 schema: schema.type,1658 schemaCode,1659 schemaValue: schemaCode,1660 parentSchema: schema,1661 params: {},1662 it1663 };1664 }1665 }1666});16671668// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js1669var require_defaults = __commonJS({1670 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports) {1671 "use strict";1672 Object.defineProperty(exports, "__esModule", { value: true });1673 exports.assignDefaults = void 0;1674 var codegen_1 = require_codegen();1675 var util_1 = require_util();1676 function assignDefaults(it, ty) {1677 const { properties, items } = it.schema;1678 if (ty === "object" && properties) {1679 for (const key in properties) {1680 assignDefault(it, key, properties[key].default);1681 }1682 } else if (ty === "array" && Array.isArray(items)) {1683 items.forEach((sch, i) => assignDefault(it, i, sch.default));1684 }1685 }1686 exports.assignDefaults = assignDefaults;1687 function assignDefault(it, prop, defaultValue) {1688 const { gen, compositeRule, data, opts } = it;1689 if (defaultValue === void 0)1690 return;1691 const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;1692 if (compositeRule) {1693 (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);1694 return;1695 }1696 let condition = (0, codegen_1._)`${childData} === undefined`;1697 if (opts.useDefaults === "empty") {1698 condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;1699 }1700 gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);1701 }1702 }1703});17041705// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js1706var require_code2 = __commonJS({1707 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js"(exports) {1708 "use strict";1709 Object.defineProperty(exports, "__esModule", { value: true });1710 exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;1711 var codegen_1 = require_codegen();1712 var util_1 = require_util();1713 var names_1 = require_names();1714 var util_2 = require_util();1715 function checkReportMissingProp(cxt, prop) {1716 const { gen, data, it } = cxt;1717 gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {1718 cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);1719 cxt.error();1720 });1721 }1722 exports.checkReportMissingProp = checkReportMissingProp;1723 function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {1724 return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));1725 }1726 exports.checkMissingProp = checkMissingProp;1727 function reportMissingProp(cxt, missing) {1728 cxt.setParams({ missingProperty: missing }, true);1729 cxt.error();1730 }1731 exports.reportMissingProp = reportMissingProp;1732 function hasPropFunc(gen) {1733 return gen.scopeValue("func", {1734 // eslint-disable-next-line @typescript-eslint/unbound-method1735 ref: Object.prototype.hasOwnProperty,1736 code: (0, codegen_1._)`Object.prototype.hasOwnProperty`1737 });1738 }1739 exports.hasPropFunc = hasPropFunc;1740 function isOwnProperty(gen, data, property) {1741 return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;1742 }1743 exports.isOwnProperty = isOwnProperty;1744 function propertyInData(gen, data, property, ownProperties) {1745 const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;1746 return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;1747 }1748 exports.propertyInData = propertyInData;1749 function noPropertyInData(gen, data, property, ownProperties) {1750 const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;1751 return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;1752 }1753 exports.noPropertyInData = noPropertyInData;1754 function allSchemaProperties(schemaMap) {1755 return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];1756 }1757 exports.allSchemaProperties = allSchemaProperties;1758 function schemaProperties(it, schemaMap) {1759 return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));1760 }1761 exports.schemaProperties = schemaProperties;1762 function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {1763 const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;1764 const valCxt = [1765 [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],1766 [names_1.default.parentData, it.parentData],1767 [names_1.default.parentDataProperty, it.parentDataProperty],1768 [names_1.default.rootData, names_1.default.rootData]1769 ];1770 if (it.opts.dynamicRef)1771 valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);1772 const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;1773 return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;1774 }1775 exports.callValidateCode = callValidateCode;1776 var newRegExp = (0, codegen_1._)`new RegExp`;1777 function usePattern({ gen, it: { opts } }, pattern) {1778 const u = opts.unicodeRegExp ? "u" : "";1779 const { regExp } = opts.code;1780 const rx = regExp(pattern, u);1781 return gen.scopeValue("pattern", {1782 key: rx.toString(),1783 ref: rx,1784 code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`1785 });1786 }1787 exports.usePattern = usePattern;1788 function validateArray(cxt) {1789 const { gen, data, keyword, it } = cxt;1790 const valid = gen.name("valid");1791 if (it.allErrors) {1792 const validArr = gen.let("valid", true);1793 validateItems(() => gen.assign(validArr, false));1794 return validArr;1795 }1796 gen.var(valid, true);1797 validateItems(() => gen.break());1798 return valid;1799 function validateItems(notValid) {1800 const len = gen.const("len", (0, codegen_1._)`${data}.length`);1801 gen.forRange("i", 0, len, (i) => {1802 cxt.subschema({1803 keyword,1804 dataProp: i,1805 dataPropType: util_1.Type.Num1806 }, valid);1807 gen.if((0, codegen_1.not)(valid), notValid);1808 });1809 }1810 }1811 exports.validateArray = validateArray;1812 function validateUnion(cxt) {1813 const { gen, schema, keyword, it } = cxt;1814 if (!Array.isArray(schema))1815 throw new Error("ajv implementation error");1816 const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));1817 if (alwaysValid && !it.opts.unevaluated)1818 return;1819 const valid = gen.let("valid", false);1820 const schValid = gen.name("_valid");1821 gen.block(() => schema.forEach((_sch, i) => {1822 const schCxt = cxt.subschema({1823 keyword,1824 schemaProp: i,1825 compositeRule: true1826 }, schValid);1827 gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);1828 const merged = cxt.mergeValidEvaluated(schCxt, schValid);1829 if (!merged)1830 gen.if((0, codegen_1.not)(valid));1831 }));1832 cxt.result(valid, () => cxt.reset(), () => cxt.error(true));1833 }1834 exports.validateUnion = validateUnion;1835 }1836});18371838// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js1839var require_keyword = __commonJS({1840 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports) {1841 "use strict";1842 Object.defineProperty(exports, "__esModule", { value: true });1843 exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;1844 var codegen_1 = require_codegen();1845 var names_1 = require_names();1846 var code_1 = require_code2();1847 var errors_1 = require_errors();1848 function macroKeywordCode(cxt, def) {1849 const { gen, keyword, schema, parentSchema, it } = cxt;1850 const macroSchema = def.macro.call(it.self, schema, parentSchema, it);1851 const schemaRef = useKeyword(gen, keyword, macroSchema);1852 if (it.opts.validateSchema !== false)1853 it.self.validateSchema(macroSchema, true);1854 const valid = gen.name("valid");1855 cxt.subschema({1856 schema: macroSchema,1857 schemaPath: codegen_1.nil,1858 errSchemaPath: `${it.errSchemaPath}/${keyword}`,1859 topSchemaRef: schemaRef,1860 compositeRule: true1861 }, valid);1862 cxt.pass(valid, () => cxt.error(true));1863 }1864 exports.macroKeywordCode = macroKeywordCode;1865 function funcKeywordCode(cxt, def) {1866 var _a;1867 const { gen, keyword, schema, parentSchema, $data, it } = cxt;1868 checkAsyncKeyword(it, def);1869 const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;1870 const validateRef = useKeyword(gen, keyword, validate);1871 const valid = gen.let("valid");1872 cxt.block$data(valid, validateKeyword);1873 cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);1874 function validateKeyword() {1875 if (def.errors === false) {1876 assignValid();1877 if (def.modifying)1878 modifyData(cxt);1879 reportErrs(() => cxt.error());1880 } else {1881 const ruleErrs = def.async ? validateAsync() : validateSync();1882 if (def.modifying)1883 modifyData(cxt);1884 reportErrs(() => addErrs(cxt, ruleErrs));1885 }1886 }1887 function validateAsync() {1888 const ruleErrs = gen.let("ruleErrs", null);1889 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)));1890 return ruleErrs;1891 }1892 function validateSync() {1893 const validateErrs = (0, codegen_1._)`${validateRef}.errors`;1894 gen.assign(validateErrs, null);1895 assignValid(codegen_1.nil);1896 return validateErrs;1897 }1898 function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {1899 const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;1900 const passSchema = !("compile" in def && !$data || def.schema === false);1901 gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);1902 }1903 function reportErrs(errors) {1904 var _a2;1905 gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors);1906 }1907 }1908 exports.funcKeywordCode = funcKeywordCode;1909 function modifyData(cxt) {1910 const { gen, data, it } = cxt;1911 gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));1912 }1913 function addErrs(cxt, errs) {1914 const { gen } = cxt;1915 gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {1916 gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);1917 (0, errors_1.extendErrors)(cxt);1918 }, () => cxt.error());1919 }1920 function checkAsyncKeyword({ schemaEnv }, def) {1921 if (def.async && !schemaEnv.$async)1922 throw new Error("async keyword in sync schema");1923 }1924 function useKeyword(gen, keyword, result) {1925 if (result === void 0)1926 throw new Error(`keyword "${keyword}" failed to compile`);1927 return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });1928 }1929 function validSchemaType(schema, schemaType, allowUndefined = false) {1930 return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");1931 }1932 exports.validSchemaType = validSchemaType;1933 function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {1934 if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {1935 throw new Error("ajv implementation error");1936 }1937 const deps = def.dependencies;1938 if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {1939 throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);1940 }1941 if (def.validateSchema) {1942 const valid = def.validateSchema(schema[keyword]);1943 if (!valid) {1944 const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors);1945 if (opts.validateSchema === "log")1946 self.logger.error(msg);1947 else1948 throw new Error(msg);1949 }1950 }1951 }1952 exports.validateKeywordUsage = validateKeywordUsage;1953 }1954});19551956// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js1957var require_subschema = __commonJS({1958 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports) {1959 "use strict";1960 Object.defineProperty(exports, "__esModule", { value: true });1961 exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;1962 var codegen_1 = require_codegen();1963 var util_1 = require_util();1964 function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {1965 if (keyword !== void 0 && schema !== void 0) {1966 throw new Error('both "keyword" and "schema" passed, only one allowed');1967 }1968 if (keyword !== void 0) {1969 const sch = it.schema[keyword];1970 return schemaProp === void 0 ? {1971 schema: sch,1972 schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,1973 errSchemaPath: `${it.errSchemaPath}/${keyword}`1974 } : {1975 schema: sch[schemaProp],1976 schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,1977 errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`1978 };1979 }1980 if (schema !== void 0) {1981 if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {1982 throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');1983 }1984 return {1985 schema,1986 schemaPath,1987 topSchemaRef,1988 errSchemaPath1989 };1990 }1991 throw new Error('either "keyword" or "schema" must be passed');1992 }1993 exports.getSubschema = getSubschema;1994 function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {1995 if (data !== void 0 && dataProp !== void 0) {1996 throw new Error('both "data" and "dataProp" passed, only one allowed');1997 }1998 const { gen } = it;1999 if (dataProp !== void 0) {2000 const { errorPath, dataPathArr, opts } = it;2001 const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);2002 dataContextProps(nextData);2003 subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;2004 subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;2005 subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];2006 }2007 if (data !== void 0) {2008 const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);2009 dataContextProps(nextData);2010 if (propertyName !== void 0)2011 subschema.propertyName = propertyName;2012 }2013 if (dataTypes)2014 subschema.dataTypes = dataTypes;2015 function dataContextProps(_nextData) {2016 subschema.data = _nextData;2017 subschema.dataLevel = it.dataLevel + 1;2018 subschema.dataTypes = [];2019 it.definedProperties = /* @__PURE__ */ new Set();2020 subschema.parentData = it.data;2021 subschema.dataNames = [...it.dataNames, _nextData];2022 }2023 }2024 exports.extendSubschemaData = extendSubschemaData;2025 function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {2026 if (compositeRule !== void 0)2027 subschema.compositeRule = compositeRule;2028 if (createErrors !== void 0)2029 subschema.createErrors = createErrors;2030 if (allErrors !== void 0)2031 subschema.allErrors = allErrors;2032 subschema.jtdDiscriminator = jtdDiscriminator;2033 subschema.jtdMetadata = jtdMetadata;2034 }2035 exports.extendSubschemaMode = extendSubschemaMode;2036 }2037});20382039// ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js2040var require_fast_deep_equal = __commonJS({2041 "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) {2042 "use strict";2043 module.exports = function equal(a, b) {2044 if (a === b) return true;2045 if (a && b && typeof a == "object" && typeof b == "object") {2046 if (a.constructor !== b.constructor) return false;2047 var length, i, keys;2048 if (Array.isArray(a)) {2049 length = a.length;2050 if (length != b.length) return false;2051 for (i = length; i-- !== 0; )2052 if (!equal(a[i], b[i])) return false;2053 return true;2054 }2055 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;2056 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();2057 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();2058 keys = Object.keys(a);2059 length = keys.length;2060 if (length !== Object.keys(b).length) return false;2061 for (i = length; i-- !== 0; )2062 if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;2063 for (i = length; i-- !== 0; ) {2064 var key = keys[i];2065 if (!equal(a[key], b[key])) return false;2066 }2067 return true;2068 }2069 return a !== a && b !== b;2070 };2071 }2072});20732074// ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js2075var require_json_schema_traverse = __commonJS({2076 "../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports, module) {2077 "use strict";2078 var traverse = module.exports = function(schema, opts, cb) {2079 if (typeof opts == "function") {2080 cb = opts;2081 opts = {};2082 }2083 cb = opts.cb || cb;2084 var pre = typeof cb == "function" ? cb : cb.pre || function() {2085 };2086 var post = cb.post || function() {2087 };2088 _traverse(opts, pre, post, schema, "", schema);2089 };2090 traverse.keywords = {2091 additionalItems: true,2092 items: true,2093 contains: true,2094 additionalProperties: true,2095 propertyNames: true,2096 not: true,2097 if: true,2098 then: true,2099 else: true2100 };2101 traverse.arrayKeywords = {2102 items: true,2103 allOf: true,2104 anyOf: true,2105 oneOf: true2106 };2107 traverse.propsKeywords = {2108 $defs: true,2109 definitions: true,2110 properties: true,2111 patternProperties: true,2112 dependencies: true2113 };2114 traverse.skipKeywords = {2115 default: true,2116 enum: true,2117 const: true,2118 required: true,2119 maximum: true,2120 minimum: true,2121 exclusiveMaximum: true,2122 exclusiveMinimum: true,2123 multipleOf: true,2124 maxLength: true,2125 minLength: true,2126 pattern: true,2127 format: true,2128 maxItems: true,2129 minItems: true,2130 uniqueItems: true,2131 maxProperties: true,2132 minProperties: true2133 };2134 function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {2135 if (schema && typeof schema == "object" && !Array.isArray(schema)) {2136 pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);2137 for (var key in schema) {2138 var sch = schema[key];2139 if (Array.isArray(sch)) {2140 if (key in traverse.arrayKeywords) {2141 for (var i = 0; i < sch.length; i++)2142 _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);2143 }2144 } else if (key in traverse.propsKeywords) {2145 if (sch && typeof sch == "object") {2146 for (var prop in sch)2147 _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);2148 }2149 } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {2150 _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);2151 }2152 }2153 post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);2154 }2155 }2156 function escapeJsonPtr(str) {2157 return str.replace(/~/g, "~0").replace(/\//g, "~1");2158 }2159 }2160});21612162// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js2163var require_resolve = __commonJS({2164 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js"(exports) {2165 "use strict";2166 Object.defineProperty(exports, "__esModule", { value: true });2167 exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;2168 var util_1 = require_util();2169 var equal = require_fast_deep_equal();2170 var traverse = require_json_schema_traverse();2171 var SIMPLE_INLINED = /* @__PURE__ */ new Set([2172 "type",2173 "format",2174 "pattern",2175 "maxLength",2176 "minLength",2177 "maxProperties",2178 "minProperties",2179 "maxItems",2180 "minItems",2181 "maximum",2182 "minimum",2183 "uniqueItems",2184 "multipleOf",2185 "required",2186 "enum",2187 "const"2188 ]);2189 function inlineRef(schema, limit = true) {2190 if (typeof schema == "boolean")2191 return true;2192 if (limit === true)2193 return !hasRef(schema);2194 if (!limit)2195 return false;2196 return countKeys(schema) <= limit;2197 }2198 exports.inlineRef = inlineRef;2199 var REF_KEYWORDS = /* @__PURE__ */ new Set([2200 "$ref",2201 "$recursiveRef",2202 "$recursiveAnchor",2203 "$dynamicRef",2204 "$dynamicAnchor"2205 ]);2206 function hasRef(schema) {2207 for (const key in schema) {2208 if (REF_KEYWORDS.has(key))2209 return true;2210 const sch = schema[key];2211 if (Array.isArray(sch) && sch.some(hasRef))2212 return true;2213 if (typeof sch == "object" && hasRef(sch))2214 return true;2215 }2216 return false;2217 }2218 function countKeys(schema) {2219 let count = 0;2220 for (const key in schema) {2221 if (key === "$ref")2222 return Infinity;2223 count++;2224 if (SIMPLE_INLINED.has(key))2225 continue;2226 if (typeof schema[key] == "object") {2227 (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));2228 }2229 if (count === Infinity)2230 return Infinity;2231 }2232 return count;2233 }2234 function getFullPath(resolver, id = "", normalize) {2235 if (normalize !== false)2236 id = normalizeId(id);2237 const p = resolver.parse(id);2238 return _getFullPath(resolver, p);2239 }2240 exports.getFullPath = getFullPath;2241 function _getFullPath(resolver, p) {2242 const serialized = resolver.serialize(p);2243 return serialized.split("#")[0] + "#";2244 }2245 exports._getFullPath = _getFullPath;2246 var TRAILING_SLASH_HASH = /#\/?$/;2247 function normalizeId(id) {2248 return id ? id.replace(TRAILING_SLASH_HASH, "") : "";2249 }2250 exports.normalizeId = normalizeId;2251 function resolveUrl(resolver, baseId, id) {2252 id = normalizeId(id);2253 return resolver.resolve(baseId, id);2254 }2255 exports.resolveUrl = resolveUrl;2256 var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;2257 function getSchemaRefs(schema, baseId) {2258 if (typeof schema == "boolean")2259 return {};2260 const { schemaId, uriResolver } = this.opts;2261 const schId = normalizeId(schema[schemaId] || baseId);2262 const baseIds = { "": schId };2263 const pathPrefix = getFullPath(uriResolver, schId, false);2264 const localRefs = {};2265 const schemaRefs = /* @__PURE__ */ new Set();2266 traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {2267 if (parentJsonPtr === void 0)2268 return;2269 const fullPath = pathPrefix + jsonPtr;2270 let innerBaseId = baseIds[parentJsonPtr];2271 if (typeof sch[schemaId] == "string")2272 innerBaseId = addRef.call(this, sch[schemaId]);2273 addAnchor.call(this, sch.$anchor);2274 addAnchor.call(this, sch.$dynamicAnchor);2275 baseIds[jsonPtr] = innerBaseId;2276 function addRef(ref) {2277 const _resolve = this.opts.uriResolver.resolve;2278 ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);2279 if (schemaRefs.has(ref))2280 throw ambiguos(ref);2281 schemaRefs.add(ref);2282 let schOrRef = this.refs[ref];2283 if (typeof schOrRef == "string")2284 schOrRef = this.refs[schOrRef];2285 if (typeof schOrRef == "object") {2286 checkAmbiguosRef(sch, schOrRef.schema, ref);2287 } else if (ref !== normalizeId(fullPath)) {2288 if (ref[0] === "#") {2289 checkAmbiguosRef(sch, localRefs[ref], ref);2290 localRefs[ref] = sch;2291 } else {2292 this.refs[ref] = fullPath;2293 }2294 }2295 return ref;2296 }2297 function addAnchor(anchor) {2298 if (typeof anchor == "string") {2299 if (!ANCHOR.test(anchor))2300 throw new Error(`invalid anchor "${anchor}"`);2301 addRef.call(this, `#${anchor}`);2302 }2303 }2304 });2305 return localRefs;2306 function checkAmbiguosRef(sch1, sch2, ref) {2307 if (sch2 !== void 0 && !equal(sch1, sch2))2308 throw ambiguos(ref);2309 }2310 function ambiguos(ref) {2311 return new Error(`reference "${ref}" resolves to more than one schema`);2312 }2313 }2314 exports.getSchemaRefs = getSchemaRefs;2315 }2316});23172318// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js2319var require_validate = __commonJS({2320 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js"(exports) {2321 "use strict";2322 Object.defineProperty(exports, "__esModule", { value: true });2323 exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;2324 var boolSchema_1 = require_boolSchema();2325 var dataType_1 = require_dataType();2326 var applicability_1 = require_applicability();2327 var dataType_2 = require_dataType();2328 var defaults_1 = require_defaults();2329 var keyword_1 = require_keyword();2330 var subschema_1 = require_subschema();2331 var codegen_1 = require_codegen();2332 var names_1 = require_names();2333 var resolve_1 = require_resolve();2334 var util_1 = require_util();2335 var errors_1 = require_errors();2336 function validateFunctionCode(it) {2337 if (isSchemaObj(it)) {2338 checkKeywords(it);2339 if (schemaCxtHasRules(it)) {2340 topSchemaObjCode(it);2341 return;2342 }2343 }2344 validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));2345 }2346 exports.validateFunctionCode = validateFunctionCode;2347 function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {2348 if (opts.code.es5) {2349 gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {2350 gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);2351 destructureValCxtES5(gen, opts);2352 gen.code(body);2353 });2354 } else {2355 gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));2356 }2357 }2358 function destructureValCxt(opts) {2359 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}}={}`;2360 }2361 function destructureValCxtES5(gen, opts) {2362 gen.if(names_1.default.valCxt, () => {2363 gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);2364 gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);2365 gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);2366 gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);2367 if (opts.dynamicRef)2368 gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);2369 }, () => {2370 gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);2371 gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);2372 gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);2373 gen.var(names_1.default.rootData, names_1.default.data);2374 if (opts.dynamicRef)2375 gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);2376 });2377 }2378 function topSchemaObjCode(it) {2379 const { schema, opts, gen } = it;2380 validateFunction(it, () => {2381 if (opts.$comment && schema.$comment)2382 commentKeyword(it);2383 checkNoDefault(it);2384 gen.let(names_1.default.vErrors, null);2385 gen.let(names_1.default.errors, 0);2386 if (opts.unevaluated)2387 resetEvaluated(it);2388 typeAndKeywords(it);2389 returnResults(it);2390 });2391 return;2392 }2393 function resetEvaluated(it) {2394 const { gen, validateName } = it;2395 it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);2396 gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));2397 gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));2398 }2399 function funcSourceUrl(schema, opts) {2400 const schId = typeof schema == "object" && schema[opts.schemaId];2401 return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;2402 }2403 function subschemaCode(it, valid) {2404 if (isSchemaObj(it)) {2405 checkKeywords(it);2406 if (schemaCxtHasRules(it)) {2407 subSchemaObjCode(it, valid);2408 return;2409 }2410 }2411 (0, boolSchema_1.boolOrEmptySchema)(it, valid);2412 }2413 function schemaCxtHasRules({ schema, self }) {2414 if (typeof schema == "boolean")2415 return !schema;2416 for (const key in schema)2417 if (self.RULES.all[key])2418 return true;2419 return false;2420 }2421 function isSchemaObj(it) {2422 return typeof it.schema != "boolean";2423 }2424 function subSchemaObjCode(it, valid) {2425 const { schema, gen, opts } = it;2426 if (opts.$comment && schema.$comment)2427 commentKeyword(it);2428 updateContext(it);2429 checkAsyncSchema(it);2430 const errsCount = gen.const("_errs", names_1.default.errors);2431 typeAndKeywords(it, errsCount);2432 gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);2433 }2434 function checkKeywords(it) {2435 (0, util_1.checkUnknownRules)(it);2436 checkRefsAndKeywords(it);2437 }2438 function typeAndKeywords(it, errsCount) {2439 if (it.opts.jtd)2440 return schemaKeywords(it, [], false, errsCount);2441 const types = (0, dataType_1.getSchemaTypes)(it.schema);2442 const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);2443 schemaKeywords(it, types, !checkedTypes, errsCount);2444 }2445 function checkRefsAndKeywords(it) {2446 const { schema, errSchemaPath, opts, self } = it;2447 if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {2448 self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);2449 }2450 }2451 function checkNoDefault(it) {2452 const { schema, opts } = it;2453 if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {2454 (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");2455 }2456 }2457 function updateContext(it) {2458 const schId = it.schema[it.opts.schemaId];2459 if (schId)2460 it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);2461 }2462 function checkAsyncSchema(it) {2463 if (it.schema.$async && !it.schemaEnv.$async)2464 throw new Error("async schema in sync schema");2465 }2466 function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {2467 const msg = schema.$comment;2468 if (opts.$comment === true) {2469 gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);2470 } else if (typeof opts.$comment == "function") {2471 const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;2472 const rootName = gen.scopeValue("root", { ref: schemaEnv.root });2473 gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);2474 }2475 }2476 function returnResults(it) {2477 const { gen, schemaEnv, validateName, ValidationError, opts } = it;2478 if (schemaEnv.$async) {2479 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})`));2480 } else {2481 gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);2482 if (opts.unevaluated)2483 assignEvaluated(it);2484 gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);2485 }2486 }2487 function assignEvaluated({ gen, evaluated, props, items }) {2488 if (props instanceof codegen_1.Name)2489 gen.assign((0, codegen_1._)`${evaluated}.props`, props);2490 if (items instanceof codegen_1.Name)2491 gen.assign((0, codegen_1._)`${evaluated}.items`, items);2492 }2493 function schemaKeywords(it, types, typeErrors, errsCount) {2494 const { gen, schema, data, allErrors, opts, self } = it;2495 const { RULES } = self;2496 if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {2497 gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));2498 return;2499 }2500 if (!opts.jtd)2501 checkStrictTypes(it, types);2502 gen.block(() => {2503 for (const group of RULES.rules)2504 groupKeywords(group);2505 groupKeywords(RULES.post);2506 });2507 function groupKeywords(group) {2508 if (!(0, applicability_1.shouldUseGroup)(schema, group))2509 return;2510 if (group.type) {2511 gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));2512 iterateKeywords(it, group);2513 if (types.length === 1 && types[0] === group.type && typeErrors) {2514 gen.else();2515 (0, dataType_2.reportTypeError)(it);2516 }2517 gen.endIf();2518 } else {2519 iterateKeywords(it, group);2520 }2521 if (!allErrors)2522 gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);2523 }2524 }2525 function iterateKeywords(it, group) {2526 const { gen, schema, opts: { useDefaults } } = it;2527 if (useDefaults)2528 (0, defaults_1.assignDefaults)(it, group.type);2529 gen.block(() => {2530 for (const rule of group.rules) {2531 if ((0, applicability_1.shouldUseRule)(schema, rule)) {2532 keywordCode(it, rule.keyword, rule.definition, group.type);2533 }2534 }2535 });2536 }2537 function checkStrictTypes(it, types) {2538 if (it.schemaEnv.meta || !it.opts.strictTypes)2539 return;2540 checkContextTypes(it, types);2541 if (!it.opts.allowUnionTypes)2542 checkMultipleTypes(it, types);2543 checkKeywordTypes(it, it.dataTypes);2544 }2545 function checkContextTypes(it, types) {2546 if (!types.length)2547 return;2548 if (!it.dataTypes.length) {2549 it.dataTypes = types;2550 return;2551 }2552 types.forEach((t) => {2553 if (!includesType(it.dataTypes, t)) {2554 strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);2555 }2556 });2557 narrowSchemaTypes(it, types);2558 }2559 function checkMultipleTypes(it, ts) {2560 if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {2561 strictTypesError(it, "use allowUnionTypes to allow union type keyword");2562 }2563 }2564 function checkKeywordTypes(it, ts) {2565 const rules = it.self.RULES.all;2566 for (const keyword in rules) {2567 const rule = rules[keyword];2568 if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {2569 const { type } = rule.definition;2570 if (type.length && !type.some((t) => hasApplicableType(ts, t))) {2571 strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);2572 }2573 }2574 }2575 }2576 function hasApplicableType(schTs, kwdT) {2577 return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");2578 }2579 function includesType(ts, t) {2580 return ts.includes(t) || t === "integer" && ts.includes("number");2581 }2582 function narrowSchemaTypes(it, withTypes) {2583 const ts = [];2584 for (const t of it.dataTypes) {2585 if (includesType(withTypes, t))2586 ts.push(t);2587 else if (withTypes.includes("integer") && t === "number")2588 ts.push("integer");2589 }2590 it.dataTypes = ts;2591 }2592 function strictTypesError(it, msg) {2593 const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;2594 msg += ` at "${schemaPath}" (strictTypes)`;2595 (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);2596 }2597 var KeywordCxt = class {2598 constructor(it, def, keyword) {2599 (0, keyword_1.validateKeywordUsage)(it, def, keyword);2600 this.gen = it.gen;2601 this.allErrors = it.allErrors;2602 this.keyword = keyword;2603 this.data = it.data;2604 this.schema = it.schema[keyword];2605 this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;2606 this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);2607 this.schemaType = def.schemaType;2608 this.parentSchema = it.schema;2609 this.params = {};2610 this.it = it;2611 this.def = def;2612 if (this.$data) {2613 this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));2614 } else {2615 this.schemaCode = this.schemaValue;2616 if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {2617 throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);2618 }2619 }2620 if ("code" in def ? def.trackErrors : def.errors !== false) {2621 this.errsCount = it.gen.const("_errs", names_1.default.errors);2622 }2623 }2624 result(condition, successAction, failAction) {2625 this.failResult((0, codegen_1.not)(condition), successAction, failAction);2626 }2627 failResult(condition, successAction, failAction) {2628 this.gen.if(condition);2629 if (failAction)2630 failAction();2631 else2632 this.error();2633 if (successAction) {2634 this.gen.else();2635 successAction();2636 if (this.allErrors)2637 this.gen.endIf();2638 } else {2639 if (this.allErrors)2640 this.gen.endIf();2641 else2642 this.gen.else();2643 }2644 }2645 pass(condition, failAction) {2646 this.failResult((0, codegen_1.not)(condition), void 0, failAction);2647 }2648 fail(condition) {2649 if (condition === void 0) {2650 this.error();2651 if (!this.allErrors)2652 this.gen.if(false);2653 return;2654 }2655 this.gen.if(condition);2656 this.error();2657 if (this.allErrors)2658 this.gen.endIf();2659 else2660 this.gen.else();2661 }2662 fail$data(condition) {2663 if (!this.$data)2664 return this.fail(condition);2665 const { schemaCode } = this;2666 this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);2667 }2668 error(append, errorParams, errorPaths) {2669 if (errorParams) {2670 this.setParams(errorParams);2671 this._error(append, errorPaths);2672 this.setParams({});2673 return;2674 }2675 this._error(append, errorPaths);2676 }2677 _error(append, errorPaths) {2678 ;2679 (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);2680 }2681 $dataError() {2682 (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);2683 }2684 reset() {2685 if (this.errsCount === void 0)2686 throw new Error('add "trackErrors" to keyword definition');2687 (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);2688 }2689 ok(cond) {2690 if (!this.allErrors)2691 this.gen.if(cond);2692 }2693 setParams(obj, assign) {2694 if (assign)2695 Object.assign(this.params, obj);2696 else2697 this.params = obj;2698 }2699 block$data(valid, codeBlock, $dataValid = codegen_1.nil) {2700 this.gen.block(() => {2701 this.check$data(valid, $dataValid);2702 codeBlock();2703 });2704 }2705 check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {2706 if (!this.$data)2707 return;2708 const { gen, schemaCode, schemaType, def } = this;2709 gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));2710 if (valid !== codegen_1.nil)2711 gen.assign(valid, true);2712 if (schemaType.length || def.validateSchema) {2713 gen.elseIf(this.invalid$data());2714 this.$dataError();2715 if (valid !== codegen_1.nil)2716 gen.assign(valid, false);2717 }2718 gen.else();2719 }2720 invalid$data() {2721 const { gen, schemaCode, schemaType, def, it } = this;2722 return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());2723 function wrong$DataType() {2724 if (schemaType.length) {2725 if (!(schemaCode instanceof codegen_1.Name))2726 throw new Error("ajv implementation error");2727 const st = Array.isArray(schemaType) ? schemaType : [schemaType];2728 return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;2729 }2730 return codegen_1.nil;2731 }2732 function invalid$DataSchema() {2733 if (def.validateSchema) {2734 const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });2735 return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;2736 }2737 return codegen_1.nil;2738 }2739 }2740 subschema(appl, valid) {2741 const subschema = (0, subschema_1.getSubschema)(this.it, appl);2742 (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);2743 (0, subschema_1.extendSubschemaMode)(subschema, appl);2744 const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };2745 subschemaCode(nextContext, valid);2746 return nextContext;2747 }2748 mergeEvaluated(schemaCxt, toName) {2749 const { it, gen } = this;2750 if (!it.opts.unevaluated)2751 return;2752 if (it.props !== true && schemaCxt.props !== void 0) {2753 it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);2754 }2755 if (it.items !== true && schemaCxt.items !== void 0) {2756 it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);2757 }2758 }2759 mergeValidEvaluated(schemaCxt, valid) {2760 const { it, gen } = this;2761 if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {2762 gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));2763 return true;2764 }2765 }2766 };2767 exports.KeywordCxt = KeywordCxt;2768 function keywordCode(it, keyword, def, ruleType) {2769 const cxt = new KeywordCxt(it, def, keyword);2770 if ("code" in def) {2771 def.code(cxt, ruleType);2772 } else if (cxt.$data && def.validate) {2773 (0, keyword_1.funcKeywordCode)(cxt, def);2774 } else if ("macro" in def) {2775 (0, keyword_1.macroKeywordCode)(cxt, def);2776 } else if (def.compile || def.validate) {2777 (0, keyword_1.funcKeywordCode)(cxt, def);2778 }2779 }2780 var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;2781 var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;2782 function getData($data, { dataLevel, dataNames, dataPathArr }) {2783 let jsonPointer;2784 let data;2785 if ($data === "")2786 return names_1.default.rootData;2787 if ($data[0] === "/") {2788 if (!JSON_POINTER.test($data))2789 throw new Error(`Invalid JSON-pointer: ${$data}`);2790 jsonPointer = $data;2791 data = names_1.default.rootData;2792 } else {2793 const matches = RELATIVE_JSON_POINTER.exec($data);2794 if (!matches)2795 throw new Error(`Invalid JSON-pointer: ${$data}`);2796 const up = +matches[1];2797 jsonPointer = matches[2];2798 if (jsonPointer === "#") {2799 if (up >= dataLevel)2800 throw new Error(errorMsg("property/index", up));2801 return dataPathArr[dataLevel - up];2802 }2803 if (up > dataLevel)2804 throw new Error(errorMsg("data", up));2805 data = dataNames[dataLevel - up];2806 if (!jsonPointer)2807 return data;2808 }2809 let expr = data;2810 const segments = jsonPointer.split("/");2811 for (const segment of segments) {2812 if (segment) {2813 data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;2814 expr = (0, codegen_1._)`${expr} && ${data}`;2815 }2816 }2817 return expr;2818 function errorMsg(pointerType, up) {2819 return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;2820 }2821 }2822 exports.getData = getData;2823 }2824});28252826// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js2827var require_validation_error = __commonJS({2828 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js"(exports) {2829 "use strict";2830 Object.defineProperty(exports, "__esModule", { value: true });2831 var ValidationError = class extends Error {2832 constructor(errors) {2833 super("validation failed");2834 this.errors = errors;2835 this.ajv = this.validation = true;2836 }2837 };2838 exports.default = ValidationError;2839 }2840});28412842// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js2843var require_ref_error = __commonJS({2844 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js"(exports) {2845 "use strict";2846 Object.defineProperty(exports, "__esModule", { value: true });2847 var resolve_1 = require_resolve();2848 var MissingRefError = class extends Error {2849 constructor(resolver, baseId, ref, msg) {2850 super(msg || `can't resolve reference ${ref} from id ${baseId}`);2851 this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);2852 this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));2853 }2854 };2855 exports.default = MissingRefError;2856 }2857});28582859// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js2860var require_compile = __commonJS({2861 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js"(exports) {2862 "use strict";2863 Object.defineProperty(exports, "__esModule", { value: true });2864 exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;2865 var codegen_1 = require_codegen();2866 var validation_error_1 = require_validation_error();2867 var names_1 = require_names();2868 var resolve_1 = require_resolve();2869 var util_1 = require_util();2870 var validate_1 = require_validate();2871 var SchemaEnv = class {2872 constructor(env) {2873 var _a;2874 this.refs = {};2875 this.dynamicAnchors = {};2876 let schema;2877 if (typeof env.schema == "object")2878 schema = env.schema;2879 this.schema = env.schema;2880 this.schemaId = env.schemaId;2881 this.root = env.root || this;2882 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"]);2883 this.schemaPath = env.schemaPath;2884 this.localRefs = env.localRefs;2885 this.meta = env.meta;2886 this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;2887 this.refs = {};2888 }2889 };2890 exports.SchemaEnv = SchemaEnv;2891 function compileSchema(sch) {2892 const _sch = getCompilingSchema.call(this, sch);2893 if (_sch)2894 return _sch;2895 const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);2896 const { es5, lines } = this.opts.code;2897 const { ownProperties } = this.opts;2898 const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });2899 let _ValidationError;2900 if (sch.$async) {2901 _ValidationError = gen.scopeValue("Error", {2902 ref: validation_error_1.default,2903 code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`2904 });2905 }2906 const validateName = gen.scopeName("validate");2907 sch.validateName = validateName;2908 const schemaCxt = {2909 gen,2910 allErrors: this.opts.allErrors,2911 data: names_1.default.data,2912 parentData: names_1.default.parentData,2913 parentDataProperty: names_1.default.parentDataProperty,2914 dataNames: [names_1.default.data],2915 dataPathArr: [codegen_1.nil],2916 // TODO can its length be used as dataLevel if nil is removed?2917 dataLevel: 0,2918 dataTypes: [],2919 definedProperties: /* @__PURE__ */ new Set(),2920 topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),2921 validateName,2922 ValidationError: _ValidationError,2923 schema: sch.schema,2924 schemaEnv: sch,2925 rootId,2926 baseId: sch.baseId || rootId,2927 schemaPath: codegen_1.nil,2928 errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),2929 errorPath: (0, codegen_1._)`""`,2930 opts: this.opts,2931 self: this2932 };2933 let sourceCode;2934 try {2935 this._compilations.add(sch);2936 (0, validate_1.validateFunctionCode)(schemaCxt);2937 gen.optimize(this.opts.code.optimize);2938 const validateCode = gen.toString();2939 sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;2940 if (this.opts.code.process)2941 sourceCode = this.opts.code.process(sourceCode, sch);2942 const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);2943 const validate = makeValidate(this, this.scope.get());2944 this.scope.value(validateName, { ref: validate });2945 validate.errors = null;2946 validate.schema = sch.schema;2947 validate.schemaEnv = sch;2948 if (sch.$async)2949 validate.$async = true;2950 if (this.opts.code.source === true) {2951 validate.source = { validateName, validateCode, scopeValues: gen._values };2952 }2953 if (this.opts.unevaluated) {2954 const { props, items } = schemaCxt;2955 validate.evaluated = {2956 props: props instanceof codegen_1.Name ? void 0 : props,2957 items: items instanceof codegen_1.Name ? void 0 : items,2958 dynamicProps: props instanceof codegen_1.Name,2959 dynamicItems: items instanceof codegen_1.Name2960 };2961 if (validate.source)2962 validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);2963 }2964 sch.validate = validate;2965 return sch;2966 } catch (e) {2967 delete sch.validate;2968 delete sch.validateName;2969 if (sourceCode)2970 this.logger.error("Error compiling schema, function code:", sourceCode);2971 throw e;2972 } finally {2973 this._compilations.delete(sch);2974 }2975 }2976 exports.compileSchema = compileSchema;2977 function resolveRef(root, baseId, ref) {2978 var _a;2979 ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);2980 const schOrFunc = root.refs[ref];2981 if (schOrFunc)2982 return schOrFunc;2983 let _sch = resolve.call(this, root, ref);2984 if (_sch === void 0) {2985 const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];2986 const { schemaId } = this.opts;2987 if (schema)2988 _sch = new SchemaEnv({ schema, schemaId, root, baseId });2989 }2990 if (_sch === void 0)2991 return;2992 return root.refs[ref] = inlineOrCompile.call(this, _sch);2993 }2994 exports.resolveRef = resolveRef;2995 function inlineOrCompile(sch) {2996 if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))2997 return sch.schema;2998 return sch.validate ? sch : compileSchema.call(this, sch);2999 }3000 function getCompilingSchema(schEnv) {3001 for (const sch of this._compilations) {3002 if (sameSchemaEnv(sch, schEnv))3003 return sch;3004 }3005 }3006 exports.getCompilingSchema = getCompilingSchema;3007 function sameSchemaEnv(s1, s2) {3008 return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;3009 }3010 function resolve(root, ref) {3011 let sch;3012 while (typeof (sch = this.refs[ref]) == "string")3013 ref = sch;3014 return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);3015 }3016 function resolveSchema(root, ref) {3017 const p = this.opts.uriResolver.parse(ref);3018 const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);3019 let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);3020 if (Object.keys(root.schema).length > 0 && refPath === baseId) {3021 return getJsonPointer.call(this, p, root);3022 }3023 const id = (0, resolve_1.normalizeId)(refPath);3024 const schOrRef = this.refs[id] || this.schemas[id];3025 if (typeof schOrRef == "string") {3026 const sch = resolveSchema.call(this, root, schOrRef);3027 if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")3028 return;3029 return getJsonPointer.call(this, p, sch);3030 }3031 if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")3032 return;3033 if (!schOrRef.validate)3034 compileSchema.call(this, schOrRef);3035 if (id === (0, resolve_1.normalizeId)(ref)) {3036 const { schema } = schOrRef;3037 const { schemaId } = this.opts;3038 const schId = schema[schemaId];3039 if (schId)3040 baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);3041 return new SchemaEnv({ schema, schemaId, root, baseId });3042 }3043 return getJsonPointer.call(this, p, schOrRef);3044 }3045 exports.resolveSchema = resolveSchema;3046 var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([3047 "properties",3048 "patternProperties",3049 "enum",3050 "dependencies",3051 "definitions"3052 ]);3053 function getJsonPointer(parsedRef, { baseId, schema, root }) {3054 var _a;3055 if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")3056 return;3057 for (const part of parsedRef.fragment.slice(1).split("/")) {3058 if (typeof schema === "boolean")3059 return;3060 const partSchema = schema[(0, util_1.unescapeFragment)(part)];3061 if (partSchema === void 0)3062 return;3063 schema = partSchema;3064 const schId = typeof schema === "object" && schema[this.opts.schemaId];3065 if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {3066 baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);3067 }3068 }3069 let env;3070 if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {3071 const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);3072 env = resolveSchema.call(this, root, $ref);3073 }3074 const { schemaId } = this.opts;3075 env = env || new SchemaEnv({ schema, schemaId, root, baseId });3076 if (env.schema !== env.root.schema)3077 return env;3078 return void 0;3079 }3080 }3081});30823083// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json3084var require_data = __commonJS({3085 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json"(exports, module) {3086 module.exports = {3087 $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",3088 description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",3089 type: "object",3090 required: ["$data"],3091 properties: {3092 $data: {3093 type: "string",3094 anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]3095 }3096 },3097 additionalProperties: false3098 };3099 }3100});31013102// ../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/lib/utils.js3103var require_utils = __commonJS({3104 "../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/lib/utils.js"(exports, module) {3105 "use strict";3106 var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);3107 var 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);3108 var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);3109 var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);3110 var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);3111 function stringArrayToHexStripped(input) {3112 let acc = "";3113 let code = 0;3114 let i = 0;3115 for (i = 0; i < input.length; i++) {3116 code = input[i].charCodeAt(0);3117 if (code === 48) {3118 continue;3119 }3120 if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {3121 return "";3122 }3123 acc += input[i];3124 break;3125 }3126 for (i += 1; i < input.length; i++) {3127 code = input[i].charCodeAt(0);3128 if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {3129 return "";3130 }3131 acc += input[i];3132 }3133 return acc;3134 }3135 var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);3136 function consumeIsZone(buffer) {3137 buffer.length = 0;3138 return true;3139 }3140 function consumeHextets(buffer, address, output) {3141 if (buffer.length) {3142 const hex = stringArrayToHexStripped(buffer);3143 if (hex !== "") {3144 address.push(hex);3145 } else {3146 output.error = true;3147 return false;3148 }3149 buffer.length = 0;3150 }3151 return true;3152 }3153 function getIPV6(input) {3154 let tokenCount = 0;3155 const output = { error: false, address: "", zone: "" };3156 const address = [];3157 const buffer = [];3158 let endipv6Encountered = false;3159 let endIpv6 = false;3160 let consume = consumeHextets;3161 for (let i = 0; i < input.length; i++) {3162 const cursor = input[i];3163 if (cursor === "[" || cursor === "]") {3164 continue;3165 }3166 if (cursor === ":") {3167 if (endipv6Encountered === true) {3168 endIpv6 = true;3169 }3170 if (!consume(buffer, address, output)) {3171 break;3172 }3173 if (++tokenCount > 7) {3174 output.error = true;3175 break;3176 }3177 if (i > 0 && input[i - 1] === ":") {3178 endipv6Encountered = true;3179 }3180 address.push(":");3181 continue;3182 } else if (cursor === "%") {3183 if (!consume(buffer, address, output)) {3184 break;3185 }3186 consume = consumeIsZone;3187 } else {3188 buffer.push(cursor);3189 continue;3190 }3191 }3192 if (buffer.length) {3193 if (consume === consumeIsZone) {3194 output.zone = buffer.join("");3195 } else if (endIpv6) {3196 address.push(buffer.join(""));3197 } else {3198 address.push(stringArrayToHexStripped(buffer));3199 }3200 }3201 output.address = address.join("");3202 return output;3203 }3204 function normalizeIPv6(host) {3205 if (findToken(host, ":") < 2) {3206 return { host, isIPV6: false };3207 }3208 const ipv62 = getIPV6(host);3209 if (!ipv62.error) {3210 let newHost = ipv62.address;3211 let escapedHost = ipv62.address;3212 if (ipv62.zone) {3213 newHost += "%" + ipv62.zone;3214 escapedHost += "%25" + ipv62.zone;3215 }3216 return { host: newHost, isIPV6: true, escapedHost };3217 } else {3218 return { host, isIPV6: false };3219 }3220 }3221 function findToken(str, token) {3222 let ind = 0;3223 for (let i = 0; i < str.length; i++) {3224 if (str[i] === token) ind++;3225 }3226 return ind;3227 }3228 function removeDotSegments(path) {3229 let input = path;3230 const output = [];3231 let nextSlash = -1;3232 let len = 0;3233 while (len = input.length) {3234 if (len === 1) {3235 if (input === ".") {3236 break;3237 } else if (input === "/") {3238 output.push("/");3239 break;3240 } else {3241 output.push(input);3242 break;3243 }3244 } else if (len === 2) {3245 if (input[0] === ".") {3246 if (input[1] === ".") {3247 break;3248 } else if (input[1] === "/") {3249 input = input.slice(2);3250 continue;3251 }3252 } else if (input[0] === "/") {3253 if (input[1] === "." || input[1] === "/") {3254 output.push("/");3255 break;3256 }3257 }3258 } else if (len === 3) {3259 if (input === "/..") {3260 if (output.length !== 0) {3261 output.pop();3262 }3263 output.push("/");3264 break;3265 }3266 }3267 if (input[0] === ".") {3268 if (input[1] === ".") {3269 if (input[2] === "/") {3270 input = input.slice(3);3271 continue;3272 }3273 } else if (input[1] === "/") {3274 input = input.slice(2);3275 continue;3276 }3277 } else if (input[0] === "/") {3278 if (input[1] === ".") {3279 if (input[2] === "/") {3280 input = input.slice(2);3281 continue;3282 } else if (input[2] === ".") {3283 if (input[3] === "/") {3284 input = input.slice(3);3285 if (output.length !== 0) {3286 output.pop();3287 }3288 continue;3289 }3290 }3291 }3292 }3293 if ((nextSlash = input.indexOf("/", 1)) === -1) {3294 output.push(input);3295 break;3296 } else {3297 output.push(input.slice(0, nextSlash));3298 input = input.slice(nextSlash);3299 }3300 }3301 return output.join("");3302 }3303 var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };3304 var HOST_DELIM_RE = /[@/?#:]/g;3305 var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;3306 function reescapeHostDelimiters(host, isIP) {3307 const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;3308 re.lastIndex = 0;3309 return host.replace(re, (ch) => HOST_DELIMS[ch]);3310 }3311 function normalizePercentEncoding(input, decodeUnreserved = false) {3312 if (input.indexOf("%") === -1) {3313 return input;3314 }3315 let output = "";3316 for (let i = 0; i < input.length; i++) {3317 if (input[i] === "%" && i + 2 < input.length) {3318 const hex = input.slice(i + 1, i + 3);3319 if (isHexPair(hex)) {3320 const normalizedHex = hex.toUpperCase();3321 const decoded = String.fromCharCode(parseInt(normalizedHex, 16));3322 if (decodeUnreserved && isUnreserved(decoded)) {3323 output += decoded;3324 } else {3325 output += "%" + normalizedHex;3326 }3327 i += 2;3328 continue;3329 }3330 }3331 output += input[i];3332 }3333 return output;3334 }3335 function normalizePathEncoding(input) {3336 let output = "";3337 for (let i = 0; i < input.length; i++) {3338 if (input[i] === "%" && i + 2 < input.length) {3339 const hex = input.slice(i + 1, i + 3);3340 if (isHexPair(hex)) {3341 const normalizedHex = hex.toUpperCase();3342 const decoded = String.fromCharCode(parseInt(normalizedHex, 16));3343 if (decoded !== "." && isUnreserved(decoded)) {3344 output += decoded;3345 } else {3346 output += "%" + normalizedHex;3347 }3348 i += 2;3349 continue;3350 }3351 }3352 if (isPathCharacter(input[i])) {3353 output += input[i];3354 } else {3355 output += escape(input[i]);3356 }3357 }3358 return output;3359 }3360 function escapePreservingEscapes(input) {3361 let output = "";3362 for (let i = 0; i < input.length; i++) {3363 if (input[i] === "%" && i + 2 < input.length) {3364 const hex = input.slice(i + 1, i + 3);3365 if (isHexPair(hex)) {3366 output += "%" + hex.toUpperCase();3367 i += 2;3368 continue;3369 }3370 }3371 output += escape(input[i]);3372 }3373 return output;3374 }3375 function recomposeAuthority(component) {3376 const uriTokens = [];3377 if (component.userinfo !== void 0) {3378 uriTokens.push(component.userinfo);3379 uriTokens.push("@");3380 }3381 if (component.host !== void 0) {3382 let host = unescape(component.host);3383 if (!isIPv4(host)) {3384 const ipV6res = normalizeIPv6(host);3385 if (ipV6res.isIPV6 === true) {3386 host = `[${ipV6res.escapedHost}]`;3387 } else {3388 host = reescapeHostDelimiters(host, false);3389 }3390 }3391 uriTokens.push(host);3392 }3393 if (typeof component.port === "number" || typeof component.port === "string") {3394 uriTokens.push(":");3395 uriTokens.push(String(component.port));3396 }3397 return uriTokens.length ? uriTokens.join("") : void 0;3398 }3399 module.exports = {3400 nonSimpleDomain,3401 recomposeAuthority,3402 reescapeHostDelimiters,3403 normalizePercentEncoding,3404 normalizePathEncoding,3405 escapePreservingEscapes,3406 removeDotSegments,3407 isIPv4,3408 isUUID,3409 normalizeIPv6,3410 stringArrayToHexStripped3411 };3412 }3413});34143415// ../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/lib/schemes.js3416var require_schemes = __commonJS({3417 "../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/lib/schemes.js"(exports, module) {3418 "use strict";3419 var { isUUID } = require_utils();3420 var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;3421 var supportedSchemeNames = (3422 /** @type {const} */3423 [3424 "http",3425 "https",3426 "ws",3427 "wss",3428 "urn",3429 "urn:uuid"3430 ]3431 );3432 function isValidSchemeName(name) {3433 return supportedSchemeNames.indexOf(3434 /** @type {*} */3435 name3436 ) !== -1;3437 }3438 function wsIsSecure(wsComponent) {3439 if (wsComponent.secure === true) {3440 return true;3441 } else if (wsComponent.secure === false) {3442 return false;3443 } else if (wsComponent.scheme) {3444 return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");3445 } else {3446 return false;3447 }3448 }3449 function httpParse(component) {3450 if (!component.host) {3451 component.error = component.error || "HTTP URIs must have a host.";3452 }3453 return component;3454 }3455 function httpSerialize(component) {3456 const secure = String(component.scheme).toLowerCase() === "https";3457 if (component.port === (secure ? 443 : 80) || component.port === "") {3458 component.port = void 0;3459 }3460 if (!component.path) {3461 component.path = "/";3462 }3463 return component;3464 }3465 function wsParse(wsComponent) {3466 wsComponent.secure = wsIsSecure(wsComponent);3467 wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");3468 wsComponent.path = void 0;3469 wsComponent.query = void 0;3470 return wsComponent;3471 }3472 function wsSerialize(wsComponent) {3473 if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {3474 wsComponent.port = void 0;3475 }3476 if (typeof wsComponent.secure === "boolean") {3477 wsComponent.scheme = wsComponent.secure ? "wss" : "ws";3478 wsComponent.secure = void 0;3479 }3480 if (wsComponent.resourceName) {3481 const [path, query] = wsComponent.resourceName.split("?");3482 wsComponent.path = path && path !== "/" ? path : void 0;3483 wsComponent.query = query;3484 wsComponent.resourceName = void 0;3485 }3486 wsComponent.fragment = void 0;3487 return wsComponent;3488 }3489 function urnParse(urnComponent, options) {3490 if (!urnComponent.path) {3491 urnComponent.error = "URN can not be parsed";3492 return urnComponent;3493 }3494 const matches = urnComponent.path.match(URN_REG);3495 if (matches) {3496 const scheme = options.scheme || urnComponent.scheme || "urn";3497 urnComponent.nid = matches[1].toLowerCase();3498 urnComponent.nss = matches[2];3499 const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;3500 const schemeHandler = getSchemeHandler(urnScheme);3501 urnComponent.path = void 0;3502 if (schemeHandler) {3503 urnComponent = schemeHandler.parse(urnComponent, options);3504 }3505 } else {3506 urnComponent.error = urnComponent.error || "URN can not be parsed.";3507 }3508 return urnComponent;3509 }3510 function urnSerialize(urnComponent, options) {3511 if (urnComponent.nid === void 0) {3512 throw new Error("URN without nid cannot be serialized");3513 }3514 const scheme = options.scheme || urnComponent.scheme || "urn";3515 const nid = urnComponent.nid.toLowerCase();3516 const urnScheme = `${scheme}:${options.nid || nid}`;3517 const schemeHandler = getSchemeHandler(urnScheme);3518 if (schemeHandler) {3519 urnComponent = schemeHandler.serialize(urnComponent, options);3520 }3521 const uriComponent = urnComponent;3522 const nss = urnComponent.nss;3523 uriComponent.path = `${nid || options.nid}:${nss}`;3524 options.skipEscape = true;3525 return uriComponent;3526 }3527 function urnuuidParse(urnComponent, options) {3528 const uuidComponent = urnComponent;3529 uuidComponent.uuid = uuidComponent.nss;3530 uuidComponent.nss = void 0;3531 if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {3532 uuidComponent.error = uuidComponent.error || "UUID is not valid.";3533 }3534 return uuidComponent;3535 }3536 function urnuuidSerialize(uuidComponent) {3537 const urnComponent = uuidComponent;3538 urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();3539 return urnComponent;3540 }3541 var http = (3542 /** @type {SchemeHandler} */3543 {3544 scheme: "http",3545 domainHost: true,3546 parse: httpParse,3547 serialize: httpSerialize3548 }3549 );3550 var https = (3551 /** @type {SchemeHandler} */3552 {3553 scheme: "https",3554 domainHost: http.domainHost,3555 parse: httpParse,3556 serialize: httpSerialize3557 }3558 );3559 var ws = (3560 /** @type {SchemeHandler} */3561 {3562 scheme: "ws",3563 domainHost: true,3564 parse: wsParse,3565 serialize: wsSerialize3566 }3567 );3568 var wss = (3569 /** @type {SchemeHandler} */3570 {3571 scheme: "wss",3572 domainHost: ws.domainHost,3573 parse: ws.parse,3574 serialize: ws.serialize3575 }3576 );3577 var urn = (3578 /** @type {SchemeHandler} */3579 {3580 scheme: "urn",3581 parse: urnParse,3582 serialize: urnSerialize,3583 skipNormalize: true3584 }3585 );3586 var urnuuid = (3587 /** @type {SchemeHandler} */3588 {3589 scheme: "urn:uuid",3590 parse: urnuuidParse,3591 serialize: urnuuidSerialize,3592 skipNormalize: true3593 }3594 );3595 var SCHEMES = (3596 /** @type {Record<SchemeName, SchemeHandler>} */3597 {3598 http,3599 https,3600 ws,3601 wss,3602 urn,3603 "urn:uuid": urnuuid3604 }3605 );3606 Object.setPrototypeOf(SCHEMES, null);3607 function getSchemeHandler(scheme) {3608 return scheme && (SCHEMES[3609 /** @type {SchemeName} */3610 scheme3611 ] || SCHEMES[3612 /** @type {SchemeName} */3613 scheme.toLowerCase()3614 ]) || void 0;3615 }3616 module.exports = {3617 wsIsSecure,3618 SCHEMES,3619 isValidSchemeName,3620 getSchemeHandler3621 };3622 }3623});36243625// ../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/index.js3626var require_fast_uri = __commonJS({3627 "../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/index.js"(exports, module) {3628 "use strict";3629 var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();3630 var { SCHEMES, getSchemeHandler } = require_schemes();3631 function normalize(uri, options) {3632 if (typeof uri === "string") {3633 uri = /** @type {T} */3634 normalizeString(uri, options);3635 } else if (typeof uri === "object") {3636 uri = /** @type {T} */3637 parse3(serialize(uri, options), options);3638 }3639 return uri;3640 }3641 function resolve(baseURI, relativeURI, options) {3642 const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };3643 const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions);3644 const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions);3645 if (baseMalformed || relativeMalformed) {3646 throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");3647 }3648 const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);3649 schemelessOptions.skipEscape = true;3650 return serialize(resolved, schemelessOptions);3651 }3652 function resolveComponent(base, relative, options, skipNormalization) {3653 const target = {};3654 if (!skipNormalization) {3655 base = parse3(serialize(base, options), options);3656 relative = parse3(serialize(relative, options), options);3657 }3658 options = options || {};3659 if (!options.tolerant && relative.scheme) {3660 target.scheme = relative.scheme;3661 target.userinfo = relative.userinfo;3662 target.host = relative.host;3663 target.port = relative.port;3664 target.path = removeDotSegments(relative.path || "");3665 target.query = relative.query;3666 } else {3667 if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {3668 target.userinfo = relative.userinfo;3669 target.host = relative.host;3670 target.port = relative.port;3671 target.path = removeDotSegments(relative.path || "");3672 target.query = relative.query;3673 } else {3674 if (!relative.path) {3675 target.path = base.path;3676 if (relative.query !== void 0) {3677 target.query = relative.query;3678 } else {3679 target.query = base.query;3680 }3681 } else {3682 if (relative.path[0] === "/") {3683 target.path = removeDotSegments(relative.path);3684 } else {3685 if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {3686 target.path = "/" + relative.path;3687 } else if (!base.path) {3688 target.path = relative.path;3689 } else {3690 target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;3691 }3692 target.path = removeDotSegments(target.path);3693 }3694 target.query = relative.query;3695 }3696 target.userinfo = base.userinfo;3697 target.host = base.host;3698 target.port = base.port;3699 }3700 target.scheme = base.scheme;3701 }3702 target.fragment = relative.fragment;3703 return target;3704 }3705 function equal(uriA, uriB, options) {3706 const normalizedA = normalizeComparableURI(uriA, options);3707 const normalizedB = normalizeComparableURI(uriB, options);3708 return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase();3709 }3710 function serialize(cmpts, opts) {3711 const component = {3712 host: cmpts.host,3713 scheme: cmpts.scheme,3714 userinfo: cmpts.userinfo,3715 port: cmpts.port,3716 path: cmpts.path,3717 query: cmpts.query,3718 nid: cmpts.nid,3719 nss: cmpts.nss,3720 uuid: cmpts.uuid,3721 fragment: cmpts.fragment,3722 reference: cmpts.reference,3723 resourceName: cmpts.resourceName,3724 secure: cmpts.secure,3725 error: ""3726 };3727 const options = Object.assign({}, opts);3728 const uriTokens = [];3729 const schemeHandler = getSchemeHandler(options.scheme || component.scheme);3730 if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);3731 if (component.path !== void 0) {3732 if (!options.skipEscape) {3733 component.path = escapePreservingEscapes(component.path);3734 if (component.scheme !== void 0) {3735 component.path = component.path.split("%3A").join(":");3736 }3737 } else {3738 component.path = normalizePercentEncoding(component.path);3739 }3740 }3741 if (options.reference !== "suffix" && component.scheme) {3742 uriTokens.push(component.scheme, ":");3743 }3744 const authority = recomposeAuthority(component);3745 if (authority !== void 0) {3746 if (options.reference !== "suffix") {3747 uriTokens.push("//");3748 }3749 uriTokens.push(authority);3750 if (component.path && component.path[0] !== "/") {3751 uriTokens.push("/");3752 }3753 }3754 if (component.path !== void 0) {3755 let s = component.path;3756 if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {3757 s = removeDotSegments(s);3758 }3759 if (authority === void 0 && s[0] === "/" && s[1] === "/") {3760 s = "/%2F" + s.slice(2);3761 }3762 uriTokens.push(s);3763 }3764 if (component.query !== void 0) {3765 uriTokens.push("?", component.query);3766 }3767 if (component.fragment !== void 0) {3768 uriTokens.push("#", component.fragment);3769 }3770 return uriTokens.join("");3771 }3772 var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;3773 var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;3774 var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;3775 function getParseError(parsed, matches) {3776 if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {3777 return 'URI path must start with "/" when authority is present.';3778 }3779 if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) {3780 return "URI port is malformed.";3781 }3782 return void 0;3783 }3784 function parseWithStatus(uri, opts) {3785 const options = Object.assign({}, opts);3786 const parsed = {3787 scheme: void 0,3788 userinfo: void 0,3789 host: "",3790 port: void 0,3791 path: "",3792 query: void 0,3793 fragment: void 03794 };3795 let malformedAuthorityOrPort = false;3796 let isIP = false;3797 if (options.reference === "suffix") {3798 if (options.scheme) {3799 uri = options.scheme + ":" + uri;3800 } else {3801 uri = "//" + uri;3802 }3803 }3804 const authorityMatch = uri.match(AUTHORITY_PREFIX);3805 if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {3806 parsed.error = "URI authority must not contain a literal backslash.";3807 malformedAuthorityOrPort = true;3808 }3809 const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);3810 if (introducerMatch !== null) {3811 const region = introducerMatch[1];3812 const normalizedRegion = region.replace(/[\t\n\r]/g, "");3813 if (normalizedRegion.length >= 2) {3814 if (normalizedRegion.slice(0, 2) !== "//") {3815 parsed.error = parsed.error || "URI authority must not contain a literal backslash.";3816 malformedAuthorityOrPort = true;3817 } else if (region.length !== normalizedRegion.length) {3818 parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";3819 malformedAuthorityOrPort = true;3820 }3821 }3822 }3823 const matches = uri.match(URI_PARSE);3824 if (matches) {3825 parsed.scheme = matches[1];3826 parsed.userinfo = matches[3];3827 parsed.host = matches[4];3828 parsed.port = parseInt(matches[5], 10);3829 parsed.path = matches[6] || "";3830 parsed.query = matches[7];3831 parsed.fragment = matches[8];3832 if (isNaN(parsed.port)) {3833 parsed.port = matches[5];3834 }3835 const parseError = getParseError(parsed, matches);3836 if (parseError !== void 0) {3837 parsed.error = parsed.error || parseError;3838 malformedAuthorityOrPort = true;3839 }3840 if (parsed.host) {3841 const ipv4result = isIPv4(parsed.host);3842 if (ipv4result === false) {3843 const ipv6result = normalizeIPv6(parsed.host);3844 parsed.host = ipv6result.host.toLowerCase();3845 isIP = ipv6result.isIPV6;3846 } else {3847 isIP = true;3848 }3849 }3850 if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {3851 parsed.reference = "same-document";3852 } else if (parsed.scheme === void 0) {3853 parsed.reference = "relative";3854 } else if (parsed.fragment === void 0) {3855 parsed.reference = "absolute";3856 } else {3857 parsed.reference = "uri";3858 }3859 if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {3860 parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";3861 }3862 const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);3863 if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {3864 if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {3865 try {3866 parsed.host = new URL("http://" + parsed.host).hostname;3867 } catch (e) {3868 parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;3869 }3870 }3871 }3872 if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {3873 if (uri.indexOf("%") !== -1) {3874 if (parsed.scheme !== void 0) {3875 parsed.scheme = unescape(parsed.scheme);3876 }3877 if (parsed.host !== void 0) {3878 parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);3879 }3880 }3881 if (parsed.path) {3882 parsed.path = normalizePathEncoding(parsed.path);3883 }3884 if (parsed.fragment) {3885 try {3886 parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));3887 } catch {3888 parsed.error = parsed.error || "URI malformed";3889 }3890 }3891 }3892 if (schemeHandler && schemeHandler.parse) {3893 schemeHandler.parse(parsed, options);3894 }3895 } else {3896 parsed.error = parsed.error || "URI can not be parsed.";3897 }3898 return { parsed, malformedAuthorityOrPort };3899 }3900 function parse3(uri, opts) {3901 return parseWithStatus(uri, opts).parsed;3902 }3903 function normalizeString(uri, opts) {3904 return normalizeStringWithStatus(uri, opts).normalized;3905 }3906 function normalizeStringWithStatus(uri, opts) {3907 const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);3908 return {3909 normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),3910 malformedAuthorityOrPort3911 };3912 }3913 function normalizeComparableURI(uri, opts) {3914 if (typeof uri === "string") {3915 const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts);3916 return malformedAuthorityOrPort ? void 0 : normalized;3917 }3918 if (typeof uri === "object") {3919 return serialize(uri, opts);3920 }3921 }3922 var fastUri = {3923 SCHEMES,3924 normalize,3925 resolve,3926 resolveComponent,3927 equal,3928 serialize,3929 parse: parse33930 };3931 module.exports = fastUri;3932 module.exports.default = fastUri;3933 module.exports.fastUri = fastUri;3934 }3935});39363937// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js3938var require_uri = __commonJS({3939 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js"(exports) {3940 "use strict";3941 Object.defineProperty(exports, "__esModule", { value: true });3942 var uri = require_fast_uri();3943 uri.code = 'require("ajv/dist/runtime/uri").default';3944 exports.default = uri;3945 }3946});39473948// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js3949var require_core = __commonJS({3950 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js"(exports) {3951 "use strict";3952 Object.defineProperty(exports, "__esModule", { value: true });3953 exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;3954 var validate_1 = require_validate();3955 Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {3956 return validate_1.KeywordCxt;3957 } });3958 var codegen_1 = require_codegen();3959 Object.defineProperty(exports, "_", { enumerable: true, get: function() {3960 return codegen_1._;3961 } });3962 Object.defineProperty(exports, "str", { enumerable: true, get: function() {3963 return codegen_1.str;3964 } });3965 Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {3966 return codegen_1.stringify;3967 } });3968 Object.defineProperty(exports, "nil", { enumerable: true, get: function() {3969 return codegen_1.nil;3970 } });3971 Object.defineProperty(exports, "Name", { enumerable: true, get: function() {3972 return codegen_1.Name;3973 } });3974 Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {3975 return codegen_1.CodeGen;3976 } });3977 var validation_error_1 = require_validation_error();3978 var ref_error_1 = require_ref_error();3979 var rules_1 = require_rules();3980 var compile_1 = require_compile();3981 var codegen_2 = require_codegen();3982 var resolve_1 = require_resolve();3983 var dataType_1 = require_dataType();3984 var util_1 = require_util();3985 var $dataRefSchema = require_data();3986 var uri_1 = require_uri();3987 var defaultRegExp = (str, flags) => new RegExp(str, flags);3988 defaultRegExp.code = "new RegExp";3989 var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];3990 var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([3991 "validate",3992 "serialize",3993 "parse",3994 "wrapper",3995 "root",3996 "schema",3997 "keyword",3998 "pattern",3999 "formats",4000 "validate$data",4001 "func",4002 "obj",4003 "Error"4004 ]);4005 var removedOptions = {4006 errorDataPath: "",4007 format: "`validateFormats: false` can be used instead.",4008 nullable: '"nullable" keyword is supported by default.',4009 jsonPointers: "Deprecated jsPropertySyntax can be used instead.",4010 extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",4011 missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",4012 processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",4013 sourceCode: "Use option `code: {source: true}`",4014 strictDefaults: "It is default now, see option `strict`.",4015 strictKeywords: "It is default now, see option `strict`.",4016 uniqueItems: '"uniqueItems" keyword is always validated.',4017 unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",4018 cache: "Map is used as cache, schema object as key.",4019 serialize: "Map is used as cache, schema object as key.",4020 ajvErrors: "It is default now."4021 };4022 var deprecatedOptions = {4023 ignoreKeywordsWithRef: "",4024 jsPropertySyntax: "",4025 unicode: '"minLength"/"maxLength" account for unicode characters by default.'4026 };4027 var MAX_EXPRESSION = 200;4028 function requiredOptions(o) {4029 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;4030 const s = o.strict;4031 const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;4032 const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;4033 const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;4034 const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;4035 return {4036 strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,4037 strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,4038 strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",4039 strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",4040 strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,4041 code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },4042 loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,4043 loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,4044 meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,4045 messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,4046 inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,4047 schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",4048 addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,4049 validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,4050 validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,4051 unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,4052 int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,4053 uriResolver4054 };4055 }4056 var Ajv2 = class {4057 constructor(opts = {}) {4058 this.schemas = {};4059 this.refs = {};4060 this.formats = /* @__PURE__ */ Object.create(null);4061 this._compilations = /* @__PURE__ */ new Set();4062 this._loading = {};4063 this._cache = /* @__PURE__ */ new Map();4064 opts = this.opts = { ...opts, ...requiredOptions(opts) };4065 const { es5, lines } = this.opts.code;4066 this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });4067 this.logger = getLogger(opts.logger);4068 const formatOpt = opts.validateFormats;4069 opts.validateFormats = false;4070 this.RULES = (0, rules_1.getRules)();4071 checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");4072 checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");4073 this._metaOpts = getMetaSchemaOptions.call(this);4074 if (opts.formats)4075 addInitialFormats.call(this);4076 this._addVocabularies();4077 this._addDefaultMetaSchema();4078 if (opts.keywords)4079 addInitialKeywords.call(this, opts.keywords);4080 if (typeof opts.meta == "object")4081 this.addMetaSchema(opts.meta);4082 addInitialSchemas.call(this);4083 opts.validateFormats = formatOpt;4084 }4085 _addVocabularies() {4086 this.addKeyword("$async");4087 }4088 _addDefaultMetaSchema() {4089 const { $data, meta, schemaId } = this.opts;4090 let _dataRefSchema = $dataRefSchema;4091 if (schemaId === "id") {4092 _dataRefSchema = { ...$dataRefSchema };4093 _dataRefSchema.id = _dataRefSchema.$id;4094 delete _dataRefSchema.$id;4095 }4096 if (meta && $data)4097 this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);4098 }4099 defaultMeta() {4100 const { meta, schemaId } = this.opts;4101 return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;4102 }4103 validate(schemaKeyRef, data) {4104 let v;4105 if (typeof schemaKeyRef == "string") {4106 v = this.getSchema(schemaKeyRef);4107 if (!v)4108 throw new Error(`no schema with key or ref "${schemaKeyRef}"`);4109 } else {4110 v = this.compile(schemaKeyRef);4111 }4112 const valid = v(data);4113 if (!("$async" in v))4114 this.errors = v.errors;4115 return valid;4116 }4117 compile(schema, _meta) {4118 const sch = this._addSchema(schema, _meta);4119 return sch.validate || this._compileSchemaEnv(sch);4120 }4121 compileAsync(schema, meta) {4122 if (typeof this.opts.loadSchema != "function") {4123 throw new Error("options.loadSchema should be a function");4124 }4125 const { loadSchema } = this.opts;4126 return runCompileAsync.call(this, schema, meta);4127 async function runCompileAsync(_schema, _meta) {4128 await loadMetaSchema.call(this, _schema.$schema);4129 const sch = this._addSchema(_schema, _meta);4130 return sch.validate || _compileAsync.call(this, sch);4131 }4132 async function loadMetaSchema($ref) {4133 if ($ref && !this.getSchema($ref)) {4134 await runCompileAsync.call(this, { $ref }, true);4135 }4136 }4137 async function _compileAsync(sch) {4138 try {4139 return this._compileSchemaEnv(sch);4140 } catch (e) {4141 if (!(e instanceof ref_error_1.default))4142 throw e;4143 checkLoaded.call(this, e);4144 await loadMissingSchema.call(this, e.missingSchema);4145 return _compileAsync.call(this, sch);4146 }4147 }4148 function checkLoaded({ missingSchema: ref, missingRef }) {4149 if (this.refs[ref]) {4150 throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);4151 }4152 }4153 async function loadMissingSchema(ref) {4154 const _schema = await _loadSchema.call(this, ref);4155 if (!this.refs[ref])4156 await loadMetaSchema.call(this, _schema.$schema);4157 if (!this.refs[ref])4158 this.addSchema(_schema, ref, meta);4159 }4160 async function _loadSchema(ref) {4161 const p = this._loading[ref];4162 if (p)4163 return p;4164 try {4165 return await (this._loading[ref] = loadSchema(ref));4166 } finally {4167 delete this._loading[ref];4168 }4169 }4170 }4171 // Adds schema to the instance4172 addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {4173 if (Array.isArray(schema)) {4174 for (const sch of schema)4175 this.addSchema(sch, void 0, _meta, _validateSchema);4176 return this;4177 }4178 let id;4179 if (typeof schema === "object") {4180 const { schemaId } = this.opts;4181 id = schema[schemaId];4182 if (id !== void 0 && typeof id != "string") {4183 throw new Error(`schema ${schemaId} must be string`);4184 }4185 }4186 key = (0, resolve_1.normalizeId)(key || id);4187 this._checkUnique(key);4188 this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);4189 return this;4190 }4191 // Add schema that will be used to validate other schemas4192 // options in META_IGNORE_OPTIONS are alway set to false4193 addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {4194 this.addSchema(schema, key, true, _validateSchema);4195 return this;4196 }4197 // Validate schema against its meta-schema4198 validateSchema(schema, throwOrLogError) {4199 if (typeof schema == "boolean")4200 return true;4201 let $schema;4202 $schema = schema.$schema;4203 if ($schema !== void 0 && typeof $schema != "string") {4204 throw new Error("$schema must be a string");4205 }4206 $schema = $schema || this.opts.defaultMeta || this.defaultMeta();4207 if (!$schema) {4208 this.logger.warn("meta-schema not available");4209 this.errors = null;4210 return true;4211 }4212 const valid = this.validate($schema, schema);4213 if (!valid && throwOrLogError) {4214 const message = "schema is invalid: " + this.errorsText();4215 if (this.opts.validateSchema === "log")4216 this.logger.error(message);4217 else4218 throw new Error(message);4219 }4220 return valid;4221 }4222 // Get compiled schema by `key` or `ref`.4223 // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)4224 getSchema(keyRef) {4225 let sch;4226 while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")4227 keyRef = sch;4228 if (sch === void 0) {4229 const { schemaId } = this.opts;4230 const root = new compile_1.SchemaEnv({ schema: {}, schemaId });4231 sch = compile_1.resolveSchema.call(this, root, keyRef);4232 if (!sch)4233 return;4234 this.refs[keyRef] = sch;4235 }4236 return sch.validate || this._compileSchemaEnv(sch);4237 }4238 // Remove cached schema(s).4239 // If no parameter is passed all schemas but meta-schemas are removed.4240 // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.4241 // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.4242 removeSchema(schemaKeyRef) {4243 if (schemaKeyRef instanceof RegExp) {4244 this._removeAllSchemas(this.schemas, schemaKeyRef);4245 this._removeAllSchemas(this.refs, schemaKeyRef);4246 return this;4247 }4248 switch (typeof schemaKeyRef) {4249 case "undefined":4250 this._removeAllSchemas(this.schemas);4251 this._removeAllSchemas(this.refs);4252 this._cache.clear();4253 return this;4254 case "string": {4255 const sch = getSchEnv.call(this, schemaKeyRef);4256 if (typeof sch == "object")4257 this._cache.delete(sch.schema);4258 delete this.schemas[schemaKeyRef];4259 delete this.refs[schemaKeyRef];4260 return this;4261 }4262 case "object": {4263 const cacheKey = schemaKeyRef;4264 this._cache.delete(cacheKey);4265 let id = schemaKeyRef[this.opts.schemaId];4266 if (id) {4267 id = (0, resolve_1.normalizeId)(id);4268 delete this.schemas[id];4269 delete this.refs[id];4270 }4271 return this;4272 }4273 default:4274 throw new Error("ajv.removeSchema: invalid parameter");4275 }4276 }4277 // add "vocabulary" - a collection of keywords4278 addVocabulary(definitions) {4279 for (const def of definitions)4280 this.addKeyword(def);4281 return this;4282 }4283 addKeyword(kwdOrDef, def) {4284 let keyword;4285 if (typeof kwdOrDef == "string") {4286 keyword = kwdOrDef;4287 if (typeof def == "object") {4288 this.logger.warn("these parameters are deprecated, see docs for addKeyword");4289 def.keyword = keyword;4290 }4291 } else if (typeof kwdOrDef == "object" && def === void 0) {4292 def = kwdOrDef;4293 keyword = def.keyword;4294 if (Array.isArray(keyword) && !keyword.length) {4295 throw new Error("addKeywords: keyword must be string or non-empty array");4296 }4297 } else {4298 throw new Error("invalid addKeywords parameters");4299 }4300 checkKeyword.call(this, keyword, def);4301 if (!def) {4302 (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));4303 return this;4304 }4305 keywordMetaschema.call(this, def);4306 const definition = {4307 ...def,4308 type: (0, dataType_1.getJSONTypes)(def.type),4309 schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)4310 };4311 (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));4312 return this;4313 }4314 getKeyword(keyword) {4315 const rule = this.RULES.all[keyword];4316 return typeof rule == "object" ? rule.definition : !!rule;4317 }4318 // Remove keyword4319 removeKeyword(keyword) {4320 const { RULES } = this;4321 delete RULES.keywords[keyword];4322 delete RULES.all[keyword];4323 for (const group of RULES.rules) {4324 const i = group.rules.findIndex((rule) => rule.keyword === keyword);4325 if (i >= 0)4326 group.rules.splice(i, 1);4327 }4328 return this;4329 }4330 // Add format4331 addFormat(name, format) {4332 if (typeof format == "string")4333 format = new RegExp(format);4334 this.formats[name] = format;4335 return this;4336 }4337 errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {4338 if (!errors || errors.length === 0)4339 return "No errors";4340 return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);4341 }4342 $dataMetaSchema(metaSchema, keywordsJsonPointers) {4343 const rules = this.RULES.all;4344 metaSchema = JSON.parse(JSON.stringify(metaSchema));4345 for (const jsonPointer of keywordsJsonPointers) {4346 const segments = jsonPointer.split("/").slice(1);4347 let keywords = metaSchema;4348 for (const seg of segments)4349 keywords = keywords[seg];4350 for (const key in rules) {4351 const rule = rules[key];4352 if (typeof rule != "object")4353 continue;4354 const { $data } = rule.definition;4355 const schema = keywords[key];4356 if ($data && schema)4357 keywords[key] = schemaOrData(schema);4358 }4359 }4360 return metaSchema;4361 }4362 _removeAllSchemas(schemas, regex) {4363 for (const keyRef in schemas) {4364 const sch = schemas[keyRef];4365 if (!regex || regex.test(keyRef)) {4366 if (typeof sch == "string") {4367 delete schemas[keyRef];4368 } else if (sch && !sch.meta) {4369 this._cache.delete(sch.schema);4370 delete schemas[keyRef];4371 }4372 }4373 }4374 }4375 _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {4376 let id;4377 const { schemaId } = this.opts;4378 if (typeof schema == "object") {4379 id = schema[schemaId];4380 } else {4381 if (this.opts.jtd)4382 throw new Error("schema must be object");4383 else if (typeof schema != "boolean")4384 throw new Error("schema must be object or boolean");4385 }4386 let sch = this._cache.get(schema);4387 if (sch !== void 0)4388 return sch;4389 baseId = (0, resolve_1.normalizeId)(id || baseId);4390 const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);4391 sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });4392 this._cache.set(sch.schema, sch);4393 if (addSchema && !baseId.startsWith("#")) {4394 if (baseId)4395 this._checkUnique(baseId);4396 this.refs[baseId] = sch;4397 }4398 if (validateSchema)4399 this.validateSchema(schema, true);4400 return sch;4401 }4402 _checkUnique(id) {4403 if (this.schemas[id] || this.refs[id]) {4404 throw new Error(`schema with key or id "${id}" already exists`);4405 }4406 }4407 _compileSchemaEnv(sch) {4408 if (sch.meta)4409 this._compileMetaSchema(sch);4410 else4411 compile_1.compileSchema.call(this, sch);4412 if (!sch.validate)4413 throw new Error("ajv implementation error");4414 return sch.validate;4415 }4416 _compileMetaSchema(sch) {4417 const currentOpts = this.opts;4418 this.opts = this._metaOpts;4419 try {4420 compile_1.compileSchema.call(this, sch);4421 } finally {4422 this.opts = currentOpts;4423 }4424 }4425 };4426 Ajv2.ValidationError = validation_error_1.default;4427 Ajv2.MissingRefError = ref_error_1.default;4428 exports.default = Ajv2;4429 function checkOptions(checkOpts, options, msg, log = "error") {4430 for (const key in checkOpts) {4431 const opt = key;4432 if (opt in options)4433 this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);4434 }4435 }4436 function getSchEnv(keyRef) {4437 keyRef = (0, resolve_1.normalizeId)(keyRef);4438 return this.schemas[keyRef] || this.refs[keyRef];4439 }4440 function addInitialSchemas() {4441 const optsSchemas = this.opts.schemas;4442 if (!optsSchemas)4443 return;4444 if (Array.isArray(optsSchemas))4445 this.addSchema(optsSchemas);4446 else4447 for (const key in optsSchemas)4448 this.addSchema(optsSchemas[key], key);4449 }4450 function addInitialFormats() {4451 for (const name in this.opts.formats) {4452 const format = this.opts.formats[name];4453 if (format)4454 this.addFormat(name, format);4455 }4456 }4457 function addInitialKeywords(defs) {4458 if (Array.isArray(defs)) {4459 this.addVocabulary(defs);4460 return;4461 }4462 this.logger.warn("keywords option as map is deprecated, pass array");4463 for (const keyword in defs) {4464 const def = defs[keyword];4465 if (!def.keyword)4466 def.keyword = keyword;4467 this.addKeyword(def);4468 }4469 }4470 function getMetaSchemaOptions() {4471 const metaOpts = { ...this.opts };4472 for (const opt of META_IGNORE_OPTIONS)4473 delete metaOpts[opt];4474 return metaOpts;4475 }4476 var noLogs = { log() {4477 }, warn() {4478 }, error() {4479 } };4480 function getLogger(logger) {4481 if (logger === false)4482 return noLogs;4483 if (logger === void 0)4484 return console;4485 if (logger.log && logger.warn && logger.error)4486 return logger;4487 throw new Error("logger must implement log, warn and error methods");4488 }4489 var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;4490 function checkKeyword(keyword, def) {4491 const { RULES } = this;4492 (0, util_1.eachItem)(keyword, (kwd) => {4493 if (RULES.keywords[kwd])4494 throw new Error(`Keyword ${kwd} is already defined`);4495 if (!KEYWORD_NAME.test(kwd))4496 throw new Error(`Keyword ${kwd} has invalid name`);4497 });4498 if (!def)4499 return;4500 if (def.$data && !("code" in def || "validate" in def)) {4501 throw new Error('$data keyword must have "code" or "validate" function');4502 }4503 }4504 function addRule(keyword, definition, dataType) {4505 var _a;4506 const post = definition === null || definition === void 0 ? void 0 : definition.post;4507 if (dataType && post)4508 throw new Error('keyword with "post" flag cannot have "type"');4509 const { RULES } = this;4510 let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);4511 if (!ruleGroup) {4512 ruleGroup = { type: dataType, rules: [] };4513 RULES.rules.push(ruleGroup);4514 }4515 RULES.keywords[keyword] = true;4516 if (!definition)4517 return;4518 const rule = {4519 keyword,4520 definition: {4521 ...definition,4522 type: (0, dataType_1.getJSONTypes)(definition.type),4523 schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)4524 }4525 };4526 if (definition.before)4527 addBeforeRule.call(this, ruleGroup, rule, definition.before);4528 else4529 ruleGroup.rules.push(rule);4530 RULES.all[keyword] = rule;4531 (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));4532 }4533 function addBeforeRule(ruleGroup, rule, before) {4534 const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);4535 if (i >= 0) {4536 ruleGroup.rules.splice(i, 0, rule);4537 } else {4538 ruleGroup.rules.push(rule);4539 this.logger.warn(`rule ${before} is not defined`);4540 }4541 }4542 function keywordMetaschema(def) {4543 let { metaSchema } = def;4544 if (metaSchema === void 0)4545 return;4546 if (def.$data && this.opts.$data)4547 metaSchema = schemaOrData(metaSchema);4548 def.validateSchema = this.compile(metaSchema, true);4549 }4550 var $dataRef = {4551 $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"4552 };4553 function schemaOrData(schema) {4554 return { anyOf: [schema, $dataRef] };4555 }4556 }4557});45584559// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js4560var require_id = __commonJS({4561 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports) {4562 "use strict";4563 Object.defineProperty(exports, "__esModule", { value: true });4564 var def = {4565 keyword: "id",4566 code() {4567 throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');4568 }4569 };4570 exports.default = def;4571 }4572});45734574// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js4575var require_ref = __commonJS({4576 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) {4577 "use strict";4578 Object.defineProperty(exports, "__esModule", { value: true });4579 exports.callRef = exports.getValidate = void 0;4580 var ref_error_1 = require_ref_error();4581 var code_1 = require_code2();4582 var codegen_1 = require_codegen();4583 var names_1 = require_names();4584 var compile_1 = require_compile();4585 var util_1 = require_util();4586 var def = {4587 keyword: "$ref",4588 schemaType: "string",4589 code(cxt) {4590 const { gen, schema: $ref, it } = cxt;4591 const { baseId, schemaEnv: env, validateName, opts, self } = it;4592 const { root } = env;4593 if (($ref === "#" || $ref === "#/") && baseId === root.baseId)4594 return callRootRef();4595 const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);4596 if (schOrEnv === void 0)4597 throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);4598 if (schOrEnv instanceof compile_1.SchemaEnv)4599 return callValidate(schOrEnv);4600 return inlineRefSchema(schOrEnv);4601 function callRootRef() {4602 if (env === root)4603 return callRef(cxt, validateName, env, env.$async);4604 const rootName = gen.scopeValue("root", { ref: root });4605 return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);4606 }4607 function callValidate(sch) {4608 const v = getValidate(cxt, sch);4609 callRef(cxt, v, sch, sch.$async);4610 }4611 function inlineRefSchema(sch) {4612 const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });4613 const valid = gen.name("valid");4614 const schCxt = cxt.subschema({4615 schema: sch,4616 dataTypes: [],4617 schemaPath: codegen_1.nil,4618 topSchemaRef: schName,4619 errSchemaPath: $ref4620 }, valid);4621 cxt.mergeEvaluated(schCxt);4622 cxt.ok(valid);4623 }4624 }4625 };4626 function getValidate(cxt, sch) {4627 const { gen } = cxt;4628 return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;4629 }4630 exports.getValidate = getValidate;4631 function callRef(cxt, v, sch, $async) {4632 const { gen, it } = cxt;4633 const { allErrors, schemaEnv: env, opts } = it;4634 const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;4635 if ($async)4636 callAsyncRef();4637 else4638 callSyncRef();4639 function callAsyncRef() {4640 if (!env.$async)4641 throw new Error("async schema referenced by sync schema");4642 const valid = gen.let("valid");4643 gen.try(() => {4644 gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);4645 addEvaluatedFrom(v);4646 if (!allErrors)4647 gen.assign(valid, true);4648 }, (e) => {4649 gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));4650 addErrorsFrom(e);4651 if (!allErrors)4652 gen.assign(valid, false);4653 });4654 cxt.ok(valid);4655 }4656 function callSyncRef() {4657 cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));4658 }4659 function addErrorsFrom(source) {4660 const errs = (0, codegen_1._)`${source}.errors`;4661 gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);4662 gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);4663 }4664 function addEvaluatedFrom(source) {4665 var _a;4666 if (!it.opts.unevaluated)4667 return;4668 const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;4669 if (it.props !== true) {4670 if (schEvaluated && !schEvaluated.dynamicProps) {4671 if (schEvaluated.props !== void 0) {4672 it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);4673 }4674 } else {4675 const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);4676 it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);4677 }4678 }4679 if (it.items !== true) {4680 if (schEvaluated && !schEvaluated.dynamicItems) {4681 if (schEvaluated.items !== void 0) {4682 it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);4683 }4684 } else {4685 const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);4686 it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);4687 }4688 }4689 }4690 }4691 exports.callRef = callRef;4692 exports.default = def;4693 }4694});46954696// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js4697var require_core2 = __commonJS({4698 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports) {4699 "use strict";4700 Object.defineProperty(exports, "__esModule", { value: true });4701 var id_1 = require_id();4702 var ref_1 = require_ref();4703 var core = [4704 "$schema",4705 "$id",4706 "$defs",4707 "$vocabulary",4708 { keyword: "$comment" },4709 "definitions",4710 id_1.default,4711 ref_1.default4712 ];4713 exports.default = core;4714 }4715});47164717// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js4718var require_limitNumber = __commonJS({4719 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) {4720 "use strict";4721 Object.defineProperty(exports, "__esModule", { value: true });4722 var codegen_1 = require_codegen();4723 var ops = codegen_1.operators;4724 var KWDs = {4725 maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },4726 minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },4727 exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },4728 exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }4729 };4730 var error2 = {4731 message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,4732 params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`4733 };4734 var def = {4735 keyword: Object.keys(KWDs),4736 type: "number",4737 schemaType: "number",4738 $data: true,4739 error: error2,4740 code(cxt) {4741 const { keyword, data, schemaCode } = cxt;4742 cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);4743 }4744 };4745 exports.default = def;4746 }4747});47484749// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js4750var require_multipleOf = __commonJS({4751 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) {4752 "use strict";4753 Object.defineProperty(exports, "__esModule", { value: true });4754 var codegen_1 = require_codegen();4755 var error2 = {4756 message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,4757 params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`4758 };4759 var def = {4760 keyword: "multipleOf",4761 type: "number",4762 schemaType: "number",4763 $data: true,4764 error: error2,4765 code(cxt) {4766 const { gen, data, schemaCode, it } = cxt;4767 const prec = it.opts.multipleOfPrecision;4768 const res = gen.let("res");4769 const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;4770 cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);4771 }4772 };4773 exports.default = def;4774 }4775});47764777// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js4778var require_ucs2length = __commonJS({4779 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports) {4780 "use strict";4781 Object.defineProperty(exports, "__esModule", { value: true });4782 function ucs2length(str) {4783 const len = str.length;4784 let length = 0;4785 let pos = 0;4786 let value;4787 while (pos < len) {4788 length++;4789 value = str.charCodeAt(pos++);4790 if (value >= 55296 && value <= 56319 && pos < len) {4791 value = str.charCodeAt(pos);4792 if ((value & 64512) === 56320)4793 pos++;4794 }4795 }4796 return length;4797 }4798 exports.default = ucs2length;4799 ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';4800 }4801});48024803// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js4804var require_limitLength = __commonJS({4805 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) {4806 "use strict";4807 Object.defineProperty(exports, "__esModule", { value: true });4808 var codegen_1 = require_codegen();4809 var util_1 = require_util();4810 var ucs2length_1 = require_ucs2length();4811 var error2 = {4812 message({ keyword, schemaCode }) {4813 const comp = keyword === "maxLength" ? "more" : "fewer";4814 return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;4815 },4816 params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`4817 };4818 var def = {4819 keyword: ["maxLength", "minLength"],4820 type: "string",4821 schemaType: "number",4822 $data: true,4823 error: error2,4824 code(cxt) {4825 const { keyword, data, schemaCode, it } = cxt;4826 const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;4827 const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;4828 cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);4829 }4830 };4831 exports.default = def;4832 }4833});48344835// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js4836var require_pattern = __commonJS({4837 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) {4838 "use strict";4839 Object.defineProperty(exports, "__esModule", { value: true });4840 var code_1 = require_code2();4841 var util_1 = require_util();4842 var codegen_1 = require_codegen();4843 var error2 = {4844 message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,4845 params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`4846 };4847 var def = {4848 keyword: "pattern",4849 type: "string",4850 schemaType: "string",4851 $data: true,4852 error: error2,4853 code(cxt) {4854 const { gen, data, $data, schema, schemaCode, it } = cxt;4855 const u = it.opts.unicodeRegExp ? "u" : "";4856 if ($data) {4857 const { regExp } = it.opts.code;4858 const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);4859 const valid = gen.let("valid");4860 gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));4861 cxt.fail$data((0, codegen_1._)`!${valid}`);4862 } else {4863 const regExp = (0, code_1.usePattern)(cxt, schema);4864 cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);4865 }4866 }4867 };4868 exports.default = def;4869 }4870});48714872// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js4873var require_limitProperties = __commonJS({4874 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) {4875 "use strict";4876 Object.defineProperty(exports, "__esModule", { value: true });4877 var codegen_1 = require_codegen();4878 var error2 = {4879 message({ keyword, schemaCode }) {4880 const comp = keyword === "maxProperties" ? "more" : "fewer";4881 return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;4882 },4883 params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`4884 };4885 var def = {4886 keyword: ["maxProperties", "minProperties"],4887 type: "object",4888 schemaType: "number",4889 $data: true,4890 error: error2,4891 code(cxt) {4892 const { keyword, data, schemaCode } = cxt;4893 const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;4894 cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);4895 }4896 };4897 exports.default = def;4898 }4899});49004901// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js4902var require_required = __commonJS({4903 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) {4904 "use strict";4905 Object.defineProperty(exports, "__esModule", { value: true });4906 var code_1 = require_code2();4907 var codegen_1 = require_codegen();4908 var util_1 = require_util();4909 var error2 = {4910 message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,4911 params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`4912 };4913 var def = {4914 keyword: "required",4915 type: "object",4916 schemaType: "array",4917 $data: true,4918 error: error2,4919 code(cxt) {4920 const { gen, schema, schemaCode, data, $data, it } = cxt;4921 const { opts } = it;4922 if (!$data && schema.length === 0)4923 return;4924 const useLoop = schema.length >= opts.loopRequired;4925 if (it.allErrors)4926 allErrorsMode();4927 else4928 exitOnErrorMode();4929 if (opts.strictRequired) {4930 const props = cxt.parentSchema.properties;4931 const { definedProperties } = cxt.it;4932 for (const requiredKey of schema) {4933 if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {4934 const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;4935 const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;4936 (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);4937 }4938 }4939 }4940 function allErrorsMode() {4941 if (useLoop || $data) {4942 cxt.block$data(codegen_1.nil, loopAllRequired);4943 } else {4944 for (const prop of schema) {4945 (0, code_1.checkReportMissingProp)(cxt, prop);4946 }4947 }4948 }4949 function exitOnErrorMode() {4950 const missing = gen.let("missing");4951 if (useLoop || $data) {4952 const valid = gen.let("valid", true);4953 cxt.block$data(valid, () => loopUntilMissing(missing, valid));4954 cxt.ok(valid);4955 } else {4956 gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));4957 (0, code_1.reportMissingProp)(cxt, missing);4958 gen.else();4959 }4960 }4961 function loopAllRequired() {4962 gen.forOf("prop", schemaCode, (prop) => {4963 cxt.setParams({ missingProperty: prop });4964 gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());4965 });4966 }4967 function loopUntilMissing(missing, valid) {4968 cxt.setParams({ missingProperty: missing });4969 gen.forOf(missing, schemaCode, () => {4970 gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));4971 gen.if((0, codegen_1.not)(valid), () => {4972 cxt.error();4973 gen.break();4974 });4975 }, codegen_1.nil);4976 }4977 }4978 };4979 exports.default = def;4980 }4981});49824983// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js4984var require_limitItems = __commonJS({4985 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) {4986 "use strict";4987 Object.defineProperty(exports, "__esModule", { value: true });4988 var codegen_1 = require_codegen();4989 var error2 = {4990 message({ keyword, schemaCode }) {4991 const comp = keyword === "maxItems" ? "more" : "fewer";4992 return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;4993 },4994 params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`4995 };4996 var def = {4997 keyword: ["maxItems", "minItems"],4998 type: "array",4999 schemaType: "number",5000 $data: true,5001 error: error2,5002 code(cxt) {5003 const { keyword, data, schemaCode } = cxt;5004 const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;5005 cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);5006 }5007 };5008 exports.default = def;5009 }5010});50115012// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js5013var require_equal = __commonJS({5014 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js"(exports) {5015 "use strict";5016 Object.defineProperty(exports, "__esModule", { value: true });5017 var equal = require_fast_deep_equal();5018 equal.code = 'require("ajv/dist/runtime/equal").default';5019 exports.default = equal;5020 }5021});50225023// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js5024var require_uniqueItems = __commonJS({5025 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) {5026 "use strict";5027 Object.defineProperty(exports, "__esModule", { value: true });5028 var dataType_1 = require_dataType();5029 var codegen_1 = require_codegen();5030 var util_1 = require_util();5031 var equal_1 = require_equal();5032 var error2 = {5033 message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,5034 params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`5035 };5036 var def = {5037 keyword: "uniqueItems",5038 type: "array",5039 schemaType: "boolean",5040 $data: true,5041 error: error2,5042 code(cxt) {5043 const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;5044 if (!$data && !schema)5045 return;5046 const valid = gen.let("valid");5047 const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];5048 cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);5049 cxt.ok(valid);5050 function validateUniqueItems() {5051 const i = gen.let("i", (0, codegen_1._)`${data}.length`);5052 const j = gen.let("j");5053 cxt.setParams({ i, j });5054 gen.assign(valid, true);5055 gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));5056 }5057 function canOptimize() {5058 return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");5059 }5060 function loopN(i, j) {5061 const item = gen.name("item");5062 const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);5063 const indices = gen.const("indices", (0, codegen_1._)`{}`);5064 gen.for((0, codegen_1._)`;${i}--;`, () => {5065 gen.let(item, (0, codegen_1._)`${data}[${i}]`);5066 gen.if(wrongType, (0, codegen_1._)`continue`);5067 if (itemTypes.length > 1)5068 gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);5069 gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {5070 gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);5071 cxt.error();5072 gen.assign(valid, false).break();5073 }).code((0, codegen_1._)`${indices}[${item}] = ${i}`);5074 });5075 }5076 function loopN2(i, j) {5077 const eql = (0, util_1.useFunc)(gen, equal_1.default);5078 const outer = gen.name("outer");5079 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}])`, () => {5080 cxt.error();5081 gen.assign(valid, false).break(outer);5082 })));5083 }5084 }5085 };5086 exports.default = def;5087 }5088});50895090// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js5091var require_const = __commonJS({5092 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) {5093 "use strict";5094 Object.defineProperty(exports, "__esModule", { value: true });5095 var codegen_1 = require_codegen();5096 var util_1 = require_util();5097 var equal_1 = require_equal();5098 var error2 = {5099 message: "must be equal to constant",5100 params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`5101 };5102 var def = {5103 keyword: "const",5104 $data: true,5105 error: error2,5106 code(cxt) {5107 const { gen, data, $data, schemaCode, schema } = cxt;5108 if ($data || schema && typeof schema == "object") {5109 cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);5110 } else {5111 cxt.fail((0, codegen_1._)`${schema} !== ${data}`);5112 }5113 }5114 };5115 exports.default = def;5116 }5117});51185119// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js5120var require_enum = __commonJS({5121 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) {5122 "use strict";5123 Object.defineProperty(exports, "__esModule", { value: true });5124 var codegen_1 = require_codegen();5125 var util_1 = require_util();5126 var equal_1 = require_equal();5127 var error2 = {5128 message: "must be equal to one of the allowed values",5129 params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`5130 };5131 var def = {5132 keyword: "enum",5133 schemaType: "array",5134 $data: true,5135 error: error2,5136 code(cxt) {5137 const { gen, data, $data, schema, schemaCode, it } = cxt;5138 if (!$data && schema.length === 0)5139 throw new Error("enum must have non-empty array");5140 const useLoop = schema.length >= it.opts.loopEnum;5141 let eql;5142 const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);5143 let valid;5144 if (useLoop || $data) {5145 valid = gen.let("valid");5146 cxt.block$data(valid, loopEnum);5147 } else {5148 if (!Array.isArray(schema))5149 throw new Error("ajv implementation error");5150 const vSchema = gen.const("vSchema", schemaCode);5151 valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));5152 }5153 cxt.pass(valid);5154 function loopEnum() {5155 gen.assign(valid, false);5156 gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));5157 }5158 function equalCode(vSchema, i) {5159 const sch = schema[i];5160 return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;5161 }5162 }5163 };5164 exports.default = def;5165 }5166});51675168// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js5169var require_validation = __commonJS({5170 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) {5171 "use strict";5172 Object.defineProperty(exports, "__esModule", { value: true });5173 var limitNumber_1 = require_limitNumber();5174 var multipleOf_1 = require_multipleOf();5175 var limitLength_1 = require_limitLength();5176 var pattern_1 = require_pattern();5177 var limitProperties_1 = require_limitProperties();5178 var required_1 = require_required();5179 var limitItems_1 = require_limitItems();5180 var uniqueItems_1 = require_uniqueItems();5181 var const_1 = require_const();5182 var enum_1 = require_enum();5183 var validation = [5184 // number5185 limitNumber_1.default,5186 multipleOf_1.default,5187 // string5188 limitLength_1.default,5189 pattern_1.default,5190 // object5191 limitProperties_1.default,5192 required_1.default,5193 // array5194 limitItems_1.default,5195 uniqueItems_1.default,5196 // any5197 { keyword: "type", schemaType: ["string", "array"] },5198 { keyword: "nullable", schemaType: "boolean" },5199 const_1.default,5200 enum_1.default5201 ];5202 exports.default = validation;5203 }5204});52055206// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js5207var require_additionalItems = __commonJS({5208 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) {5209 "use strict";5210 Object.defineProperty(exports, "__esModule", { value: true });5211 exports.validateAdditionalItems = void 0;5212 var codegen_1 = require_codegen();5213 var util_1 = require_util();5214 var error2 = {5215 message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,5216 params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`5217 };5218 var def = {5219 keyword: "additionalItems",5220 type: "array",5221 schemaType: ["boolean", "object"],5222 before: "uniqueItems",5223 error: error2,5224 code(cxt) {5225 const { parentSchema, it } = cxt;5226 const { items } = parentSchema;5227 if (!Array.isArray(items)) {5228 (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');5229 return;5230 }5231 validateAdditionalItems(cxt, items);5232 }5233 };5234 function validateAdditionalItems(cxt, items) {5235 const { gen, schema, data, keyword, it } = cxt;5236 it.items = true;5237 const len = gen.const("len", (0, codegen_1._)`${data}.length`);5238 if (schema === false) {5239 cxt.setParams({ len: items.length });5240 cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);5241 } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {5242 const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);5243 gen.if((0, codegen_1.not)(valid), () => validateItems(valid));5244 cxt.ok(valid);5245 }5246 function validateItems(valid) {5247 gen.forRange("i", items.length, len, (i) => {5248 cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);5249 if (!it.allErrors)5250 gen.if((0, codegen_1.not)(valid), () => gen.break());5251 });5252 }5253 }5254 exports.validateAdditionalItems = validateAdditionalItems;5255 exports.default = def;5256 }5257});52585259// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js5260var require_items = __commonJS({5261 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) {5262 "use strict";5263 Object.defineProperty(exports, "__esModule", { value: true });5264 exports.validateTuple = void 0;5265 var codegen_1 = require_codegen();5266 var util_1 = require_util();5267 var code_1 = require_code2();5268 var def = {5269 keyword: "items",5270 type: "array",5271 schemaType: ["object", "array", "boolean"],5272 before: "uniqueItems",5273 code(cxt) {5274 const { schema, it } = cxt;5275 if (Array.isArray(schema))5276 return validateTuple(cxt, "additionalItems", schema);5277 it.items = true;5278 if ((0, util_1.alwaysValidSchema)(it, schema))5279 return;5280 cxt.ok((0, code_1.validateArray)(cxt));5281 }5282 };5283 function validateTuple(cxt, extraItems, schArr = cxt.schema) {5284 const { gen, parentSchema, data, keyword, it } = cxt;5285 checkStrictTuple(parentSchema);5286 if (it.opts.unevaluated && schArr.length && it.items !== true) {5287 it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);5288 }5289 const valid = gen.name("valid");5290 const len = gen.const("len", (0, codegen_1._)`${data}.length`);5291 schArr.forEach((sch, i) => {5292 if ((0, util_1.alwaysValidSchema)(it, sch))5293 return;5294 gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({5295 keyword,5296 schemaProp: i,5297 dataProp: i5298 }, valid));5299 cxt.ok(valid);5300 });5301 function checkStrictTuple(sch) {5302 const { opts, errSchemaPath } = it;5303 const l = schArr.length;5304 const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);5305 if (opts.strictTuples && !fullTuple) {5306 const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;5307 (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);5308 }5309 }5310 }5311 exports.validateTuple = validateTuple;5312 exports.default = def;5313 }5314});53155316// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js5317var require_prefixItems = __commonJS({5318 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) {5319 "use strict";5320 Object.defineProperty(exports, "__esModule", { value: true });5321 var items_1 = require_items();5322 var def = {5323 keyword: "prefixItems",5324 type: "array",5325 schemaType: ["array"],5326 before: "uniqueItems",5327 code: (cxt) => (0, items_1.validateTuple)(cxt, "items")5328 };5329 exports.default = def;5330 }5331});53325333// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js5334var require_items2020 = __commonJS({5335 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) {5336 "use strict";5337 Object.defineProperty(exports, "__esModule", { value: true });5338 var codegen_1 = require_codegen();5339 var util_1 = require_util();5340 var code_1 = require_code2();5341 var additionalItems_1 = require_additionalItems();5342 var error2 = {5343 message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,5344 params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`5345 };5346 var def = {5347 keyword: "items",5348 type: "array",5349 schemaType: ["object", "boolean"],5350 before: "uniqueItems",5351 error: error2,5352 code(cxt) {5353 const { schema, parentSchema, it } = cxt;5354 const { prefixItems } = parentSchema;5355 it.items = true;5356 if ((0, util_1.alwaysValidSchema)(it, schema))5357 return;5358 if (prefixItems)5359 (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);5360 else5361 cxt.ok((0, code_1.validateArray)(cxt));5362 }5363 };5364 exports.default = def;5365 }5366});53675368// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js5369var require_contains = __commonJS({5370 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) {5371 "use strict";5372 Object.defineProperty(exports, "__esModule", { value: true });5373 var codegen_1 = require_codegen();5374 var util_1 = require_util();5375 var error2 = {5376 message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,5377 params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`5378 };5379 var def = {5380 keyword: "contains",5381 type: "array",5382 schemaType: ["object", "boolean"],5383 before: "uniqueItems",5384 trackErrors: true,5385 error: error2,5386 code(cxt) {5387 const { gen, schema, parentSchema, data, it } = cxt;5388 let min;5389 let max;5390 const { minContains, maxContains } = parentSchema;5391 if (it.opts.next) {5392 min = minContains === void 0 ? 1 : minContains;5393 max = maxContains;5394 } else {5395 min = 1;5396 }5397 const len = gen.const("len", (0, codegen_1._)`${data}.length`);5398 cxt.setParams({ min, max });5399 if (max === void 0 && min === 0) {5400 (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);5401 return;5402 }5403 if (max !== void 0 && min > max) {5404 (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);5405 cxt.fail();5406 return;5407 }5408 if ((0, util_1.alwaysValidSchema)(it, schema)) {5409 let cond = (0, codegen_1._)`${len} >= ${min}`;5410 if (max !== void 0)5411 cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;5412 cxt.pass(cond);5413 return;5414 }5415 it.items = true;5416 const valid = gen.name("valid");5417 if (max === void 0 && min === 1) {5418 validateItems(valid, () => gen.if(valid, () => gen.break()));5419 } else if (min === 0) {5420 gen.let(valid, true);5421 if (max !== void 0)5422 gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);5423 } else {5424 gen.let(valid, false);5425 validateItemsWithCount();5426 }5427 cxt.result(valid, () => cxt.reset());5428 function validateItemsWithCount() {5429 const schValid = gen.name("_valid");5430 const count = gen.let("count", 0);5431 validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));5432 }5433 function validateItems(_valid, block) {5434 gen.forRange("i", 0, len, (i) => {5435 cxt.subschema({5436 keyword: "contains",5437 dataProp: i,5438 dataPropType: util_1.Type.Num,5439 compositeRule: true5440 }, _valid);5441 block();5442 });5443 }5444 function checkLimits(count) {5445 gen.code((0, codegen_1._)`${count}++`);5446 if (max === void 0) {5447 gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());5448 } else {5449 gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());5450 if (min === 1)5451 gen.assign(valid, true);5452 else5453 gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));5454 }5455 }5456 }5457 };5458 exports.default = def;5459 }5460});54615462// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js5463var require_dependencies = __commonJS({5464 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) {5465 "use strict";5466 Object.defineProperty(exports, "__esModule", { value: true });5467 exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;5468 var codegen_1 = require_codegen();5469 var util_1 = require_util();5470 var code_1 = require_code2();5471 exports.error = {5472 message: ({ params: { property, depsCount, deps } }) => {5473 const property_ies = depsCount === 1 ? "property" : "properties";5474 return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;5475 },5476 params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},5477 missingProperty: ${missingProperty},5478 depsCount: ${depsCount},5479 deps: ${deps}}`5480 // TODO change to reference5481 };5482 var def = {5483 keyword: "dependencies",5484 type: "object",5485 schemaType: "object",5486 error: exports.error,5487 code(cxt) {5488 const [propDeps, schDeps] = splitDependencies(cxt);5489 validatePropertyDeps(cxt, propDeps);5490 validateSchemaDeps(cxt, schDeps);5491 }5492 };5493 function splitDependencies({ schema }) {5494 const propertyDeps = {};5495 const schemaDeps = {};5496 for (const key in schema) {5497 if (key === "__proto__")5498 continue;5499 const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;5500 deps[key] = schema[key];5501 }5502 return [propertyDeps, schemaDeps];5503 }5504 function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {5505 const { gen, data, it } = cxt;5506 if (Object.keys(propertyDeps).length === 0)5507 return;5508 const missing = gen.let("missing");5509 for (const prop in propertyDeps) {5510 const deps = propertyDeps[prop];5511 if (deps.length === 0)5512 continue;5513 const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);5514 cxt.setParams({5515 property: prop,5516 depsCount: deps.length,5517 deps: deps.join(", ")5518 });5519 if (it.allErrors) {5520 gen.if(hasProperty, () => {5521 for (const depProp of deps) {5522 (0, code_1.checkReportMissingProp)(cxt, depProp);5523 }5524 });5525 } else {5526 gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);5527 (0, code_1.reportMissingProp)(cxt, missing);5528 gen.else();5529 }5530 }5531 }5532 exports.validatePropertyDeps = validatePropertyDeps;5533 function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {5534 const { gen, data, keyword, it } = cxt;5535 const valid = gen.name("valid");5536 for (const prop in schemaDeps) {5537 if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))5538 continue;5539 gen.if(5540 (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),5541 () => {5542 const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);5543 cxt.mergeValidEvaluated(schCxt, valid);5544 },5545 () => gen.var(valid, true)5546 // TODO var5547 );5548 cxt.ok(valid);5549 }5550 }5551 exports.validateSchemaDeps = validateSchemaDeps;5552 exports.default = def;5553 }5554});55555556// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js5557var require_propertyNames = __commonJS({5558 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) {5559 "use strict";5560 Object.defineProperty(exports, "__esModule", { value: true });5561 var codegen_1 = require_codegen();5562 var util_1 = require_util();5563 var error2 = {5564 message: "property name must be valid",5565 params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`5566 };5567 var def = {5568 keyword: "propertyNames",5569 type: "object",5570 schemaType: ["object", "boolean"],5571 error: error2,5572 code(cxt) {5573 const { gen, schema, data, it } = cxt;5574 if ((0, util_1.alwaysValidSchema)(it, schema))5575 return;5576 const valid = gen.name("valid");5577 gen.forIn("key", data, (key) => {5578 cxt.setParams({ propertyName: key });5579 cxt.subschema({5580 keyword: "propertyNames",5581 data: key,5582 dataTypes: ["string"],5583 propertyName: key,5584 compositeRule: true5585 }, valid);5586 gen.if((0, codegen_1.not)(valid), () => {5587 cxt.error(true);5588 if (!it.allErrors)5589 gen.break();5590 });5591 });5592 cxt.ok(valid);5593 }5594 };5595 exports.default = def;5596 }5597});55985599// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js5600var require_additionalProperties = __commonJS({5601 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) {5602 "use strict";5603 Object.defineProperty(exports, "__esModule", { value: true });5604 var code_1 = require_code2();5605 var codegen_1 = require_codegen();5606 var names_1 = require_names();5607 var util_1 = require_util();5608 var error2 = {5609 message: "must NOT have additional properties",5610 params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`5611 };5612 var def = {5613 keyword: "additionalProperties",5614 type: ["object"],5615 schemaType: ["boolean", "object"],5616 allowUndefined: true,5617 trackErrors: true,5618 error: error2,5619 code(cxt) {5620 const { gen, schema, parentSchema, data, errsCount, it } = cxt;5621 if (!errsCount)5622 throw new Error("ajv implementation error");5623 const { allErrors, opts } = it;5624 it.props = true;5625 if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))5626 return;5627 const props = (0, code_1.allSchemaProperties)(parentSchema.properties);5628 const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);5629 checkAdditionalProperties();5630 cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);5631 function checkAdditionalProperties() {5632 gen.forIn("key", data, (key) => {5633 if (!props.length && !patProps.length)5634 additionalPropertyCode(key);5635 else5636 gen.if(isAdditional(key), () => additionalPropertyCode(key));5637 });5638 }5639 function isAdditional(key) {5640 let definedProp;5641 if (props.length > 8) {5642 const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");5643 definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);5644 } else if (props.length) {5645 definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));5646 } else {5647 definedProp = codegen_1.nil;5648 }5649 if (patProps.length) {5650 definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));5651 }5652 return (0, codegen_1.not)(definedProp);5653 }5654 function deleteAdditional(key) {5655 gen.code((0, codegen_1._)`delete ${data}[${key}]`);5656 }5657 function additionalPropertyCode(key) {5658 if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {5659 deleteAdditional(key);5660 return;5661 }5662 if (schema === false) {5663 cxt.setParams({ additionalProperty: key });5664 cxt.error();5665 if (!allErrors)5666 gen.break();5667 return;5668 }5669 if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {5670 const valid = gen.name("valid");5671 if (opts.removeAdditional === "failing") {5672 applyAdditionalSchema(key, valid, false);5673 gen.if((0, codegen_1.not)(valid), () => {5674 cxt.reset();5675 deleteAdditional(key);5676 });5677 } else {5678 applyAdditionalSchema(key, valid);5679 if (!allErrors)5680 gen.if((0, codegen_1.not)(valid), () => gen.break());5681 }5682 }5683 }5684 function applyAdditionalSchema(key, valid, errors) {5685 const subschema = {5686 keyword: "additionalProperties",5687 dataProp: key,5688 dataPropType: util_1.Type.Str5689 };5690 if (errors === false) {5691 Object.assign(subschema, {5692 compositeRule: true,5693 createErrors: false,5694 allErrors: false5695 });5696 }5697 cxt.subschema(subschema, valid);5698 }5699 }5700 };5701 exports.default = def;5702 }5703});57045705// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js5706var require_properties = __commonJS({5707 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) {5708 "use strict";5709 Object.defineProperty(exports, "__esModule", { value: true });5710 var validate_1 = require_validate();5711 var code_1 = require_code2();5712 var util_1 = require_util();5713 var additionalProperties_1 = require_additionalProperties();5714 var def = {5715 keyword: "properties",5716 type: "object",5717 schemaType: "object",5718 code(cxt) {5719 const { gen, schema, parentSchema, data, it } = cxt;5720 if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {5721 additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));5722 }5723 const allProps = (0, code_1.allSchemaProperties)(schema);5724 for (const prop of allProps) {5725 it.definedProperties.add(prop);5726 }5727 if (it.opts.unevaluated && allProps.length && it.props !== true) {5728 it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);5729 }5730 const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));5731 if (properties.length === 0)5732 return;5733 const valid = gen.name("valid");5734 for (const prop of properties) {5735 if (hasDefault(prop)) {5736 applyPropertySchema(prop);5737 } else {5738 gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));5739 applyPropertySchema(prop);5740 if (!it.allErrors)5741 gen.else().var(valid, true);5742 gen.endIf();5743 }5744 cxt.it.definedProperties.add(prop);5745 cxt.ok(valid);5746 }5747 function hasDefault(prop) {5748 return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;5749 }5750 function applyPropertySchema(prop) {5751 cxt.subschema({5752 keyword: "properties",5753 schemaProp: prop,5754 dataProp: prop5755 }, valid);5756 }5757 }5758 };5759 exports.default = def;5760 }5761});57625763// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js5764var require_patternProperties = __commonJS({5765 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) {5766 "use strict";5767 Object.defineProperty(exports, "__esModule", { value: true });5768 var code_1 = require_code2();5769 var codegen_1 = require_codegen();5770 var util_1 = require_util();5771 var util_2 = require_util();5772 var def = {5773 keyword: "patternProperties",5774 type: "object",5775 schemaType: "object",5776 code(cxt) {5777 const { gen, schema, data, parentSchema, it } = cxt;5778 const { opts } = it;5779 const patterns = (0, code_1.allSchemaProperties)(schema);5780 const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));5781 if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {5782 return;5783 }5784 const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;5785 const valid = gen.name("valid");5786 if (it.props !== true && !(it.props instanceof codegen_1.Name)) {5787 it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);5788 }5789 const { props } = it;5790 validatePatternProperties();5791 function validatePatternProperties() {5792 for (const pat of patterns) {5793 if (checkProperties)5794 checkMatchingProperties(pat);5795 if (it.allErrors) {5796 validateProperties(pat);5797 } else {5798 gen.var(valid, true);5799 validateProperties(pat);5800 gen.if(valid);5801 }5802 }5803 }5804 function checkMatchingProperties(pat) {5805 for (const prop in checkProperties) {5806 if (new RegExp(pat).test(prop)) {5807 (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);5808 }5809 }5810 }5811 function validateProperties(pat) {5812 gen.forIn("key", data, (key) => {5813 gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {5814 const alwaysValid = alwaysValidPatterns.includes(pat);5815 if (!alwaysValid) {5816 cxt.subschema({5817 keyword: "patternProperties",5818 schemaProp: pat,5819 dataProp: key,5820 dataPropType: util_2.Type.Str5821 }, valid);5822 }5823 if (it.opts.unevaluated && props !== true) {5824 gen.assign((0, codegen_1._)`${props}[${key}]`, true);5825 } else if (!alwaysValid && !it.allErrors) {5826 gen.if((0, codegen_1.not)(valid), () => gen.break());5827 }5828 });5829 });5830 }5831 }5832 };5833 exports.default = def;5834 }5835});58365837// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js5838var require_not = __commonJS({5839 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) {5840 "use strict";5841 Object.defineProperty(exports, "__esModule", { value: true });5842 var util_1 = require_util();5843 var def = {5844 keyword: "not",5845 schemaType: ["object", "boolean"],5846 trackErrors: true,5847 code(cxt) {5848 const { gen, schema, it } = cxt;5849 if ((0, util_1.alwaysValidSchema)(it, schema)) {5850 cxt.fail();5851 return;5852 }5853 const valid = gen.name("valid");5854 cxt.subschema({5855 keyword: "not",5856 compositeRule: true,5857 createErrors: false,5858 allErrors: false5859 }, valid);5860 cxt.failResult(valid, () => cxt.reset(), () => cxt.error());5861 },5862 error: { message: "must NOT be valid" }5863 };5864 exports.default = def;5865 }5866});58675868// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js5869var require_anyOf = __commonJS({5870 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) {5871 "use strict";5872 Object.defineProperty(exports, "__esModule", { value: true });5873 var code_1 = require_code2();5874 var def = {5875 keyword: "anyOf",5876 schemaType: "array",5877 trackErrors: true,5878 code: code_1.validateUnion,5879 error: { message: "must match a schema in anyOf" }5880 };5881 exports.default = def;5882 }5883});58845885// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js5886var require_oneOf = __commonJS({5887 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) {5888 "use strict";5889 Object.defineProperty(exports, "__esModule", { value: true });5890 var codegen_1 = require_codegen();5891 var util_1 = require_util();5892 var error2 = {5893 message: "must match exactly one schema in oneOf",5894 params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`5895 };5896 var def = {5897 keyword: "oneOf",5898 schemaType: "array",5899 trackErrors: true,5900 error: error2,5901 code(cxt) {5902 const { gen, schema, parentSchema, it } = cxt;5903 if (!Array.isArray(schema))5904 throw new Error("ajv implementation error");5905 if (it.opts.discriminator && parentSchema.discriminator)5906 return;5907 const schArr = schema;5908 const valid = gen.let("valid", false);5909 const passing = gen.let("passing", null);5910 const schValid = gen.name("_valid");5911 cxt.setParams({ passing });5912 gen.block(validateOneOf);5913 cxt.result(valid, () => cxt.reset(), () => cxt.error(true));5914 function validateOneOf() {5915 schArr.forEach((sch, i) => {5916 let schCxt;5917 if ((0, util_1.alwaysValidSchema)(it, sch)) {5918 gen.var(schValid, true);5919 } else {5920 schCxt = cxt.subschema({5921 keyword: "oneOf",5922 schemaProp: i,5923 compositeRule: true5924 }, schValid);5925 }5926 if (i > 0) {5927 gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();5928 }5929 gen.if(schValid, () => {5930 gen.assign(valid, true);5931 gen.assign(passing, i);5932 if (schCxt)5933 cxt.mergeEvaluated(schCxt, codegen_1.Name);5934 });5935 });5936 }5937 }5938 };5939 exports.default = def;5940 }5941});59425943// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js5944var require_allOf = __commonJS({5945 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) {5946 "use strict";5947 Object.defineProperty(exports, "__esModule", { value: true });5948 var util_1 = require_util();5949 var def = {5950 keyword: "allOf",5951 schemaType: "array",5952 code(cxt) {5953 const { gen, schema, it } = cxt;5954 if (!Array.isArray(schema))5955 throw new Error("ajv implementation error");5956 const valid = gen.name("valid");5957 schema.forEach((sch, i) => {5958 if ((0, util_1.alwaysValidSchema)(it, sch))5959 return;5960 const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);5961 cxt.ok(valid);5962 cxt.mergeEvaluated(schCxt);5963 });5964 }5965 };5966 exports.default = def;5967 }5968});59695970// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js5971var require_if = __commonJS({5972 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) {5973 "use strict";5974 Object.defineProperty(exports, "__esModule", { value: true });5975 var codegen_1 = require_codegen();5976 var util_1 = require_util();5977 var error2 = {5978 message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,5979 params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`5980 };5981 var def = {5982 keyword: "if",5983 schemaType: ["object", "boolean"],5984 trackErrors: true,5985 error: error2,5986 code(cxt) {5987 const { gen, parentSchema, it } = cxt;5988 if (parentSchema.then === void 0 && parentSchema.else === void 0) {5989 (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');5990 }5991 const hasThen = hasSchema(it, "then");5992 const hasElse = hasSchema(it, "else");5993 if (!hasThen && !hasElse)5994 return;5995 const valid = gen.let("valid", true);5996 const schValid = gen.name("_valid");5997 validateIf();5998 cxt.reset();5999 if (hasThen && hasElse) {6000 const ifClause = gen.let("ifClause");6001 cxt.setParams({ ifClause });6002 gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));6003 } else if (hasThen) {6004 gen.if(schValid, validateClause("then"));6005 } else {6006 gen.if((0, codegen_1.not)(schValid), validateClause("else"));6007 }6008 cxt.pass(valid, () => cxt.error(true));6009 function validateIf() {6010 const schCxt = cxt.subschema({6011 keyword: "if",6012 compositeRule: true,6013 createErrors: false,6014 allErrors: false6015 }, schValid);6016 cxt.mergeEvaluated(schCxt);6017 }6018 function validateClause(keyword, ifClause) {6019 return () => {6020 const schCxt = cxt.subschema({ keyword }, schValid);6021 gen.assign(valid, schValid);6022 cxt.mergeValidEvaluated(schCxt, valid);6023 if (ifClause)6024 gen.assign(ifClause, (0, codegen_1._)`${keyword}`);6025 else6026 cxt.setParams({ ifClause: keyword });6027 };6028 }6029 }6030 };6031 function hasSchema(it, keyword) {6032 const schema = it.schema[keyword];6033 return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);6034 }6035 exports.default = def;6036 }6037});60386039// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js6040var require_thenElse = __commonJS({6041 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) {6042 "use strict";6043 Object.defineProperty(exports, "__esModule", { value: true });6044 var util_1 = require_util();6045 var def = {6046 keyword: ["then", "else"],6047 schemaType: ["object", "boolean"],6048 code({ keyword, parentSchema, it }) {6049 if (parentSchema.if === void 0)6050 (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);6051 }6052 };6053 exports.default = def;6054 }6055});60566057// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js6058var require_applicator = __commonJS({6059 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) {6060 "use strict";6061 Object.defineProperty(exports, "__esModule", { value: true });6062 var additionalItems_1 = require_additionalItems();6063 var prefixItems_1 = require_prefixItems();6064 var items_1 = require_items();6065 var items2020_1 = require_items2020();6066 var contains_1 = require_contains();6067 var dependencies_1 = require_dependencies();6068 var propertyNames_1 = require_propertyNames();6069 var additionalProperties_1 = require_additionalProperties();6070 var properties_1 = require_properties();6071 var patternProperties_1 = require_patternProperties();6072 var not_1 = require_not();6073 var anyOf_1 = require_anyOf();6074 var oneOf_1 = require_oneOf();6075 var allOf_1 = require_allOf();6076 var if_1 = require_if();6077 var thenElse_1 = require_thenElse();6078 function getApplicator(draft2020 = false) {6079 const applicator = [6080 // any6081 not_1.default,6082 anyOf_1.default,6083 oneOf_1.default,6084 allOf_1.default,6085 if_1.default,6086 thenElse_1.default,6087 // object6088 propertyNames_1.default,6089 additionalProperties_1.default,6090 dependencies_1.default,6091 properties_1.default,6092 patternProperties_1.default6093 ];6094 if (draft2020)6095 applicator.push(prefixItems_1.default, items2020_1.default);6096 else6097 applicator.push(additionalItems_1.default, items_1.default);6098 applicator.push(contains_1.default);6099 return applicator;6100 }6101 exports.default = getApplicator;6102 }6103});61046105// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js6106var require_format = __commonJS({6107 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports) {6108 "use strict";6109 Object.defineProperty(exports, "__esModule", { value: true });6110 var codegen_1 = require_codegen();6111 var error2 = {6112 message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,6113 params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`6114 };6115 var def = {6116 keyword: "format",6117 type: ["number", "string"],6118 schemaType: "string",6119 $data: true,6120 error: error2,6121 code(cxt, ruleType) {6122 const { gen, data, $data, schema, schemaCode, it } = cxt;6123 const { opts, errSchemaPath, schemaEnv, self } = it;6124 if (!opts.validateFormats)6125 return;6126 if ($data)6127 validate$DataFormat();6128 else6129 validateFormat();6130 function validate$DataFormat() {6131 const fmts = gen.scopeValue("formats", {6132 ref: self.formats,6133 code: opts.code.formats6134 });6135 const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);6136 const fType = gen.let("fType");6137 const format = gen.let("format");6138 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));6139 cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));6140 function unknownFmt() {6141 if (opts.strictSchema === false)6142 return codegen_1.nil;6143 return (0, codegen_1._)`${schemaCode} && !${format}`;6144 }6145 function invalidFmt() {6146 const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;6147 const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;6148 return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;6149 }6150 }6151 function validateFormat() {6152 const formatDef = self.formats[schema];6153 if (!formatDef) {6154 unknownFormat();6155 return;6156 }6157 if (formatDef === true)6158 return;6159 const [fmtType, format, fmtRef] = getFormat(formatDef);6160 if (fmtType === ruleType)6161 cxt.pass(validCondition());6162 function unknownFormat() {6163 if (opts.strictSchema === false) {6164 self.logger.warn(unknownMsg());6165 return;6166 }6167 throw new Error(unknownMsg());6168 function unknownMsg() {6169 return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;6170 }6171 }6172 function getFormat(fmtDef) {6173 const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;6174 const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });6175 if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {6176 return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];6177 }6178 return ["string", fmtDef, fmt];6179 }6180 function validCondition() {6181 if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {6182 if (!schemaEnv.$async)6183 throw new Error("async format in sync schema");6184 return (0, codegen_1._)`await ${fmtRef}(${data})`;6185 }6186 return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;6187 }6188 }6189 }6190 };6191 exports.default = def;6192 }6193});61946195// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js6196var require_format2 = __commonJS({6197 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports) {6198 "use strict";6199 Object.defineProperty(exports, "__esModule", { value: true });6200 var format_1 = require_format();6201 var format = [format_1.default];6202 exports.default = format;6203 }6204});62056206// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js6207var require_metadata = __commonJS({6208 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports) {6209 "use strict";6210 Object.defineProperty(exports, "__esModule", { value: true });6211 exports.contentVocabulary = exports.metadataVocabulary = void 0;6212 exports.metadataVocabulary = [6213 "title",6214 "description",6215 "default",6216 "deprecated",6217 "readOnly",6218 "writeOnly",6219 "examples"6220 ];6221 exports.contentVocabulary = [6222 "contentMediaType",6223 "contentEncoding",6224 "contentSchema"6225 ];6226 }6227});62286229// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js6230var require_draft7 = __commonJS({6231 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports) {6232 "use strict";6233 Object.defineProperty(exports, "__esModule", { value: true });6234 var core_1 = require_core2();6235 var validation_1 = require_validation();6236 var applicator_1 = require_applicator();6237 var format_1 = require_format2();6238 var metadata_1 = require_metadata();6239 var draft7Vocabularies = [6240 core_1.default,6241 validation_1.default,6242 (0, applicator_1.default)(),6243 format_1.default,6244 metadata_1.metadataVocabulary,6245 metadata_1.contentVocabulary6246 ];6247 exports.default = draft7Vocabularies;6248 }6249});62506251// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js6252var require_types = __commonJS({6253 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) {6254 "use strict";6255 Object.defineProperty(exports, "__esModule", { value: true });6256 exports.DiscrError = void 0;6257 var DiscrError;6258 (function(DiscrError2) {6259 DiscrError2["Tag"] = "tag";6260 DiscrError2["Mapping"] = "mapping";6261 })(DiscrError || (exports.DiscrError = DiscrError = {}));6262 }6263});62646265// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js6266var require_discriminator = __commonJS({6267 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) {6268 "use strict";6269 Object.defineProperty(exports, "__esModule", { value: true });6270 var codegen_1 = require_codegen();6271 var types_1 = require_types();6272 var compile_1 = require_compile();6273 var ref_error_1 = require_ref_error();6274 var util_1 = require_util();6275 var error2 = {6276 message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,6277 params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`6278 };6279 var def = {6280 keyword: "discriminator",6281 type: "object",6282 schemaType: "object",6283 error: error2,6284 code(cxt) {6285 const { gen, data, schema, parentSchema, it } = cxt;6286 const { oneOf } = parentSchema;6287 if (!it.opts.discriminator) {6288 throw new Error("discriminator: requires discriminator option");6289 }6290 const tagName = schema.propertyName;6291 if (typeof tagName != "string")6292 throw new Error("discriminator: requires propertyName");6293 if (schema.mapping)6294 throw new Error("discriminator: mapping is not supported");6295 if (!oneOf)6296 throw new Error("discriminator: requires oneOf keyword");6297 const valid = gen.let("valid", false);6298 const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);6299 gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));6300 cxt.ok(valid);6301 function validateMapping() {6302 const mapping = getMapping();6303 gen.if(false);6304 for (const tagValue in mapping) {6305 gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);6306 gen.assign(valid, applyTagSchema(mapping[tagValue]));6307 }6308 gen.else();6309 cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });6310 gen.endIf();6311 }6312 function applyTagSchema(schemaProp) {6313 const _valid = gen.name("valid");6314 const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);6315 cxt.mergeEvaluated(schCxt, codegen_1.Name);6316 return _valid;6317 }6318 function getMapping() {6319 var _a;6320 const oneOfMapping = {};6321 const topRequired = hasRequired(parentSchema);6322 let tagRequired = true;6323 for (let i = 0; i < oneOf.length; i++) {6324 let sch = oneOf[i];6325 if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {6326 const ref = sch.$ref;6327 sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);6328 if (sch instanceof compile_1.SchemaEnv)6329 sch = sch.schema;6330 if (sch === void 0)6331 throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);6332 }6333 const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];6334 if (typeof propSch != "object") {6335 throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);6336 }6337 tagRequired = tagRequired && (topRequired || hasRequired(sch));6338 addMappings(propSch, i);6339 }6340 if (!tagRequired)6341 throw new Error(`discriminator: "${tagName}" must be required`);6342 return oneOfMapping;6343 function hasRequired({ required: required2 }) {6344 return Array.isArray(required2) && required2.includes(tagName);6345 }6346 function addMappings(sch, i) {6347 if (sch.const) {6348 addMapping(sch.const, i);6349 } else if (sch.enum) {6350 for (const tagValue of sch.enum) {6351 addMapping(tagValue, i);6352 }6353 } else {6354 throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);6355 }6356 }6357 function addMapping(tagValue, i) {6358 if (typeof tagValue != "string" || tagValue in oneOfMapping) {6359 throw new Error(`discriminator: "${tagName}" values must be unique strings`);6360 }6361 oneOfMapping[tagValue] = i;6362 }6363 }6364 }6365 };6366 exports.default = def;6367 }6368});63696370// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json6371var require_json_schema_draft_07 = __commonJS({6372 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) {6373 module.exports = {6374 $schema: "http://json-schema.org/draft-07/schema#",6375 $id: "http://json-schema.org/draft-07/schema#",6376 title: "Core schema meta-schema",6377 definitions: {6378 schemaArray: {6379 type: "array",6380 minItems: 1,6381 items: { $ref: "#" }6382 },6383 nonNegativeInteger: {6384 type: "integer",6385 minimum: 06386 },6387 nonNegativeIntegerDefault0: {6388 allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }]6389 },6390 simpleTypes: {6391 enum: ["array", "boolean", "integer", "null", "number", "object", "string"]6392 },6393 stringArray: {6394 type: "array",6395 items: { type: "string" },6396 uniqueItems: true,6397 default: []6398 }6399 },6400 type: ["object", "boolean"],6401 properties: {6402 $id: {6403 type: "string",6404 format: "uri-reference"6405 },6406 $schema: {6407 type: "string",6408 format: "uri"6409 },6410 $ref: {6411 type: "string",6412 format: "uri-reference"6413 },6414 $comment: {6415 type: "string"6416 },6417 title: {6418 type: "string"6419 },6420 description: {6421 type: "string"6422 },6423 default: true,6424 readOnly: {6425 type: "boolean",6426 default: false6427 },6428 examples: {6429 type: "array",6430 items: true6431 },6432 multipleOf: {6433 type: "number",6434 exclusiveMinimum: 06435 },6436 maximum: {6437 type: "number"6438 },6439 exclusiveMaximum: {6440 type: "number"6441 },6442 minimum: {6443 type: "number"6444 },6445 exclusiveMinimum: {6446 type: "number"6447 },6448 maxLength: { $ref: "#/definitions/nonNegativeInteger" },6449 minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" },6450 pattern: {6451 type: "string",6452 format: "regex"6453 },6454 additionalItems: { $ref: "#" },6455 items: {6456 anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }],6457 default: true6458 },6459 maxItems: { $ref: "#/definitions/nonNegativeInteger" },6460 minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" },6461 uniqueItems: {6462 type: "boolean",6463 default: false6464 },6465 contains: { $ref: "#" },6466 maxProperties: { $ref: "#/definitions/nonNegativeInteger" },6467 minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" },6468 required: { $ref: "#/definitions/stringArray" },6469 additionalProperties: { $ref: "#" },6470 definitions: {6471 type: "object",6472 additionalProperties: { $ref: "#" },6473 default: {}6474 },6475 properties: {6476 type: "object",6477 additionalProperties: { $ref: "#" },6478 default: {}6479 },6480 patternProperties: {6481 type: "object",6482 additionalProperties: { $ref: "#" },6483 propertyNames: { format: "regex" },6484 default: {}6485 },6486 dependencies: {6487 type: "object",6488 additionalProperties: {6489 anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }]6490 }6491 },6492 propertyNames: { $ref: "#" },6493 const: true,6494 enum: {6495 type: "array",6496 items: true,6497 minItems: 1,6498 uniqueItems: true6499 },6500 type: {6501 anyOf: [6502 { $ref: "#/definitions/simpleTypes" },6503 {6504 type: "array",6505 items: { $ref: "#/definitions/simpleTypes" },6506 minItems: 1,6507 uniqueItems: true6508 }6509 ]6510 },6511 format: { type: "string" },6512 contentMediaType: { type: "string" },6513 contentEncoding: { type: "string" },6514 if: { $ref: "#" },6515 then: { $ref: "#" },6516 else: { $ref: "#" },6517 allOf: { $ref: "#/definitions/schemaArray" },6518 anyOf: { $ref: "#/definitions/schemaArray" },6519 oneOf: { $ref: "#/definitions/schemaArray" },6520 not: { $ref: "#" }6521 },6522 default: true6523 };6524 }6525});65266527// ../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js6528var require_ajv = __commonJS({6529 "../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js"(exports, module) {6530 "use strict";6531 Object.defineProperty(exports, "__esModule", { value: true });6532 exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;6533 var core_1 = require_core();6534 var draft7_1 = require_draft7();6535 var discriminator_1 = require_discriminator();6536 var draft7MetaSchema = require_json_schema_draft_07();6537 var META_SUPPORT_DATA = ["/properties"];6538 var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";6539 var Ajv2 = class extends core_1.default {6540 _addVocabularies() {6541 super._addVocabularies();6542 draft7_1.default.forEach((v) => this.addVocabulary(v));6543 if (this.opts.discriminator)6544 this.addKeyword(discriminator_1.default);6545 }6546 _addDefaultMetaSchema() {6547 super._addDefaultMetaSchema();6548 if (!this.opts.meta)6549 return;6550 const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;6551 this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);6552 this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;6553 }6554 defaultMeta() {6555 return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);6556 }6557 };6558 exports.Ajv = Ajv2;6559 module.exports = exports = Ajv2;6560 module.exports.Ajv = Ajv2;6561 Object.defineProperty(exports, "__esModule", { value: true });6562 exports.default = Ajv2;6563 var validate_1 = require_validate();6564 Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {6565 return validate_1.KeywordCxt;6566 } });6567 var codegen_1 = require_codegen();6568 Object.defineProperty(exports, "_", { enumerable: true, get: function() {6569 return codegen_1._;6570 } });6571 Object.defineProperty(exports, "str", { enumerable: true, get: function() {6572 return codegen_1.str;6573 } });6574 Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {6575 return codegen_1.stringify;6576 } });6577 Object.defineProperty(exports, "nil", { enumerable: true, get: function() {6578 return codegen_1.nil;6579 } });6580 Object.defineProperty(exports, "Name", { enumerable: true, get: function() {6581 return codegen_1.Name;6582 } });6583 Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {6584 return codegen_1.CodeGen;6585 } });6586 var validation_error_1 = require_validation_error();6587 Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {6588 return validation_error_1.default;6589 } });6590 var ref_error_1 = require_ref_error();6591 Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {6592 return ref_error_1.default;6593 } });6594 }6595});65966597// ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js6598var require_formats = __commonJS({6599 "../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js"(exports) {6600 "use strict";6601 Object.defineProperty(exports, "__esModule", { value: true });6602 exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;6603 function fmtDef(validate, compare) {6604 return { validate, compare };6605 }6606 exports.fullFormats = {6607 // date: http://tools.ietf.org/html/rfc3339#section-5.66608 date: fmtDef(date3, compareDate),6609 // date-time: http://tools.ietf.org/html/rfc3339#section-5.66610 time: fmtDef(getTime(true), compareTime),6611 "date-time": fmtDef(getDateTime(true), compareDateTime),6612 "iso-time": fmtDef(getTime(), compareIsoTime),6613 "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),6614 // duration: https://tools.ietf.org/html/rfc3339#appendix-A6615 duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,6616 uri,6617 "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,6618 // uri-template: https://tools.ietf.org/html/rfc65706619 "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,6620 // For the source: https://gist.github.com/dperini/7292946621 // For test cases: https://mathiasbynens.be/demo/url-regex6622 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,6623 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,6624 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,6625 // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html6626 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)$/,6627 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,6628 regex,6629 // uuid: http://tools.ietf.org/html/rfc41226630 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,6631 // JSON-pointer: https://tools.ietf.org/html/rfc69016632 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A6633 "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,6634 "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,6635 // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-006636 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,6637 // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types6638 // byte: https://github.com/miguelmota/is-base646639 byte,6640 // signed 32 bit integer6641 int32: { type: "number", validate: validateInt32 },6642 // signed 64 bit integer6643 int64: { type: "number", validate: validateInt64 },6644 // C-type float6645 float: { type: "number", validate: validateNumber },6646 // C-type double6647 double: { type: "number", validate: validateNumber },6648 // hint to the UI to hide input strings6649 password: true,6650 // unchecked string payload6651 binary: true6652 };6653 exports.fastFormats = {6654 ...exports.fullFormats,6655 date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),6656 time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),6657 "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),6658 "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),6659 "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),6660 // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js6661 uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,6662 "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,6663 // email (sources from jsen validator):6664 // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-88293636665 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')6666 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])?)*$/i6667 };6668 exports.formatNames = Object.keys(exports.fullFormats);6669 function isLeapYear(year) {6670 return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);6671 }6672 var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;6673 var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];6674 function date3(str) {6675 const matches = DATE.exec(str);6676 if (!matches)6677 return false;6678 const year = +matches[1];6679 const month = +matches[2];6680 const day = +matches[3];6681 return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);6682 }6683 function compareDate(d1, d2) {6684 if (!(d1 && d2))6685 return void 0;6686 if (d1 > d2)6687 return 1;6688 if (d1 < d2)6689 return -1;6690 return 0;6691 }6692 var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;6693 function getTime(strictTimeZone) {6694 return function time3(str) {6695 const matches = TIME.exec(str);6696 if (!matches)6697 return false;6698 const hr = +matches[1];6699 const min = +matches[2];6700 const sec = +matches[3];6701 const tz = matches[4];6702 const tzSign = matches[5] === "-" ? -1 : 1;6703 const tzH = +(matches[6] || 0);6704 const tzM = +(matches[7] || 0);6705 if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)6706 return false;6707 if (hr <= 23 && min <= 59 && sec < 60)6708 return true;6709 const utcMin = min - tzM * tzSign;6710 const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);6711 return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;6712 };6713 }6714 function compareTime(s1, s2) {6715 if (!(s1 && s2))6716 return void 0;6717 const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();6718 const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf();6719 if (!(t1 && t2))6720 return void 0;6721 return t1 - t2;6722 }6723 function compareIsoTime(t1, t2) {6724 if (!(t1 && t2))6725 return void 0;6726 const a1 = TIME.exec(t1);6727 const a2 = TIME.exec(t2);6728 if (!(a1 && a2))6729 return void 0;6730 t1 = a1[1] + a1[2] + a1[3];6731 t2 = a2[1] + a2[2] + a2[3];6732 if (t1 > t2)6733 return 1;6734 if (t1 < t2)6735 return -1;6736 return 0;6737 }6738 var DATE_TIME_SEPARATOR = /t|\s/i;6739 function getDateTime(strictTimeZone) {6740 const time3 = getTime(strictTimeZone);6741 return function date_time(str) {6742 const dateTime = str.split(DATE_TIME_SEPARATOR);6743 return dateTime.length === 2 && date3(dateTime[0]) && time3(dateTime[1]);6744 };6745 }6746 function compareDateTime(dt1, dt2) {6747 if (!(dt1 && dt2))6748 return void 0;6749 const d1 = new Date(dt1).valueOf();6750 const d2 = new Date(dt2).valueOf();6751 if (!(d1 && d2))6752 return void 0;6753 return d1 - d2;6754 }6755 function compareIsoDateTime(dt1, dt2) {6756 if (!(dt1 && dt2))6757 return void 0;6758 const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);6759 const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);6760 const res = compareDate(d1, d2);6761 if (res === void 0)6762 return void 0;6763 return res || compareTime(t1, t2);6764 }6765 var NOT_URI_FRAGMENT = /\/|:/;6766 var 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;6767 function uri(str) {6768 return NOT_URI_FRAGMENT.test(str) && URI.test(str);6769 }6770 var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;6771 function byte(str) {6772 BYTE.lastIndex = 0;6773 return BYTE.test(str);6774 }6775 var MIN_INT32 = -(2 ** 31);6776 var MAX_INT32 = 2 ** 31 - 1;6777 function validateInt32(value) {6778 return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;6779 }6780 function validateInt64(value) {6781 return Number.isInteger(value);6782 }6783 function validateNumber() {6784 return true;6785 }6786 var Z_ANCHOR = /[^\\]\\Z/;6787 function regex(str) {6788 if (Z_ANCHOR.test(str))6789 return false;6790 try {6791 new RegExp(str);6792 return true;6793 } catch (e) {6794 return false;6795 }6796 }6797 }6798});67996800// ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js6801var require_limit = __commonJS({6802 "../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js"(exports) {6803 "use strict";6804 Object.defineProperty(exports, "__esModule", { value: true });6805 exports.formatLimitDefinition = void 0;6806 var ajv_1 = require_ajv();6807 var codegen_1 = require_codegen();6808 var ops = codegen_1.operators;6809 var KWDs = {6810 formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },6811 formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },6812 formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },6813 formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }6814 };6815 var error2 = {6816 message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,6817 params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`6818 };6819 exports.formatLimitDefinition = {6820 keyword: Object.keys(KWDs),6821 type: "string",6822 schemaType: "string",6823 $data: true,6824 error: error2,6825 code(cxt) {6826 const { gen, data, schemaCode, keyword, it } = cxt;6827 const { opts, self } = it;6828 if (!opts.validateFormats)6829 return;6830 const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");6831 if (fCxt.$data)6832 validate$DataFormat();6833 else6834 validateFormat();6835 function validate$DataFormat() {6836 const fmts = gen.scopeValue("formats", {6837 ref: self.formats,6838 code: opts.code.formats6839 });6840 const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);6841 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)));6842 }6843 function validateFormat() {6844 const format = fCxt.schema;6845 const fmtDef = self.formats[format];6846 if (!fmtDef || fmtDef === true)6847 return;6848 if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {6849 throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);6850 }6851 const fmt = gen.scopeValue("formats", {6852 key: format,6853 ref: fmtDef,6854 code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 06855 });6856 cxt.fail$data(compareCode(fmt));6857 }6858 function compareCode(fmt) {6859 return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;6860 }6861 },6862 dependencies: ["format"]6863 };6864 var formatLimitPlugin = (ajv) => {6865 ajv.addKeyword(exports.formatLimitDefinition);6866 return ajv;6867 };6868 exports.default = formatLimitPlugin;6869 }6870});68716872// ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js6873var require_dist = __commonJS({6874 "../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js"(exports, module) {6875 "use strict";6876 Object.defineProperty(exports, "__esModule", { value: true });6877 var formats_1 = require_formats();6878 var limit_1 = require_limit();6879 var codegen_1 = require_codegen();6880 var fullName = new codegen_1.Name("fullFormats");6881 var fastName = new codegen_1.Name("fastFormats");6882 var formatsPlugin = (ajv, opts = { keywords: true }) => {6883 if (Array.isArray(opts)) {6884 addFormats(ajv, opts, formats_1.fullFormats, fullName);6885 return ajv;6886 }6887 const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];6888 const list = opts.formats || formats_1.formatNames;6889 addFormats(ajv, list, formats, exportName);6890 if (opts.keywords)6891 (0, limit_1.default)(ajv);6892 return ajv;6893 };6894 formatsPlugin.get = (name, mode = "full") => {6895 const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;6896 const f = formats[name];6897 if (!f)6898 throw new Error(`Unknown format "${name}"`);6899 return f;6900 };6901 function addFormats(ajv, list, fs, exportName) {6902 var _a;6903 var _b;6904 (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;6905 for (const f of list)6906 ajv.addFormat(f, fs[f]);6907 }6908 module.exports = exports = formatsPlugin;6909 Object.defineProperty(exports, "__esModule", { value: true });6910 exports.default = formatsPlugin;6911 }6912});69136914// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js6915var external_exports = {};6916__export(external_exports, {6917 BRAND: () => BRAND,6918 DIRTY: () => DIRTY,6919 EMPTY_PATH: () => EMPTY_PATH,6920 INVALID: () => INVALID,6921 NEVER: () => NEVER,6922 OK: () => OK,6923 ParseStatus: () => ParseStatus,6924 Schema: () => ZodType,6925 ZodAny: () => ZodAny,6926 ZodArray: () => ZodArray,6927 ZodBigInt: () => ZodBigInt,6928 ZodBoolean: () => ZodBoolean,6929 ZodBranded: () => ZodBranded,6930 ZodCatch: () => ZodCatch,6931 ZodDate: () => ZodDate,6932 ZodDefault: () => ZodDefault,6933 ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,6934 ZodEffects: () => ZodEffects,6935 ZodEnum: () => ZodEnum,6936 ZodError: () => ZodError,6937 ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,6938 ZodFunction: () => ZodFunction,6939 ZodIntersection: () => ZodIntersection,6940 ZodIssueCode: () => ZodIssueCode,6941 ZodLazy: () => ZodLazy,6942 ZodLiteral: () => ZodLiteral,6943 ZodMap: () => ZodMap,6944 ZodNaN: () => ZodNaN,6945 ZodNativeEnum: () => ZodNativeEnum,6946 ZodNever: () => ZodNever,6947 ZodNull: () => ZodNull,6948 ZodNullable: () => ZodNullable,6949 ZodNumber: () => ZodNumber,6950 ZodObject: () => ZodObject,6951 ZodOptional: () => ZodOptional,6952 ZodParsedType: () => ZodParsedType,6953 ZodPipeline: () => ZodPipeline,6954 ZodPromise: () => ZodPromise,6955 ZodReadonly: () => ZodReadonly,6956 ZodRecord: () => ZodRecord,6957 ZodSchema: () => ZodType,6958 ZodSet: () => ZodSet,6959 ZodString: () => ZodString,6960 ZodSymbol: () => ZodSymbol,6961 ZodTransformer: () => ZodEffects,6962 ZodTuple: () => ZodTuple,6963 ZodType: () => ZodType,6964 ZodUndefined: () => ZodUndefined,6965 ZodUnion: () => ZodUnion,6966 ZodUnknown: () => ZodUnknown,6967 ZodVoid: () => ZodVoid,6968 addIssueToContext: () => addIssueToContext,6969 any: () => anyType,6970 array: () => arrayType,6971 bigint: () => bigIntType,6972 boolean: () => booleanType,6973 coerce: () => coerce,6974 custom: () => custom,6975 date: () => dateType,6976 datetimeRegex: () => datetimeRegex,6977 defaultErrorMap: () => en_default,6978 discriminatedUnion: () => discriminatedUnionType,6979 effect: () => effectsType,6980 enum: () => enumType,6981 function: () => functionType,6982 getErrorMap: () => getErrorMap,6983 getParsedType: () => getParsedType,6984 instanceof: () => instanceOfType,6985 intersection: () => intersectionType,6986 isAborted: () => isAborted,6987 isAsync: () => isAsync,6988 isDirty: () => isDirty,6989 isValid: () => isValid,6990 late: () => late,6991 lazy: () => lazyType,6992 literal: () => literalType,6993 makeIssue: () => makeIssue,6994 map: () => mapType,6995 nan: () => nanType,6996 nativeEnum: () => nativeEnumType,6997 never: () => neverType,6998 null: () => nullType,6999 nullable: () => nullableType,7000 number: () => numberType,7001 object: () => objectType,7002 objectUtil: () => objectUtil,7003 oboolean: () => oboolean,7004 onumber: () => onumber,7005 optional: () => optionalType,7006 ostring: () => ostring,7007 pipeline: () => pipelineType,7008 preprocess: () => preprocessType,7009 promise: () => promiseType,7010 quotelessJson: () => quotelessJson,7011 record: () => recordType,7012 set: () => setType,7013 setErrorMap: () => setErrorMap,7014 strictObject: () => strictObjectType,7015 string: () => stringType,7016 symbol: () => symbolType,7017 transformer: () => effectsType,7018 tuple: () => tupleType,7019 undefined: () => undefinedType,7020 union: () => unionType,7021 unknown: () => unknownType,7022 util: () => util,7023 void: () => voidType7024});70257026// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js7027var util;7028(function(util2) {7029 util2.assertEqual = (_) => {7030 };7031 function assertIs2(_arg) {7032 }7033 util2.assertIs = assertIs2;7034 function assertNever2(_x) {7035 throw new Error();7036 }7037 util2.assertNever = assertNever2;7038 util2.arrayToEnum = (items) => {7039 const obj = {};7040 for (const item of items) {7041 obj[item] = item;7042 }7043 return obj;7044 };7045 util2.getValidEnumValues = (obj) => {7046 const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");7047 const filtered = {};7048 for (const k of validKeys) {7049 filtered[k] = obj[k];7050 }7051 return util2.objectValues(filtered);7052 };7053 util2.objectValues = (obj) => {7054 return util2.objectKeys(obj).map(function(e) {7055 return obj[e];7056 });7057 };7058 util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => {7059 const keys = [];7060 for (const key in object3) {7061 if (Object.prototype.hasOwnProperty.call(object3, key)) {7062 keys.push(key);7063 }7064 }7065 return keys;7066 };7067 util2.find = (arr, checker) => {7068 for (const item of arr) {7069 if (checker(item))7070 return item;7071 }7072 return void 0;7073 };7074 util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;7075 function joinValues2(array2, separator = " | ") {7076 return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);7077 }7078 util2.joinValues = joinValues2;7079 util2.jsonStringifyReplacer = (_, value) => {7080 if (typeof value === "bigint") {7081 return value.toString();7082 }7083 return value;7084 };7085})(util || (util = {}));7086var objectUtil;7087(function(objectUtil2) {7088 objectUtil2.mergeShapes = (first, second) => {7089 return {7090 ...first,7091 ...second7092 // second overwrites first7093 };7094 };7095})(objectUtil || (objectUtil = {}));7096var ZodParsedType = util.arrayToEnum([7097 "string",7098 "nan",7099 "number",7100 "integer",7101 "float",7102 "boolean",7103 "date",7104 "bigint",7105 "symbol",7106 "function",7107 "undefined",7108 "null",7109 "array",7110 "object",7111 "unknown",7112 "promise",7113 "void",7114 "never",7115 "map",7116 "set"7117]);7118var getParsedType = (data) => {7119 const t = typeof data;7120 switch (t) {7121 case "undefined":7122 return ZodParsedType.undefined;7123 case "string":7124 return ZodParsedType.string;7125 case "number":7126 return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;7127 case "boolean":7128 return ZodParsedType.boolean;7129 case "function":7130 return ZodParsedType.function;7131 case "bigint":7132 return ZodParsedType.bigint;7133 case "symbol":7134 return ZodParsedType.symbol;7135 case "object":7136 if (Array.isArray(data)) {7137 return ZodParsedType.array;7138 }7139 if (data === null) {7140 return ZodParsedType.null;7141 }7142 if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {7143 return ZodParsedType.promise;7144 }7145 if (typeof Map !== "undefined" && data instanceof Map) {7146 return ZodParsedType.map;7147 }7148 if (typeof Set !== "undefined" && data instanceof Set) {7149 return ZodParsedType.set;7150 }7151 if (typeof Date !== "undefined" && data instanceof Date) {7152 return ZodParsedType.date;7153 }7154 return ZodParsedType.object;7155 default:7156 return ZodParsedType.unknown;7157 }7158};71597160// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js7161var ZodIssueCode = util.arrayToEnum([7162 "invalid_type",7163 "invalid_literal",7164 "custom",7165 "invalid_union",7166 "invalid_union_discriminator",7167 "invalid_enum_value",7168 "unrecognized_keys",7169 "invalid_arguments",7170 "invalid_return_type",7171 "invalid_date",7172 "invalid_string",7173 "too_small",7174 "too_big",7175 "invalid_intersection_types",7176 "not_multiple_of",7177 "not_finite"7178]);7179var quotelessJson = (obj) => {7180 const json = JSON.stringify(obj, null, 2);7181 return json.replace(/"([^"]+)":/g, "$1:");7182};7183var ZodError = class _ZodError extends Error {7184 get errors() {7185 return this.issues;7186 }7187 constructor(issues) {7188 super();7189 this.issues = [];7190 this.addIssue = (sub) => {7191 this.issues = [...this.issues, sub];7192 };7193 this.addIssues = (subs = []) => {7194 this.issues = [...this.issues, ...subs];7195 };7196 const actualProto = new.target.prototype;7197 if (Object.setPrototypeOf) {7198 Object.setPrototypeOf(this, actualProto);7199 } else {7200 this.__proto__ = actualProto;7201 }7202 this.name = "ZodError";7203 this.issues = issues;7204 }7205 format(_mapper) {7206 const mapper = _mapper || function(issue2) {7207 return issue2.message;7208 };7209 const fieldErrors = { _errors: [] };7210 const processError = (error2) => {7211 for (const issue2 of error2.issues) {7212 if (issue2.code === "invalid_union") {7213 issue2.unionErrors.map(processError);7214 } else if (issue2.code === "invalid_return_type") {7215 processError(issue2.returnTypeError);7216 } else if (issue2.code === "invalid_arguments") {7217 processError(issue2.argumentsError);7218 } else if (issue2.path.length === 0) {7219 fieldErrors._errors.push(mapper(issue2));7220 } else {7221 let curr = fieldErrors;7222 let i = 0;7223 while (i < issue2.path.length) {7224 const el = issue2.path[i];7225 const terminal = i === issue2.path.length - 1;7226 if (!terminal) {7227 curr[el] = curr[el] || { _errors: [] };7228 } else {7229 curr[el] = curr[el] || { _errors: [] };7230 curr[el]._errors.push(mapper(issue2));7231 }7232 curr = curr[el];7233 i++;7234 }7235 }7236 }7237 };7238 processError(this);7239 return fieldErrors;7240 }7241 static assert(value) {7242 if (!(value instanceof _ZodError)) {7243 throw new Error(`Not a ZodError: ${value}`);7244 }7245 }7246 toString() {7247 return this.message;7248 }7249 get message() {7250 return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);7251 }7252 get isEmpty() {7253 return this.issues.length === 0;7254 }7255 flatten(mapper = (issue2) => issue2.message) {7256 const fieldErrors = {};7257 const formErrors = [];7258 for (const sub of this.issues) {7259 if (sub.path.length > 0) {7260 const firstEl = sub.path[0];7261 fieldErrors[firstEl] = fieldErrors[firstEl] || [];7262 fieldErrors[firstEl].push(mapper(sub));7263 } else {7264 formErrors.push(mapper(sub));7265 }7266 }7267 return { formErrors, fieldErrors };7268 }7269 get formErrors() {7270 return this.flatten();7271 }7272};7273ZodError.create = (issues) => {7274 const error2 = new ZodError(issues);7275 return error2;7276};72777278// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js7279var errorMap = (issue2, _ctx) => {7280 let message;7281 switch (issue2.code) {7282 case ZodIssueCode.invalid_type:7283 if (issue2.received === ZodParsedType.undefined) {7284 message = "Required";7285 } else {7286 message = `Expected ${issue2.expected}, received ${issue2.received}`;7287 }7288 break;7289 case ZodIssueCode.invalid_literal:7290 message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;7291 break;7292 case ZodIssueCode.unrecognized_keys:7293 message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;7294 break;7295 case ZodIssueCode.invalid_union:7296 message = `Invalid input`;7297 break;7298 case ZodIssueCode.invalid_union_discriminator:7299 message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;7300 break;7301 case ZodIssueCode.invalid_enum_value:7302 message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;7303 break;7304 case ZodIssueCode.invalid_arguments:7305 message = `Invalid function arguments`;7306 break;7307 case ZodIssueCode.invalid_return_type:7308 message = `Invalid function return type`;7309 break;7310 case ZodIssueCode.invalid_date:7311 message = `Invalid date`;7312 break;7313 case ZodIssueCode.invalid_string:7314 if (typeof issue2.validation === "object") {7315 if ("includes" in issue2.validation) {7316 message = `Invalid input: must include "${issue2.validation.includes}"`;7317 if (typeof issue2.validation.position === "number") {7318 message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;7319 }7320 } else if ("startsWith" in issue2.validation) {7321 message = `Invalid input: must start with "${issue2.validation.startsWith}"`;7322 } else if ("endsWith" in issue2.validation) {7323 message = `Invalid input: must end with "${issue2.validation.endsWith}"`;7324 } else {7325 util.assertNever(issue2.validation);7326 }7327 } else if (issue2.validation !== "regex") {7328 message = `Invalid ${issue2.validation}`;7329 } else {7330 message = "Invalid";7331 }7332 break;7333 case ZodIssueCode.too_small:7334 if (issue2.type === "array")7335 message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;7336 else if (issue2.type === "string")7337 message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;7338 else if (issue2.type === "number")7339 message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;7340 else if (issue2.type === "bigint")7341 message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;7342 else if (issue2.type === "date")7343 message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;7344 else7345 message = "Invalid input";7346 break;7347 case ZodIssueCode.too_big:7348 if (issue2.type === "array")7349 message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;7350 else if (issue2.type === "string")7351 message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;7352 else if (issue2.type === "number")7353 message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;7354 else if (issue2.type === "bigint")7355 message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;7356 else if (issue2.type === "date")7357 message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;7358 else7359 message = "Invalid input";7360 break;7361 case ZodIssueCode.custom:7362 message = `Invalid input`;7363 break;7364 case ZodIssueCode.invalid_intersection_types:7365 message = `Intersection results could not be merged`;7366 break;7367 case ZodIssueCode.not_multiple_of:7368 message = `Number must be a multiple of ${issue2.multipleOf}`;7369 break;7370 case ZodIssueCode.not_finite:7371 message = "Number must be finite";7372 break;7373 default:7374 message = _ctx.defaultError;7375 util.assertNever(issue2);7376 }7377 return { message };7378};7379var en_default = errorMap;73807381// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js7382var overrideErrorMap = en_default;7383function setErrorMap(map) {7384 overrideErrorMap = map;7385}7386function getErrorMap() {7387 return overrideErrorMap;7388}73897390// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js7391var makeIssue = (params) => {7392 const { data, path, errorMaps, issueData } = params;7393 const fullPath = [...path, ...issueData.path || []];7394 const fullIssue = {7395 ...issueData,7396 path: fullPath7397 };7398 if (issueData.message !== void 0) {7399 return {7400 ...issueData,7401 path: fullPath,7402 message: issueData.message7403 };7404 }7405 let errorMessage = "";7406 const maps = errorMaps.filter((m) => !!m).slice().reverse();7407 for (const map of maps) {7408 errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;7409 }7410 return {7411 ...issueData,7412 path: fullPath,7413 message: errorMessage7414 };7415};7416var EMPTY_PATH = [];7417function addIssueToContext(ctx, issueData) {7418 const overrideMap = getErrorMap();7419 const issue2 = makeIssue({7420 issueData,7421 data: ctx.data,7422 path: ctx.path,7423 errorMaps: [7424 ctx.common.contextualErrorMap,7425 // contextual error map is first priority7426 ctx.schemaErrorMap,7427 // then schema-bound map if available7428 overrideMap,7429 // then global override map7430 overrideMap === en_default ? void 0 : en_default7431 // then global default map7432 ].filter((x) => !!x)7433 });7434 ctx.common.issues.push(issue2);7435}7436var ParseStatus = class _ParseStatus {7437 constructor() {7438 this.value = "valid";7439 }7440 dirty() {7441 if (this.value === "valid")7442 this.value = "dirty";7443 }7444 abort() {7445 if (this.value !== "aborted")7446 this.value = "aborted";7447 }7448 static mergeArray(status, results) {7449 const arrayValue = [];7450 for (const s of results) {7451 if (s.status === "aborted")7452 return INVALID;7453 if (s.status === "dirty")7454 status.dirty();7455 arrayValue.push(s.value);7456 }7457 return { status: status.value, value: arrayValue };7458 }7459 static async mergeObjectAsync(status, pairs) {7460 const syncPairs = [];7461 for (const pair of pairs) {7462 const key = await pair.key;7463 const value = await pair.value;7464 syncPairs.push({7465 key,7466 value7467 });7468 }7469 return _ParseStatus.mergeObjectSync(status, syncPairs);7470 }7471 static mergeObjectSync(status, pairs) {7472 const finalObject = {};7473 for (const pair of pairs) {7474 const { key, value } = pair;7475 if (key.status === "aborted")7476 return INVALID;7477 if (value.status === "aborted")7478 return INVALID;7479 if (key.status === "dirty")7480 status.dirty();7481 if (value.status === "dirty")7482 status.dirty();7483 if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {7484 finalObject[key.value] = value.value;7485 }7486 }7487 return { status: status.value, value: finalObject };7488 }7489};7490var INVALID = Object.freeze({7491 status: "aborted"7492});7493var DIRTY = (value) => ({ status: "dirty", value });7494var OK = (value) => ({ status: "valid", value });7495var isAborted = (x) => x.status === "aborted";7496var isDirty = (x) => x.status === "dirty";7497var isValid = (x) => x.status === "valid";7498var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;74997500// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js7501var errorUtil;7502(function(errorUtil2) {7503 errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};7504 errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;7505})(errorUtil || (errorUtil = {}));75067507// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js7508var ParseInputLazyPath = class {7509 constructor(parent, value, path, key) {7510 this._cachedPath = [];7511 this.parent = parent;7512 this.data = value;7513 this._path = path;7514 this._key = key;7515 }7516 get path() {7517 if (!this._cachedPath.length) {7518 if (Array.isArray(this._key)) {7519 this._cachedPath.push(...this._path, ...this._key);7520 } else {7521 this._cachedPath.push(...this._path, this._key);7522 }7523 }7524 return this._cachedPath;7525 }7526};7527var handleResult = (ctx, result) => {7528 if (isValid(result)) {7529 return { success: true, data: result.value };7530 } else {7531 if (!ctx.common.issues.length) {7532 throw new Error("Validation failed but no issues detected.");7533 }7534 return {7535 success: false,7536 get error() {7537 if (this._error)7538 return this._error;7539 const error2 = new ZodError(ctx.common.issues);7540 this._error = error2;7541 return this._error;7542 }7543 };7544 }7545};7546function processCreateParams(params) {7547 if (!params)7548 return {};7549 const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;7550 if (errorMap2 && (invalid_type_error || required_error)) {7551 throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);7552 }7553 if (errorMap2)7554 return { errorMap: errorMap2, description };7555 const customMap = (iss, ctx) => {7556 const { message } = params;7557 if (iss.code === "invalid_enum_value") {7558 return { message: message ?? ctx.defaultError };7559 }7560 if (typeof ctx.data === "undefined") {7561 return { message: message ?? required_error ?? ctx.defaultError };7562 }7563 if (iss.code !== "invalid_type")7564 return { message: ctx.defaultError };7565 return { message: message ?? invalid_type_error ?? ctx.defaultError };7566 };7567 return { errorMap: customMap, description };7568}7569var ZodType = class {7570 get description() {7571 return this._def.description;7572 }7573 _getType(input) {7574 return getParsedType(input.data);7575 }7576 _getOrReturnCtx(input, ctx) {7577 return ctx || {7578 common: input.parent.common,7579 data: input.data,7580 parsedType: getParsedType(input.data),7581 schemaErrorMap: this._def.errorMap,7582 path: input.path,7583 parent: input.parent7584 };7585 }7586 _processInputParams(input) {7587 return {7588 status: new ParseStatus(),7589 ctx: {7590 common: input.parent.common,7591 data: input.data,7592 parsedType: getParsedType(input.data),7593 schemaErrorMap: this._def.errorMap,7594 path: input.path,7595 parent: input.parent7596 }7597 };7598 }7599 _parseSync(input) {7600 const result = this._parse(input);7601 if (isAsync(result)) {7602 throw new Error("Synchronous parse encountered promise.");7603 }7604 return result;7605 }7606 _parseAsync(input) {7607 const result = this._parse(input);7608 return Promise.resolve(result);7609 }7610 parse(data, params) {7611 const result = this.safeParse(data, params);7612 if (result.success)7613 return result.data;7614 throw result.error;7615 }7616 safeParse(data, params) {7617 const ctx = {7618 common: {7619 issues: [],7620 async: params?.async ?? false,7621 contextualErrorMap: params?.errorMap7622 },7623 path: params?.path || [],7624 schemaErrorMap: this._def.errorMap,7625 parent: null,7626 data,7627 parsedType: getParsedType(data)7628 };7629 const result = this._parseSync({ data, path: ctx.path, parent: ctx });7630 return handleResult(ctx, result);7631 }7632 "~validate"(data) {7633 const ctx = {7634 common: {7635 issues: [],7636 async: !!this["~standard"].async7637 },7638 path: [],7639 schemaErrorMap: this._def.errorMap,7640 parent: null,7641 data,7642 parsedType: getParsedType(data)7643 };7644 if (!this["~standard"].async) {7645 try {7646 const result = this._parseSync({ data, path: [], parent: ctx });7647 return isValid(result) ? {7648 value: result.value7649 } : {7650 issues: ctx.common.issues7651 };7652 } catch (err) {7653 if (err?.message?.toLowerCase()?.includes("encountered")) {7654 this["~standard"].async = true;7655 }7656 ctx.common = {7657 issues: [],7658 async: true7659 };7660 }7661 }7662 return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {7663 value: result.value7664 } : {7665 issues: ctx.common.issues7666 });7667 }7668 async parseAsync(data, params) {7669 const result = await this.safeParseAsync(data, params);7670 if (result.success)7671 return result.data;7672 throw result.error;7673 }7674 async safeParseAsync(data, params) {7675 const ctx = {7676 common: {7677 issues: [],7678 contextualErrorMap: params?.errorMap,7679 async: true7680 },7681 path: params?.path || [],7682 schemaErrorMap: this._def.errorMap,7683 parent: null,7684 data,7685 parsedType: getParsedType(data)7686 };7687 const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });7688 const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));7689 return handleResult(ctx, result);7690 }7691 refine(check2, message) {7692 const getIssueProperties = (val) => {7693 if (typeof message === "string" || typeof message === "undefined") {7694 return { message };7695 } else if (typeof message === "function") {7696 return message(val);7697 } else {7698 return message;7699 }7700 };7701 return this._refinement((val, ctx) => {7702 const result = check2(val);7703 const setError = () => ctx.addIssue({7704 code: ZodIssueCode.custom,7705 ...getIssueProperties(val)7706 });7707 if (typeof Promise !== "undefined" && result instanceof Promise) {7708 return result.then((data) => {7709 if (!data) {7710 setError();7711 return false;7712 } else {7713 return true;7714 }7715 });7716 }7717 if (!result) {7718 setError();7719 return false;7720 } else {7721 return true;7722 }7723 });7724 }7725 refinement(check2, refinementData) {7726 return this._refinement((val, ctx) => {7727 if (!check2(val)) {7728 ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);7729 return false;7730 } else {7731 return true;7732 }7733 });7734 }7735 _refinement(refinement) {7736 return new ZodEffects({7737 schema: this,7738 typeName: ZodFirstPartyTypeKind.ZodEffects,7739 effect: { type: "refinement", refinement }7740 });7741 }7742 superRefine(refinement) {7743 return this._refinement(refinement);7744 }7745 constructor(def) {7746 this.spa = this.safeParseAsync;7747 this._def = def;7748 this.parse = this.parse.bind(this);7749 this.safeParse = this.safeParse.bind(this);7750 this.parseAsync = this.parseAsync.bind(this);7751 this.safeParseAsync = this.safeParseAsync.bind(this);7752 this.spa = this.spa.bind(this);7753 this.refine = this.refine.bind(this);7754 this.refinement = this.refinement.bind(this);7755 this.superRefine = this.superRefine.bind(this);7756 this.optional = this.optional.bind(this);7757 this.nullable = this.nullable.bind(this);7758 this.nullish = this.nullish.bind(this);7759 this.array = this.array.bind(this);7760 this.promise = this.promise.bind(this);7761 this.or = this.or.bind(this);7762 this.and = this.and.bind(this);7763 this.transform = this.transform.bind(this);7764 this.brand = this.brand.bind(this);7765 this.default = this.default.bind(this);7766 this.catch = this.catch.bind(this);7767 this.describe = this.describe.bind(this);7768 this.pipe = this.pipe.bind(this);7769 this.readonly = this.readonly.bind(this);7770 this.isNullable = this.isNullable.bind(this);7771 this.isOptional = this.isOptional.bind(this);7772 this["~standard"] = {7773 version: 1,7774 vendor: "zod",7775 validate: (data) => this["~validate"](data)7776 };7777 }7778 optional() {7779 return ZodOptional.create(this, this._def);7780 }7781 nullable() {7782 return ZodNullable.create(this, this._def);7783 }7784 nullish() {7785 return this.nullable().optional();7786 }7787 array() {7788 return ZodArray.create(this);7789 }7790 promise() {7791 return ZodPromise.create(this, this._def);7792 }7793 or(option) {7794 return ZodUnion.create([this, option], this._def);7795 }7796 and(incoming) {7797 return ZodIntersection.create(this, incoming, this._def);7798 }7799 transform(transform2) {7800 return new ZodEffects({7801 ...processCreateParams(this._def),7802 schema: this,7803 typeName: ZodFirstPartyTypeKind.ZodEffects,7804 effect: { type: "transform", transform: transform2 }7805 });7806 }7807 default(def) {7808 const defaultValueFunc = typeof def === "function" ? def : () => def;7809 return new ZodDefault({7810 ...processCreateParams(this._def),7811 innerType: this,7812 defaultValue: defaultValueFunc,7813 typeName: ZodFirstPartyTypeKind.ZodDefault7814 });7815 }7816 brand() {7817 return new ZodBranded({7818 typeName: ZodFirstPartyTypeKind.ZodBranded,7819 type: this,7820 ...processCreateParams(this._def)7821 });7822 }7823 catch(def) {7824 const catchValueFunc = typeof def === "function" ? def : () => def;7825 return new ZodCatch({7826 ...processCreateParams(this._def),7827 innerType: this,7828 catchValue: catchValueFunc,7829 typeName: ZodFirstPartyTypeKind.ZodCatch7830 });7831 }7832 describe(description) {7833 const This = this.constructor;7834 return new This({7835 ...this._def,7836 description7837 });7838 }7839 pipe(target) {7840 return ZodPipeline.create(this, target);7841 }7842 readonly() {7843 return ZodReadonly.create(this);7844 }7845 isOptional() {7846 return this.safeParse(void 0).success;7847 }7848 isNullable() {7849 return this.safeParse(null).success;7850 }7851};7852var cuidRegex = /^c[^\s-]{8,}$/i;7853var cuid2Regex = /^[0-9a-z]+$/;7854var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;7855var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;7856var nanoidRegex = /^[a-z0-9_-]{21}$/i;7857var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;7858var durationRegex = /^[-+]?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)?)??$/;7859var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;7860var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;7861var emojiRegex;7862var ipv4Regex = /^(?:(?: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])$/;7863var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/;7864var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;7865var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;7866var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;7867var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;7868var dateRegexSource = `((\\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])))`;7869var dateRegex = new RegExp(`^${dateRegexSource}$`);7870function timeRegexSource(args) {7871 let secondsRegexSource = `[0-5]\\d`;7872 if (args.precision) {7873 secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;7874 } else if (args.precision == null) {7875 secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;7876 }7877 const secondsQuantifier = args.precision ? "+" : "?";7878 return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;7879}7880function timeRegex(args) {7881 return new RegExp(`^${timeRegexSource(args)}$`);7882}7883function datetimeRegex(args) {7884 let regex = `${dateRegexSource}T${timeRegexSource(args)}`;7885 const opts = [];7886 opts.push(args.local ? `Z?` : `Z`);7887 if (args.offset)7888 opts.push(`([+-]\\d{2}:?\\d{2})`);7889 regex = `${regex}(${opts.join("|")})`;7890 return new RegExp(`^${regex}$`);7891}7892function isValidIP(ip, version2) {7893 if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {7894 return true;7895 }7896 if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {7897 return true;7898 }7899 return false;7900}7901function isValidJWT(jwt, alg) {7902 if (!jwtRegex.test(jwt))7903 return false;7904 try {7905 const [header] = jwt.split(".");7906 if (!header)7907 return false;7908 const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");7909 const decoded = JSON.parse(atob(base642));7910 if (typeof decoded !== "object" || decoded === null)7911 return false;7912 if ("typ" in decoded && decoded?.typ !== "JWT")7913 return false;7914 if (!decoded.alg)7915 return false;7916 if (alg && decoded.alg !== alg)7917 return false;7918 return true;7919 } catch {7920 return false;7921 }7922}7923function isValidCidr(ip, version2) {7924 if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {7925 return true;7926 }7927 if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {7928 return true;7929 }7930 return false;7931}7932var ZodString = class _ZodString2 extends ZodType {7933 _parse(input) {7934 if (this._def.coerce) {7935 input.data = String(input.data);7936 }7937 const parsedType2 = this._getType(input);7938 if (parsedType2 !== ZodParsedType.string) {7939 const ctx2 = this._getOrReturnCtx(input);7940 addIssueToContext(ctx2, {7941 code: ZodIssueCode.invalid_type,7942 expected: ZodParsedType.string,7943 received: ctx2.parsedType7944 });7945 return INVALID;7946 }7947 const status = new ParseStatus();7948 let ctx = void 0;7949 for (const check2 of this._def.checks) {7950 if (check2.kind === "min") {7951 if (input.data.length < check2.value) {7952 ctx = this._getOrReturnCtx(input, ctx);7953 addIssueToContext(ctx, {7954 code: ZodIssueCode.too_small,7955 minimum: check2.value,7956 type: "string",7957 inclusive: true,7958 exact: false,7959 message: check2.message7960 });7961 status.dirty();7962 }7963 } else if (check2.kind === "max") {7964 if (input.data.length > check2.value) {7965 ctx = this._getOrReturnCtx(input, ctx);7966 addIssueToContext(ctx, {7967 code: ZodIssueCode.too_big,7968 maximum: check2.value,7969 type: "string",7970 inclusive: true,7971 exact: false,7972 message: check2.message7973 });7974 status.dirty();7975 }7976 } else if (check2.kind === "length") {7977 const tooBig = input.data.length > check2.value;7978 const tooSmall = input.data.length < check2.value;7979 if (tooBig || tooSmall) {7980 ctx = this._getOrReturnCtx(input, ctx);7981 if (tooBig) {7982 addIssueToContext(ctx, {7983 code: ZodIssueCode.too_big,7984 maximum: check2.value,7985 type: "string",7986 inclusive: true,7987 exact: true,7988 message: check2.message7989 });7990 } else if (tooSmall) {7991 addIssueToContext(ctx, {7992 code: ZodIssueCode.too_small,7993 minimum: check2.value,7994 type: "string",7995 inclusive: true,7996 exact: true,7997 message: check2.message7998 });7999 }8000 status.dirty();8001 }8002 } else if (check2.kind === "email") {8003 if (!emailRegex.test(input.data)) {8004 ctx = this._getOrReturnCtx(input, ctx);8005 addIssueToContext(ctx, {8006 validation: "email",8007 code: ZodIssueCode.invalid_string,8008 message: check2.message8009 });8010 status.dirty();8011 }8012 } else if (check2.kind === "emoji") {8013 if (!emojiRegex) {8014 emojiRegex = new RegExp(_emojiRegex, "u");8015 }8016 if (!emojiRegex.test(input.data)) {8017 ctx = this._getOrReturnCtx(input, ctx);8018 addIssueToContext(ctx, {8019 validation: "emoji",8020 code: ZodIssueCode.invalid_string,8021 message: check2.message8022 });8023 status.dirty();8024 }8025 } else if (check2.kind === "uuid") {8026 if (!uuidRegex.test(input.data)) {8027 ctx = this._getOrReturnCtx(input, ctx);8028 addIssueToContext(ctx, {8029 validation: "uuid",8030 code: ZodIssueCode.invalid_string,8031 message: check2.message8032 });8033 status.dirty();8034 }8035 } else if (check2.kind === "nanoid") {8036 if (!nanoidRegex.test(input.data)) {8037 ctx = this._getOrReturnCtx(input, ctx);8038 addIssueToContext(ctx, {8039 validation: "nanoid",8040 code: ZodIssueCode.invalid_string,8041 message: check2.message8042 });8043 status.dirty();8044 }8045 } else if (check2.kind === "cuid") {8046 if (!cuidRegex.test(input.data)) {8047 ctx = this._getOrReturnCtx(input, ctx);8048 addIssueToContext(ctx, {8049 validation: "cuid",8050 code: ZodIssueCode.invalid_string,8051 message: check2.message8052 });8053 status.dirty();8054 }8055 } else if (check2.kind === "cuid2") {8056 if (!cuid2Regex.test(input.data)) {8057 ctx = this._getOrReturnCtx(input, ctx);8058 addIssueToContext(ctx, {8059 validation: "cuid2",8060 code: ZodIssueCode.invalid_string,8061 message: check2.message8062 });8063 status.dirty();8064 }8065 } else if (check2.kind === "ulid") {8066 if (!ulidRegex.test(input.data)) {8067 ctx = this._getOrReturnCtx(input, ctx);8068 addIssueToContext(ctx, {8069 validation: "ulid",8070 code: ZodIssueCode.invalid_string,8071 message: check2.message8072 });8073 status.dirty();8074 }8075 } else if (check2.kind === "url") {8076 try {8077 new URL(input.data);8078 } catch {8079 ctx = this._getOrReturnCtx(input, ctx);8080 addIssueToContext(ctx, {8081 validation: "url",8082 code: ZodIssueCode.invalid_string,8083 message: check2.message8084 });8085 status.dirty();8086 }8087 } else if (check2.kind === "regex") {8088 check2.regex.lastIndex = 0;8089 const testResult = check2.regex.test(input.data);8090 if (!testResult) {8091 ctx = this._getOrReturnCtx(input, ctx);8092 addIssueToContext(ctx, {8093 validation: "regex",8094 code: ZodIssueCode.invalid_string,8095 message: check2.message8096 });8097 status.dirty();8098 }8099 } else if (check2.kind === "trim") {8100 input.data = input.data.trim();8101 } else if (check2.kind === "includes") {8102 if (!input.data.includes(check2.value, check2.position)) {8103 ctx = this._getOrReturnCtx(input, ctx);8104 addIssueToContext(ctx, {8105 code: ZodIssueCode.invalid_string,8106 validation: { includes: check2.value, position: check2.position },8107 message: check2.message8108 });8109 status.dirty();8110 }8111 } else if (check2.kind === "toLowerCase") {8112 input.data = input.data.toLowerCase();8113 } else if (check2.kind === "toUpperCase") {8114 input.data = input.data.toUpperCase();8115 } else if (check2.kind === "startsWith") {8116 if (!input.data.startsWith(check2.value)) {8117 ctx = this._getOrReturnCtx(input, ctx);8118 addIssueToContext(ctx, {8119 code: ZodIssueCode.invalid_string,8120 validation: { startsWith: check2.value },8121 message: check2.message8122 });8123 status.dirty();8124 }8125 } else if (check2.kind === "endsWith") {8126 if (!input.data.endsWith(check2.value)) {8127 ctx = this._getOrReturnCtx(input, ctx);8128 addIssueToContext(ctx, {8129 code: ZodIssueCode.invalid_string,8130 validation: { endsWith: check2.value },8131 message: check2.message8132 });8133 status.dirty();8134 }8135 } else if (check2.kind === "datetime") {8136 const regex = datetimeRegex(check2);8137 if (!regex.test(input.data)) {8138 ctx = this._getOrReturnCtx(input, ctx);8139 addIssueToContext(ctx, {8140 code: ZodIssueCode.invalid_string,8141 validation: "datetime",8142 message: check2.message8143 });8144 status.dirty();8145 }8146 } else if (check2.kind === "date") {8147 const regex = dateRegex;8148 if (!regex.test(input.data)) {8149 ctx = this._getOrReturnCtx(input, ctx);8150 addIssueToContext(ctx, {8151 code: ZodIssueCode.invalid_string,8152 validation: "date",8153 message: check2.message8154 });8155 status.dirty();8156 }8157 } else if (check2.kind === "time") {8158 const regex = timeRegex(check2);8159 if (!regex.test(input.data)) {8160 ctx = this._getOrReturnCtx(input, ctx);8161 addIssueToContext(ctx, {8162 code: ZodIssueCode.invalid_string,8163 validation: "time",8164 message: check2.message8165 });8166 status.dirty();8167 }8168 } else if (check2.kind === "duration") {8169 if (!durationRegex.test(input.data)) {8170 ctx = this._getOrReturnCtx(input, ctx);8171 addIssueToContext(ctx, {8172 validation: "duration",8173 code: ZodIssueCode.invalid_string,8174 message: check2.message8175 });8176 status.dirty();8177 }8178 } else if (check2.kind === "ip") {8179 if (!isValidIP(input.data, check2.version)) {8180 ctx = this._getOrReturnCtx(input, ctx);8181 addIssueToContext(ctx, {8182 validation: "ip",8183 code: ZodIssueCode.invalid_string,8184 message: check2.message8185 });8186 status.dirty();8187 }8188 } else if (check2.kind === "jwt") {8189 if (!isValidJWT(input.data, check2.alg)) {8190 ctx = this._getOrReturnCtx(input, ctx);8191 addIssueToContext(ctx, {8192 validation: "jwt",8193 code: ZodIssueCode.invalid_string,8194 message: check2.message8195 });8196 status.dirty();8197 }8198 } else if (check2.kind === "cidr") {8199 if (!isValidCidr(input.data, check2.version)) {8200 ctx = this._getOrReturnCtx(input, ctx);8201 addIssueToContext(ctx, {8202 validation: "cidr",8203 code: ZodIssueCode.invalid_string,8204 message: check2.message8205 });8206 status.dirty();8207 }8208 } else if (check2.kind === "base64") {8209 if (!base64Regex.test(input.data)) {8210 ctx = this._getOrReturnCtx(input, ctx);8211 addIssueToContext(ctx, {8212 validation: "base64",8213 code: ZodIssueCode.invalid_string,8214 message: check2.message8215 });8216 status.dirty();8217 }8218 } else if (check2.kind === "base64url") {8219 if (!base64urlRegex.test(input.data)) {8220 ctx = this._getOrReturnCtx(input, ctx);8221 addIssueToContext(ctx, {8222 validation: "base64url",8223 code: ZodIssueCode.invalid_string,8224 message: check2.message8225 });8226 status.dirty();8227 }8228 } else {8229 util.assertNever(check2);8230 }8231 }8232 return { status: status.value, value: input.data };8233 }8234 _regex(regex, validation, message) {8235 return this.refinement((data) => regex.test(data), {8236 validation,8237 code: ZodIssueCode.invalid_string,8238 ...errorUtil.errToObj(message)8239 });8240 }8241 _addCheck(check2) {8242 return new _ZodString2({8243 ...this._def,8244 checks: [...this._def.checks, check2]8245 });8246 }8247 email(message) {8248 return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });8249 }8250 url(message) {8251 return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });8252 }8253 emoji(message) {8254 return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });8255 }8256 uuid(message) {8257 return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });8258 }8259 nanoid(message) {8260 return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });8261 }8262 cuid(message) {8263 return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });8264 }8265 cuid2(message) {8266 return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });8267 }8268 ulid(message) {8269 return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });8270 }8271 base64(message) {8272 return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });8273 }8274 base64url(message) {8275 return this._addCheck({8276 kind: "base64url",8277 ...errorUtil.errToObj(message)8278 });8279 }8280 jwt(options) {8281 return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });8282 }8283 ip(options) {8284 return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });8285 }8286 cidr(options) {8287 return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });8288 }8289 datetime(options) {8290 if (typeof options === "string") {8291 return this._addCheck({8292 kind: "datetime",8293 precision: null,8294 offset: false,8295 local: false,8296 message: options8297 });8298 }8299 return this._addCheck({8300 kind: "datetime",8301 precision: typeof options?.precision === "undefined" ? null : options?.precision,8302 offset: options?.offset ?? false,8303 local: options?.local ?? false,8304 ...errorUtil.errToObj(options?.message)8305 });8306 }8307 date(message) {8308 return this._addCheck({ kind: "date", message });8309 }8310 time(options) {8311 if (typeof options === "string") {8312 return this._addCheck({8313 kind: "time",8314 precision: null,8315 message: options8316 });8317 }8318 return this._addCheck({8319 kind: "time",8320 precision: typeof options?.precision === "undefined" ? null : options?.precision,8321 ...errorUtil.errToObj(options?.message)8322 });8323 }8324 duration(message) {8325 return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });8326 }8327 regex(regex, message) {8328 return this._addCheck({8329 kind: "regex",8330 regex,8331 ...errorUtil.errToObj(message)8332 });8333 }8334 includes(value, options) {8335 return this._addCheck({8336 kind: "includes",8337 value,8338 position: options?.position,8339 ...errorUtil.errToObj(options?.message)8340 });8341 }8342 startsWith(value, message) {8343 return this._addCheck({8344 kind: "startsWith",8345 value,8346 ...errorUtil.errToObj(message)8347 });8348 }8349 endsWith(value, message) {8350 return this._addCheck({8351 kind: "endsWith",8352 value,8353 ...errorUtil.errToObj(message)8354 });8355 }8356 min(minLength, message) {8357 return this._addCheck({8358 kind: "min",8359 value: minLength,8360 ...errorUtil.errToObj(message)8361 });8362 }8363 max(maxLength, message) {8364 return this._addCheck({8365 kind: "max",8366 value: maxLength,8367 ...errorUtil.errToObj(message)8368 });8369 }8370 length(len, message) {8371 return this._addCheck({8372 kind: "length",8373 value: len,8374 ...errorUtil.errToObj(message)8375 });8376 }8377 /**8378 * Equivalent to `.min(1)`8379 */8380 nonempty(message) {8381 return this.min(1, errorUtil.errToObj(message));8382 }8383 trim() {8384 return new _ZodString2({8385 ...this._def,8386 checks: [...this._def.checks, { kind: "trim" }]8387 });8388 }8389 toLowerCase() {8390 return new _ZodString2({8391 ...this._def,8392 checks: [...this._def.checks, { kind: "toLowerCase" }]8393 });8394 }8395 toUpperCase() {8396 return new _ZodString2({8397 ...this._def,8398 checks: [...this._def.checks, { kind: "toUpperCase" }]8399 });8400 }8401 get isDatetime() {8402 return !!this._def.checks.find((ch) => ch.kind === "datetime");8403 }8404 get isDate() {8405 return !!this._def.checks.find((ch) => ch.kind === "date");8406 }8407 get isTime() {8408 return !!this._def.checks.find((ch) => ch.kind === "time");8409 }8410 get isDuration() {8411 return !!this._def.checks.find((ch) => ch.kind === "duration");8412 }8413 get isEmail() {8414 return !!this._def.checks.find((ch) => ch.kind === "email");8415 }8416 get isURL() {8417 return !!this._def.checks.find((ch) => ch.kind === "url");8418 }8419 get isEmoji() {8420 return !!this._def.checks.find((ch) => ch.kind === "emoji");8421 }8422 get isUUID() {8423 return !!this._def.checks.find((ch) => ch.kind === "uuid");8424 }8425 get isNANOID() {8426 return !!this._def.checks.find((ch) => ch.kind === "nanoid");8427 }8428 get isCUID() {8429 return !!this._def.checks.find((ch) => ch.kind === "cuid");8430 }8431 get isCUID2() {8432 return !!this._def.checks.find((ch) => ch.kind === "cuid2");8433 }8434 get isULID() {8435 return !!this._def.checks.find((ch) => ch.kind === "ulid");8436 }8437 get isIP() {8438 return !!this._def.checks.find((ch) => ch.kind === "ip");8439 }8440 get isCIDR() {8441 return !!this._def.checks.find((ch) => ch.kind === "cidr");8442 }8443 get isBase64() {8444 return !!this._def.checks.find((ch) => ch.kind === "base64");8445 }8446 get isBase64url() {8447 return !!this._def.checks.find((ch) => ch.kind === "base64url");8448 }8449 get minLength() {8450 let min = null;8451 for (const ch of this._def.checks) {8452 if (ch.kind === "min") {8453 if (min === null || ch.value > min)8454 min = ch.value;8455 }8456 }8457 return min;8458 }8459 get maxLength() {8460 let max = null;8461 for (const ch of this._def.checks) {8462 if (ch.kind === "max") {8463 if (max === null || ch.value < max)8464 max = ch.value;8465 }8466 }8467 return max;8468 }8469};8470ZodString.create = (params) => {8471 return new ZodString({8472 checks: [],8473 typeName: ZodFirstPartyTypeKind.ZodString,8474 coerce: params?.coerce ?? false,8475 ...processCreateParams(params)8476 });8477};8478function floatSafeRemainder(val, step) {8479 const valDecCount = (val.toString().split(".")[1] || "").length;8480 const stepDecCount = (step.toString().split(".")[1] || "").length;8481 const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;8482 const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));8483 const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));8484 return valInt % stepInt / 10 ** decCount;8485}8486var ZodNumber = class _ZodNumber extends ZodType {8487 constructor() {8488 super(...arguments);8489 this.min = this.gte;8490 this.max = this.lte;8491 this.step = this.multipleOf;8492 }8493 _parse(input) {8494 if (this._def.coerce) {8495 input.data = Number(input.data);8496 }8497 const parsedType2 = this._getType(input);8498 if (parsedType2 !== ZodParsedType.number) {8499 const ctx2 = this._getOrReturnCtx(input);8500 addIssueToContext(ctx2, {8501 code: ZodIssueCode.invalid_type,8502 expected: ZodParsedType.number,8503 received: ctx2.parsedType8504 });8505 return INVALID;8506 }8507 let ctx = void 0;8508 const status = new ParseStatus();8509 for (const check2 of this._def.checks) {8510 if (check2.kind === "int") {8511 if (!util.isInteger(input.data)) {8512 ctx = this._getOrReturnCtx(input, ctx);8513 addIssueToContext(ctx, {8514 code: ZodIssueCode.invalid_type,8515 expected: "integer",8516 received: "float",8517 message: check2.message8518 });8519 status.dirty();8520 }8521 } else if (check2.kind === "min") {8522 const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;8523 if (tooSmall) {8524 ctx = this._getOrReturnCtx(input, ctx);8525 addIssueToContext(ctx, {8526 code: ZodIssueCode.too_small,8527 minimum: check2.value,8528 type: "number",8529 inclusive: check2.inclusive,8530 exact: false,8531 message: check2.message8532 });8533 status.dirty();8534 }8535 } else if (check2.kind === "max") {8536 const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;8537 if (tooBig) {8538 ctx = this._getOrReturnCtx(input, ctx);8539 addIssueToContext(ctx, {8540 code: ZodIssueCode.too_big,8541 maximum: check2.value,8542 type: "number",8543 inclusive: check2.inclusive,8544 exact: false,8545 message: check2.message8546 });8547 status.dirty();8548 }8549 } else if (check2.kind === "multipleOf") {8550 if (floatSafeRemainder(input.data, check2.value) !== 0) {8551 ctx = this._getOrReturnCtx(input, ctx);8552 addIssueToContext(ctx, {8553 code: ZodIssueCode.not_multiple_of,8554 multipleOf: check2.value,8555 message: check2.message8556 });8557 status.dirty();8558 }8559 } else if (check2.kind === "finite") {8560 if (!Number.isFinite(input.data)) {8561 ctx = this._getOrReturnCtx(input, ctx);8562 addIssueToContext(ctx, {8563 code: ZodIssueCode.not_finite,8564 message: check2.message8565 });8566 status.dirty();8567 }8568 } else {8569 util.assertNever(check2);8570 }8571 }8572 return { status: status.value, value: input.data };8573 }8574 gte(value, message) {8575 return this.setLimit("min", value, true, errorUtil.toString(message));8576 }8577 gt(value, message) {8578 return this.setLimit("min", value, false, errorUtil.toString(message));8579 }8580 lte(value, message) {8581 return this.setLimit("max", value, true, errorUtil.toString(message));8582 }8583 lt(value, message) {8584 return this.setLimit("max", value, false, errorUtil.toString(message));8585 }8586 setLimit(kind, value, inclusive, message) {8587 return new _ZodNumber({8588 ...this._def,8589 checks: [8590 ...this._def.checks,8591 {8592 kind,8593 value,8594 inclusive,8595 message: errorUtil.toString(message)8596 }8597 ]8598 });8599 }8600 _addCheck(check2) {8601 return new _ZodNumber({8602 ...this._def,8603 checks: [...this._def.checks, check2]8604 });8605 }8606 int(message) {8607 return this._addCheck({8608 kind: "int",8609 message: errorUtil.toString(message)8610 });8611 }8612 positive(message) {8613 return this._addCheck({8614 kind: "min",8615 value: 0,8616 inclusive: false,8617 message: errorUtil.toString(message)8618 });8619 }8620 negative(message) {8621 return this._addCheck({8622 kind: "max",8623 value: 0,8624 inclusive: false,8625 message: errorUtil.toString(message)8626 });8627 }8628 nonpositive(message) {8629 return this._addCheck({8630 kind: "max",8631 value: 0,8632 inclusive: true,8633 message: errorUtil.toString(message)8634 });8635 }8636 nonnegative(message) {8637 return this._addCheck({8638 kind: "min",8639 value: 0,8640 inclusive: true,8641 message: errorUtil.toString(message)8642 });8643 }8644 multipleOf(value, message) {8645 return this._addCheck({8646 kind: "multipleOf",8647 value,8648 message: errorUtil.toString(message)8649 });8650 }8651 finite(message) {8652 return this._addCheck({8653 kind: "finite",8654 message: errorUtil.toString(message)8655 });8656 }8657 safe(message) {8658 return this._addCheck({8659 kind: "min",8660 inclusive: true,8661 value: Number.MIN_SAFE_INTEGER,8662 message: errorUtil.toString(message)8663 })._addCheck({8664 kind: "max",8665 inclusive: true,8666 value: Number.MAX_SAFE_INTEGER,8667 message: errorUtil.toString(message)8668 });8669 }8670 get minValue() {8671 let min = null;8672 for (const ch of this._def.checks) {8673 if (ch.kind === "min") {8674 if (min === null || ch.value > min)8675 min = ch.value;8676 }8677 }8678 return min;8679 }8680 get maxValue() {8681 let max = null;8682 for (const ch of this._def.checks) {8683 if (ch.kind === "max") {8684 if (max === null || ch.value < max)8685 max = ch.value;8686 }8687 }8688 return max;8689 }8690 get isInt() {8691 return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));8692 }8693 get isFinite() {8694 let max = null;8695 let min = null;8696 for (const ch of this._def.checks) {8697 if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {8698 return true;8699 } else if (ch.kind === "min") {8700 if (min === null || ch.value > min)8701 min = ch.value;8702 } else if (ch.kind === "max") {8703 if (max === null || ch.value < max)8704 max = ch.value;8705 }8706 }8707 return Number.isFinite(min) && Number.isFinite(max);8708 }8709};8710ZodNumber.create = (params) => {8711 return new ZodNumber({8712 checks: [],8713 typeName: ZodFirstPartyTypeKind.ZodNumber,8714 coerce: params?.coerce || false,8715 ...processCreateParams(params)8716 });8717};8718var ZodBigInt = class _ZodBigInt extends ZodType {8719 constructor() {8720 super(...arguments);8721 this.min = this.gte;8722 this.max = this.lte;8723 }8724 _parse(input) {8725 if (this._def.coerce) {8726 try {8727 input.data = BigInt(input.data);8728 } catch {8729 return this._getInvalidInput(input);8730 }8731 }8732 const parsedType2 = this._getType(input);8733 if (parsedType2 !== ZodParsedType.bigint) {8734 return this._getInvalidInput(input);8735 }8736 let ctx = void 0;8737 const status = new ParseStatus();8738 for (const check2 of this._def.checks) {8739 if (check2.kind === "min") {8740 const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;8741 if (tooSmall) {8742 ctx = this._getOrReturnCtx(input, ctx);8743 addIssueToContext(ctx, {8744 code: ZodIssueCode.too_small,8745 type: "bigint",8746 minimum: check2.value,8747 inclusive: check2.inclusive,8748 message: check2.message8749 });8750 status.dirty();8751 }8752 } else if (check2.kind === "max") {8753 const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;8754 if (tooBig) {8755 ctx = this._getOrReturnCtx(input, ctx);8756 addIssueToContext(ctx, {8757 code: ZodIssueCode.too_big,8758 type: "bigint",8759 maximum: check2.value,8760 inclusive: check2.inclusive,8761 message: check2.message8762 });8763 status.dirty();8764 }8765 } else if (check2.kind === "multipleOf") {8766 if (input.data % check2.value !== BigInt(0)) {8767 ctx = this._getOrReturnCtx(input, ctx);8768 addIssueToContext(ctx, {8769 code: ZodIssueCode.not_multiple_of,8770 multipleOf: check2.value,8771 message: check2.message8772 });8773 status.dirty();8774 }8775 } else {8776 util.assertNever(check2);8777 }8778 }8779 return { status: status.value, value: input.data };8780 }8781 _getInvalidInput(input) {8782 const ctx = this._getOrReturnCtx(input);8783 addIssueToContext(ctx, {8784 code: ZodIssueCode.invalid_type,8785 expected: ZodParsedType.bigint,8786 received: ctx.parsedType8787 });8788 return INVALID;8789 }8790 gte(value, message) {8791 return this.setLimit("min", value, true, errorUtil.toString(message));8792 }8793 gt(value, message) {8794 return this.setLimit("min", value, false, errorUtil.toString(message));8795 }8796 lte(value, message) {8797 return this.setLimit("max", value, true, errorUtil.toString(message));8798 }8799 lt(value, message) {8800 return this.setLimit("max", value, false, errorUtil.toString(message));8801 }8802 setLimit(kind, value, inclusive, message) {8803 return new _ZodBigInt({8804 ...this._def,8805 checks: [8806 ...this._def.checks,8807 {8808 kind,8809 value,8810 inclusive,8811 message: errorUtil.toString(message)8812 }8813 ]8814 });8815 }8816 _addCheck(check2) {8817 return new _ZodBigInt({8818 ...this._def,8819 checks: [...this._def.checks, check2]8820 });8821 }8822 positive(message) {8823 return this._addCheck({8824 kind: "min",8825 value: BigInt(0),8826 inclusive: false,8827 message: errorUtil.toString(message)8828 });8829 }8830 negative(message) {8831 return this._addCheck({8832 kind: "max",8833 value: BigInt(0),8834 inclusive: false,8835 message: errorUtil.toString(message)8836 });8837 }8838 nonpositive(message) {8839 return this._addCheck({8840 kind: "max",8841 value: BigInt(0),8842 inclusive: true,8843 message: errorUtil.toString(message)8844 });8845 }8846 nonnegative(message) {8847 return this._addCheck({8848 kind: "min",8849 value: BigInt(0),8850 inclusive: true,8851 message: errorUtil.toString(message)8852 });8853 }8854 multipleOf(value, message) {8855 return this._addCheck({8856 kind: "multipleOf",8857 value,8858 message: errorUtil.toString(message)8859 });8860 }8861 get minValue() {8862 let min = null;8863 for (const ch of this._def.checks) {8864 if (ch.kind === "min") {8865 if (min === null || ch.value > min)8866 min = ch.value;8867 }8868 }8869 return min;8870 }8871 get maxValue() {8872 let max = null;8873 for (const ch of this._def.checks) {8874 if (ch.kind === "max") {8875 if (max === null || ch.value < max)8876 max = ch.value;8877 }8878 }8879 return max;8880 }8881};8882ZodBigInt.create = (params) => {8883 return new ZodBigInt({8884 checks: [],8885 typeName: ZodFirstPartyTypeKind.ZodBigInt,8886 coerce: params?.coerce ?? false,8887 ...processCreateParams(params)8888 });8889};8890var ZodBoolean = class extends ZodType {8891 _parse(input) {8892 if (this._def.coerce) {8893 input.data = Boolean(input.data);8894 }8895 const parsedType2 = this._getType(input);8896 if (parsedType2 !== ZodParsedType.boolean) {8897 const ctx = this._getOrReturnCtx(input);8898 addIssueToContext(ctx, {8899 code: ZodIssueCode.invalid_type,8900 expected: ZodParsedType.boolean,8901 received: ctx.parsedType8902 });8903 return INVALID;8904 }8905 return OK(input.data);8906 }8907};8908ZodBoolean.create = (params) => {8909 return new ZodBoolean({8910 typeName: ZodFirstPartyTypeKind.ZodBoolean,8911 coerce: params?.coerce || false,8912 ...processCreateParams(params)8913 });8914};8915var ZodDate = class _ZodDate extends ZodType {8916 _parse(input) {8917 if (this._def.coerce) {8918 input.data = new Date(input.data);8919 }8920 const parsedType2 = this._getType(input);8921 if (parsedType2 !== ZodParsedType.date) {8922 const ctx2 = this._getOrReturnCtx(input);8923 addIssueToContext(ctx2, {8924 code: ZodIssueCode.invalid_type,8925 expected: ZodParsedType.date,8926 received: ctx2.parsedType8927 });8928 return INVALID;8929 }8930 if (Number.isNaN(input.data.getTime())) {8931 const ctx2 = this._getOrReturnCtx(input);8932 addIssueToContext(ctx2, {8933 code: ZodIssueCode.invalid_date8934 });8935 return INVALID;8936 }8937 const status = new ParseStatus();8938 let ctx = void 0;8939 for (const check2 of this._def.checks) {8940 if (check2.kind === "min") {8941 if (input.data.getTime() < check2.value) {8942 ctx = this._getOrReturnCtx(input, ctx);8943 addIssueToContext(ctx, {8944 code: ZodIssueCode.too_small,8945 message: check2.message,8946 inclusive: true,8947 exact: false,8948 minimum: check2.value,8949 type: "date"8950 });8951 status.dirty();8952 }8953 } else if (check2.kind === "max") {8954 if (input.data.getTime() > check2.value) {8955 ctx = this._getOrReturnCtx(input, ctx);8956 addIssueToContext(ctx, {8957 code: ZodIssueCode.too_big,8958 message: check2.message,8959 inclusive: true,8960 exact: false,8961 maximum: check2.value,8962 type: "date"8963 });8964 status.dirty();8965 }8966 } else {8967 util.assertNever(check2);8968 }8969 }8970 return {8971 status: status.value,8972 value: new Date(input.data.getTime())8973 };8974 }8975 _addCheck(check2) {8976 return new _ZodDate({8977 ...this._def,8978 checks: [...this._def.checks, check2]8979 });8980 }8981 min(minDate, message) {8982 return this._addCheck({8983 kind: "min",8984 value: minDate.getTime(),8985 message: errorUtil.toString(message)8986 });8987 }8988 max(maxDate, message) {8989 return this._addCheck({8990 kind: "max",8991 value: maxDate.getTime(),8992 message: errorUtil.toString(message)8993 });8994 }8995 get minDate() {8996 let min = null;8997 for (const ch of this._def.checks) {8998 if (ch.kind === "min") {8999 if (min === null || ch.value > min)9000 min = ch.value;9001 }9002 }9003 return min != null ? new Date(min) : null;9004 }9005 get maxDate() {9006 let max = null;9007 for (const ch of this._def.checks) {9008 if (ch.kind === "max") {9009 if (max === null || ch.value < max)9010 max = ch.value;9011 }9012 }9013 return max != null ? new Date(max) : null;9014 }9015};9016ZodDate.create = (params) => {9017 return new ZodDate({9018 checks: [],9019 coerce: params?.coerce || false,9020 typeName: ZodFirstPartyTypeKind.ZodDate,9021 ...processCreateParams(params)9022 });9023};9024var ZodSymbol = class extends ZodType {9025 _parse(input) {9026 const parsedType2 = this._getType(input);9027 if (parsedType2 !== ZodParsedType.symbol) {9028 const ctx = this._getOrReturnCtx(input);9029 addIssueToContext(ctx, {9030 code: ZodIssueCode.invalid_type,9031 expected: ZodParsedType.symbol,9032 received: ctx.parsedType9033 });9034 return INVALID;9035 }9036 return OK(input.data);9037 }9038};9039ZodSymbol.create = (params) => {9040 return new ZodSymbol({9041 typeName: ZodFirstPartyTypeKind.ZodSymbol,9042 ...processCreateParams(params)9043 });9044};9045var ZodUndefined = class extends ZodType {9046 _parse(input) {9047 const parsedType2 = this._getType(input);9048 if (parsedType2 !== ZodParsedType.undefined) {9049 const ctx = this._getOrReturnCtx(input);9050 addIssueToContext(ctx, {9051 code: ZodIssueCode.invalid_type,9052 expected: ZodParsedType.undefined,9053 received: ctx.parsedType9054 });9055 return INVALID;9056 }9057 return OK(input.data);9058 }9059};9060ZodUndefined.create = (params) => {9061 return new ZodUndefined({9062 typeName: ZodFirstPartyTypeKind.ZodUndefined,9063 ...processCreateParams(params)9064 });9065};9066var ZodNull = class extends ZodType {9067 _parse(input) {9068 const parsedType2 = this._getType(input);9069 if (parsedType2 !== ZodParsedType.null) {9070 const ctx = this._getOrReturnCtx(input);9071 addIssueToContext(ctx, {9072 code: ZodIssueCode.invalid_type,9073 expected: ZodParsedType.null,9074 received: ctx.parsedType9075 });9076 return INVALID;9077 }9078 return OK(input.data);9079 }9080};9081ZodNull.create = (params) => {9082 return new ZodNull({9083 typeName: ZodFirstPartyTypeKind.ZodNull,9084 ...processCreateParams(params)9085 });9086};9087var ZodAny = class extends ZodType {9088 constructor() {9089 super(...arguments);9090 this._any = true;9091 }9092 _parse(input) {9093 return OK(input.data);9094 }9095};9096ZodAny.create = (params) => {9097 return new ZodAny({9098 typeName: ZodFirstPartyTypeKind.ZodAny,9099 ...processCreateParams(params)9100 });9101};9102var ZodUnknown = class extends ZodType {9103 constructor() {9104 super(...arguments);9105 this._unknown = true;9106 }9107 _parse(input) {9108 return OK(input.data);9109 }9110};9111ZodUnknown.create = (params) => {9112 return new ZodUnknown({9113 typeName: ZodFirstPartyTypeKind.ZodUnknown,9114 ...processCreateParams(params)9115 });9116};9117var ZodNever = class extends ZodType {9118 _parse(input) {9119 const ctx = this._getOrReturnCtx(input);9120 addIssueToContext(ctx, {9121 code: ZodIssueCode.invalid_type,9122 expected: ZodParsedType.never,9123 received: ctx.parsedType9124 });9125 return INVALID;9126 }9127};9128ZodNever.create = (params) => {9129 return new ZodNever({9130 typeName: ZodFirstPartyTypeKind.ZodNever,9131 ...processCreateParams(params)9132 });9133};9134var ZodVoid = class extends ZodType {9135 _parse(input) {9136 const parsedType2 = this._getType(input);9137 if (parsedType2 !== ZodParsedType.undefined) {9138 const ctx = this._getOrReturnCtx(input);9139 addIssueToContext(ctx, {9140 code: ZodIssueCode.invalid_type,9141 expected: ZodParsedType.void,9142 received: ctx.parsedType9143 });9144 return INVALID;9145 }9146 return OK(input.data);9147 }9148};9149ZodVoid.create = (params) => {9150 return new ZodVoid({9151 typeName: ZodFirstPartyTypeKind.ZodVoid,9152 ...processCreateParams(params)9153 });9154};9155var ZodArray = class _ZodArray extends ZodType {9156 _parse(input) {9157 const { ctx, status } = this._processInputParams(input);9158 const def = this._def;9159 if (ctx.parsedType !== ZodParsedType.array) {9160 addIssueToContext(ctx, {9161 code: ZodIssueCode.invalid_type,9162 expected: ZodParsedType.array,9163 received: ctx.parsedType9164 });9165 return INVALID;9166 }9167 if (def.exactLength !== null) {9168 const tooBig = ctx.data.length > def.exactLength.value;9169 const tooSmall = ctx.data.length < def.exactLength.value;9170 if (tooBig || tooSmall) {9171 addIssueToContext(ctx, {9172 code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,9173 minimum: tooSmall ? def.exactLength.value : void 0,9174 maximum: tooBig ? def.exactLength.value : void 0,9175 type: "array",9176 inclusive: true,9177 exact: true,9178 message: def.exactLength.message9179 });9180 status.dirty();9181 }9182 }9183 if (def.minLength !== null) {9184 if (ctx.data.length < def.minLength.value) {9185 addIssueToContext(ctx, {9186 code: ZodIssueCode.too_small,9187 minimum: def.minLength.value,9188 type: "array",9189 inclusive: true,9190 exact: false,9191 message: def.minLength.message9192 });9193 status.dirty();9194 }9195 }9196 if (def.maxLength !== null) {9197 if (ctx.data.length > def.maxLength.value) {9198 addIssueToContext(ctx, {9199 code: ZodIssueCode.too_big,9200 maximum: def.maxLength.value,9201 type: "array",9202 inclusive: true,9203 exact: false,9204 message: def.maxLength.message9205 });9206 status.dirty();9207 }9208 }9209 if (ctx.common.async) {9210 return Promise.all([...ctx.data].map((item, i) => {9211 return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));9212 })).then((result2) => {9213 return ParseStatus.mergeArray(status, result2);9214 });9215 }9216 const result = [...ctx.data].map((item, i) => {9217 return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));9218 });9219 return ParseStatus.mergeArray(status, result);9220 }9221 get element() {9222 return this._def.type;9223 }9224 min(minLength, message) {9225 return new _ZodArray({9226 ...this._def,9227 minLength: { value: minLength, message: errorUtil.toString(message) }9228 });9229 }9230 max(maxLength, message) {9231 return new _ZodArray({9232 ...this._def,9233 maxLength: { value: maxLength, message: errorUtil.toString(message) }9234 });9235 }9236 length(len, message) {9237 return new _ZodArray({9238 ...this._def,9239 exactLength: { value: len, message: errorUtil.toString(message) }9240 });9241 }9242 nonempty(message) {9243 return this.min(1, message);9244 }9245};9246ZodArray.create = (schema, params) => {9247 return new ZodArray({9248 type: schema,9249 minLength: null,9250 maxLength: null,9251 exactLength: null,9252 typeName: ZodFirstPartyTypeKind.ZodArray,9253 ...processCreateParams(params)9254 });9255};9256function deepPartialify(schema) {9257 if (schema instanceof ZodObject) {9258 const newShape = {};9259 for (const key in schema.shape) {9260 const fieldSchema = schema.shape[key];9261 newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));9262 }9263 return new ZodObject({9264 ...schema._def,9265 shape: () => newShape9266 });9267 } else if (schema instanceof ZodArray) {9268 return new ZodArray({9269 ...schema._def,9270 type: deepPartialify(schema.element)9271 });9272 } else if (schema instanceof ZodOptional) {9273 return ZodOptional.create(deepPartialify(schema.unwrap()));9274 } else if (schema instanceof ZodNullable) {9275 return ZodNullable.create(deepPartialify(schema.unwrap()));9276 } else if (schema instanceof ZodTuple) {9277 return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));9278 } else {9279 return schema;9280 }9281}9282var ZodObject = class _ZodObject extends ZodType {9283 constructor() {9284 super(...arguments);9285 this._cached = null;9286 this.nonstrict = this.passthrough;9287 this.augment = this.extend;9288 }9289 _getCached() {9290 if (this._cached !== null)9291 return this._cached;9292 const shape = this._def.shape();9293 const keys = util.objectKeys(shape);9294 this._cached = { shape, keys };9295 return this._cached;9296 }9297 _parse(input) {9298 const parsedType2 = this._getType(input);9299 if (parsedType2 !== ZodParsedType.object) {9300 const ctx2 = this._getOrReturnCtx(input);9301 addIssueToContext(ctx2, {9302 code: ZodIssueCode.invalid_type,9303 expected: ZodParsedType.object,9304 received: ctx2.parsedType9305 });9306 return INVALID;9307 }9308 const { status, ctx } = this._processInputParams(input);9309 const { shape, keys: shapeKeys } = this._getCached();9310 const extraKeys = [];9311 if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {9312 for (const key in ctx.data) {9313 if (!shapeKeys.includes(key)) {9314 extraKeys.push(key);9315 }9316 }9317 }9318 const pairs = [];9319 for (const key of shapeKeys) {9320 const keyValidator = shape[key];9321 const value = ctx.data[key];9322 pairs.push({9323 key: { status: "valid", value: key },9324 value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),9325 alwaysSet: key in ctx.data9326 });9327 }9328 if (this._def.catchall instanceof ZodNever) {9329 const unknownKeys = this._def.unknownKeys;9330 if (unknownKeys === "passthrough") {9331 for (const key of extraKeys) {9332 pairs.push({9333 key: { status: "valid", value: key },9334 value: { status: "valid", value: ctx.data[key] }9335 });9336 }9337 } else if (unknownKeys === "strict") {9338 if (extraKeys.length > 0) {9339 addIssueToContext(ctx, {9340 code: ZodIssueCode.unrecognized_keys,9341 keys: extraKeys9342 });9343 status.dirty();9344 }9345 } else if (unknownKeys === "strip") {9346 } else {9347 throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);9348 }9349 } else {9350 const catchall = this._def.catchall;9351 for (const key of extraKeys) {9352 const value = ctx.data[key];9353 pairs.push({9354 key: { status: "valid", value: key },9355 value: catchall._parse(9356 new ParseInputLazyPath(ctx, value, ctx.path, key)9357 //, ctx.child(key), value, getParsedType(value)9358 ),9359 alwaysSet: key in ctx.data9360 });9361 }9362 }9363 if (ctx.common.async) {9364 return Promise.resolve().then(async () => {9365 const syncPairs = [];9366 for (const pair of pairs) {9367 const key = await pair.key;9368 const value = await pair.value;9369 syncPairs.push({9370 key,9371 value,9372 alwaysSet: pair.alwaysSet9373 });9374 }9375 return syncPairs;9376 }).then((syncPairs) => {9377 return ParseStatus.mergeObjectSync(status, syncPairs);9378 });9379 } else {9380 return ParseStatus.mergeObjectSync(status, pairs);9381 }9382 }9383 get shape() {9384 return this._def.shape();9385 }9386 strict(message) {9387 errorUtil.errToObj;9388 return new _ZodObject({9389 ...this._def,9390 unknownKeys: "strict",9391 ...message !== void 0 ? {9392 errorMap: (issue2, ctx) => {9393 const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError;9394 if (issue2.code === "unrecognized_keys")9395 return {9396 message: errorUtil.errToObj(message).message ?? defaultError9397 };9398 return {9399 message: defaultError9400 };9401 }9402 } : {}9403 });9404 }9405 strip() {9406 return new _ZodObject({9407 ...this._def,9408 unknownKeys: "strip"9409 });9410 }9411 passthrough() {9412 return new _ZodObject({9413 ...this._def,9414 unknownKeys: "passthrough"9415 });9416 }9417 // const AugmentFactory =9418 // <Def extends ZodObjectDef>(def: Def) =>9419 // <Augmentation extends ZodRawShape>(9420 // augmentation: Augmentation9421 // ): ZodObject<9422 // extendShape<ReturnType<Def["shape"]>, Augmentation>,9423 // Def["unknownKeys"],9424 // Def["catchall"]9425 // > => {9426 // return new ZodObject({9427 // ...def,9428 // shape: () => ({9429 // ...def.shape(),9430 // ...augmentation,9431 // }),9432 // }) as any;9433 // };9434 extend(augmentation) {9435 return new _ZodObject({9436 ...this._def,9437 shape: () => ({9438 ...this._def.shape(),9439 ...augmentation9440 })9441 });9442 }9443 /**9444 * Prior to zod@1.0.12 there was a bug in the9445 * inferred type of merged objects. Please9446 * upgrade if you are experiencing issues.9447 */9448 merge(merging) {9449 const merged = new _ZodObject({9450 unknownKeys: merging._def.unknownKeys,9451 catchall: merging._def.catchall,9452 shape: () => ({9453 ...this._def.shape(),9454 ...merging._def.shape()9455 }),9456 typeName: ZodFirstPartyTypeKind.ZodObject9457 });9458 return merged;9459 }9460 // merge<9461 // Incoming extends AnyZodObject,9462 // Augmentation extends Incoming["shape"],9463 // NewOutput extends {9464 // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation9465 // ? Augmentation[k]["_output"]9466 // : k extends keyof Output9467 // ? Output[k]9468 // : never;9469 // },9470 // NewInput extends {9471 // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation9472 // ? Augmentation[k]["_input"]9473 // : k extends keyof Input9474 // ? Input[k]9475 // : never;9476 // }9477 // >(9478 // merging: Incoming9479 // ): ZodObject<9480 // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,9481 // Incoming["_def"]["unknownKeys"],9482 // Incoming["_def"]["catchall"],9483 // NewOutput,9484 // NewInput9485 // > {9486 // const merged: any = new ZodObject({9487 // unknownKeys: merging._def.unknownKeys,9488 // catchall: merging._def.catchall,9489 // shape: () =>9490 // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),9491 // typeName: ZodFirstPartyTypeKind.ZodObject,9492 // }) as any;9493 // return merged;9494 // }9495 setKey(key, schema) {9496 return this.augment({ [key]: schema });9497 }9498 // merge<Incoming extends AnyZodObject>(9499 // merging: Incoming9500 // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {9501 // ZodObject<9502 // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,9503 // Incoming["_def"]["unknownKeys"],9504 // Incoming["_def"]["catchall"]9505 // > {9506 // // const mergedShape = objectUtil.mergeShapes(9507 // // this._def.shape(),9508 // // merging._def.shape()9509 // // );9510 // const merged: any = new ZodObject({9511 // unknownKeys: merging._def.unknownKeys,9512 // catchall: merging._def.catchall,9513 // shape: () =>9514 // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),9515 // typeName: ZodFirstPartyTypeKind.ZodObject,9516 // }) as any;9517 // return merged;9518 // }9519 catchall(index) {9520 return new _ZodObject({9521 ...this._def,9522 catchall: index9523 });9524 }9525 pick(mask) {9526 const shape = {};9527 for (const key of util.objectKeys(mask)) {9528 if (mask[key] && this.shape[key]) {9529 shape[key] = this.shape[key];9530 }9531 }9532 return new _ZodObject({9533 ...this._def,9534 shape: () => shape9535 });9536 }9537 omit(mask) {9538 const shape = {};9539 for (const key of util.objectKeys(this.shape)) {9540 if (!mask[key]) {9541 shape[key] = this.shape[key];9542 }9543 }9544 return new _ZodObject({9545 ...this._def,9546 shape: () => shape9547 });9548 }9549 /**9550 * @deprecated9551 */9552 deepPartial() {9553 return deepPartialify(this);9554 }9555 partial(mask) {9556 const newShape = {};9557 for (const key of util.objectKeys(this.shape)) {9558 const fieldSchema = this.shape[key];9559 if (mask && !mask[key]) {9560 newShape[key] = fieldSchema;9561 } else {9562 newShape[key] = fieldSchema.optional();9563 }9564 }9565 return new _ZodObject({9566 ...this._def,9567 shape: () => newShape9568 });9569 }9570 required(mask) {9571 const newShape = {};9572 for (const key of util.objectKeys(this.shape)) {9573 if (mask && !mask[key]) {9574 newShape[key] = this.shape[key];9575 } else {9576 const fieldSchema = this.shape[key];9577 let newField = fieldSchema;9578 while (newField instanceof ZodOptional) {9579 newField = newField._def.innerType;9580 }9581 newShape[key] = newField;9582 }9583 }9584 return new _ZodObject({9585 ...this._def,9586 shape: () => newShape9587 });9588 }9589 keyof() {9590 return createZodEnum(util.objectKeys(this.shape));9591 }9592};9593ZodObject.create = (shape, params) => {9594 return new ZodObject({9595 shape: () => shape,9596 unknownKeys: "strip",9597 catchall: ZodNever.create(),9598 typeName: ZodFirstPartyTypeKind.ZodObject,9599 ...processCreateParams(params)9600 });9601};9602ZodObject.strictCreate = (shape, params) => {9603 return new ZodObject({9604 shape: () => shape,9605 unknownKeys: "strict",9606 catchall: ZodNever.create(),9607 typeName: ZodFirstPartyTypeKind.ZodObject,9608 ...processCreateParams(params)9609 });9610};9611ZodObject.lazycreate = (shape, params) => {9612 return new ZodObject({9613 shape,9614 unknownKeys: "strip",9615 catchall: ZodNever.create(),9616 typeName: ZodFirstPartyTypeKind.ZodObject,9617 ...processCreateParams(params)9618 });9619};9620var ZodUnion = class extends ZodType {9621 _parse(input) {9622 const { ctx } = this._processInputParams(input);9623 const options = this._def.options;9624 function handleResults(results) {9625 for (const result of results) {9626 if (result.result.status === "valid") {9627 return result.result;9628 }9629 }9630 for (const result of results) {9631 if (result.result.status === "dirty") {9632 ctx.common.issues.push(...result.ctx.common.issues);9633 return result.result;9634 }9635 }9636 const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));9637 addIssueToContext(ctx, {9638 code: ZodIssueCode.invalid_union,9639 unionErrors9640 });9641 return INVALID;9642 }9643 if (ctx.common.async) {9644 return Promise.all(options.map(async (option) => {9645 const childCtx = {9646 ...ctx,9647 common: {9648 ...ctx.common,9649 issues: []9650 },9651 parent: null9652 };9653 return {9654 result: await option._parseAsync({9655 data: ctx.data,9656 path: ctx.path,9657 parent: childCtx9658 }),9659 ctx: childCtx9660 };9661 })).then(handleResults);9662 } else {9663 let dirty = void 0;9664 const issues = [];9665 for (const option of options) {9666 const childCtx = {9667 ...ctx,9668 common: {9669 ...ctx.common,9670 issues: []9671 },9672 parent: null9673 };9674 const result = option._parseSync({9675 data: ctx.data,9676 path: ctx.path,9677 parent: childCtx9678 });9679 if (result.status === "valid") {9680 return result;9681 } else if (result.status === "dirty" && !dirty) {9682 dirty = { result, ctx: childCtx };9683 }9684 if (childCtx.common.issues.length) {9685 issues.push(childCtx.common.issues);9686 }9687 }9688 if (dirty) {9689 ctx.common.issues.push(...dirty.ctx.common.issues);9690 return dirty.result;9691 }9692 const unionErrors = issues.map((issues2) => new ZodError(issues2));9693 addIssueToContext(ctx, {9694 code: ZodIssueCode.invalid_union,9695 unionErrors9696 });9697 return INVALID;9698 }9699 }9700 get options() {9701 return this._def.options;9702 }9703};9704ZodUnion.create = (types, params) => {9705 return new ZodUnion({9706 options: types,9707 typeName: ZodFirstPartyTypeKind.ZodUnion,9708 ...processCreateParams(params)9709 });9710};9711var getDiscriminator = (type) => {9712 if (type instanceof ZodLazy) {9713 return getDiscriminator(type.schema);9714 } else if (type instanceof ZodEffects) {9715 return getDiscriminator(type.innerType());9716 } else if (type instanceof ZodLiteral) {9717 return [type.value];9718 } else if (type instanceof ZodEnum) {9719 return type.options;9720 } else if (type instanceof ZodNativeEnum) {9721 return util.objectValues(type.enum);9722 } else if (type instanceof ZodDefault) {9723 return getDiscriminator(type._def.innerType);9724 } else if (type instanceof ZodUndefined) {9725 return [void 0];9726 } else if (type instanceof ZodNull) {9727 return [null];9728 } else if (type instanceof ZodOptional) {9729 return [void 0, ...getDiscriminator(type.unwrap())];9730 } else if (type instanceof ZodNullable) {9731 return [null, ...getDiscriminator(type.unwrap())];9732 } else if (type instanceof ZodBranded) {9733 return getDiscriminator(type.unwrap());9734 } else if (type instanceof ZodReadonly) {9735 return getDiscriminator(type.unwrap());9736 } else if (type instanceof ZodCatch) {9737 return getDiscriminator(type._def.innerType);9738 } else {9739 return [];9740 }9741};9742var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {9743 _parse(input) {9744 const { ctx } = this._processInputParams(input);9745 if (ctx.parsedType !== ZodParsedType.object) {9746 addIssueToContext(ctx, {9747 code: ZodIssueCode.invalid_type,9748 expected: ZodParsedType.object,9749 received: ctx.parsedType9750 });9751 return INVALID;9752 }9753 const discriminator = this.discriminator;9754 const discriminatorValue = ctx.data[discriminator];9755 const option = this.optionsMap.get(discriminatorValue);9756 if (!option) {9757 addIssueToContext(ctx, {9758 code: ZodIssueCode.invalid_union_discriminator,9759 options: Array.from(this.optionsMap.keys()),9760 path: [discriminator]9761 });9762 return INVALID;9763 }9764 if (ctx.common.async) {9765 return option._parseAsync({9766 data: ctx.data,9767 path: ctx.path,9768 parent: ctx9769 });9770 } else {9771 return option._parseSync({9772 data: ctx.data,9773 path: ctx.path,9774 parent: ctx9775 });9776 }9777 }9778 get discriminator() {9779 return this._def.discriminator;9780 }9781 get options() {9782 return this._def.options;9783 }9784 get optionsMap() {9785 return this._def.optionsMap;9786 }9787 /**9788 * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.9789 * However, it only allows a union of objects, all of which need to share a discriminator property. This property must9790 * have a different value for each object in the union.9791 * @param discriminator the name of the discriminator property9792 * @param types an array of object schemas9793 * @param params9794 */9795 static create(discriminator, options, params) {9796 const optionsMap = /* @__PURE__ */ new Map();9797 for (const type of options) {9798 const discriminatorValues = getDiscriminator(type.shape[discriminator]);9799 if (!discriminatorValues.length) {9800 throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);9801 }9802 for (const value of discriminatorValues) {9803 if (optionsMap.has(value)) {9804 throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);9805 }9806 optionsMap.set(value, type);9807 }9808 }9809 return new _ZodDiscriminatedUnion({9810 typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,9811 discriminator,9812 options,9813 optionsMap,9814 ...processCreateParams(params)9815 });9816 }9817};9818function mergeValues(a, b) {9819 const aType = getParsedType(a);9820 const bType = getParsedType(b);9821 if (a === b) {9822 return { valid: true, data: a };9823 } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {9824 const bKeys = util.objectKeys(b);9825 const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);9826 const newObj = { ...a, ...b };9827 for (const key of sharedKeys) {9828 const sharedValue = mergeValues(a[key], b[key]);9829 if (!sharedValue.valid) {9830 return { valid: false };9831 }9832 newObj[key] = sharedValue.data;9833 }9834 return { valid: true, data: newObj };9835 } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {9836 if (a.length !== b.length) {9837 return { valid: false };9838 }9839 const newArray = [];9840 for (let index = 0; index < a.length; index++) {9841 const itemA = a[index];9842 const itemB = b[index];9843 const sharedValue = mergeValues(itemA, itemB);9844 if (!sharedValue.valid) {9845 return { valid: false };9846 }9847 newArray.push(sharedValue.data);9848 }9849 return { valid: true, data: newArray };9850 } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {9851 return { valid: true, data: a };9852 } else {9853 return { valid: false };9854 }9855}9856var ZodIntersection = class extends ZodType {9857 _parse(input) {9858 const { status, ctx } = this._processInputParams(input);9859 const handleParsed = (parsedLeft, parsedRight) => {9860 if (isAborted(parsedLeft) || isAborted(parsedRight)) {9861 return INVALID;9862 }9863 const merged = mergeValues(parsedLeft.value, parsedRight.value);9864 if (!merged.valid) {9865 addIssueToContext(ctx, {9866 code: ZodIssueCode.invalid_intersection_types9867 });9868 return INVALID;9869 }9870 if (isDirty(parsedLeft) || isDirty(parsedRight)) {9871 status.dirty();9872 }9873 return { status: status.value, value: merged.data };9874 };9875 if (ctx.common.async) {9876 return Promise.all([9877 this._def.left._parseAsync({9878 data: ctx.data,9879 path: ctx.path,9880 parent: ctx9881 }),9882 this._def.right._parseAsync({9883 data: ctx.data,9884 path: ctx.path,9885 parent: ctx9886 })9887 ]).then(([left, right]) => handleParsed(left, right));9888 } else {9889 return handleParsed(this._def.left._parseSync({9890 data: ctx.data,9891 path: ctx.path,9892 parent: ctx9893 }), this._def.right._parseSync({9894 data: ctx.data,9895 path: ctx.path,9896 parent: ctx9897 }));9898 }9899 }9900};9901ZodIntersection.create = (left, right, params) => {9902 return new ZodIntersection({9903 left,9904 right,9905 typeName: ZodFirstPartyTypeKind.ZodIntersection,9906 ...processCreateParams(params)9907 });9908};9909var ZodTuple = class _ZodTuple extends ZodType {9910 _parse(input) {9911 const { status, ctx } = this._processInputParams(input);9912 if (ctx.parsedType !== ZodParsedType.array) {9913 addIssueToContext(ctx, {9914 code: ZodIssueCode.invalid_type,9915 expected: ZodParsedType.array,9916 received: ctx.parsedType9917 });9918 return INVALID;9919 }9920 if (ctx.data.length < this._def.items.length) {9921 addIssueToContext(ctx, {9922 code: ZodIssueCode.too_small,9923 minimum: this._def.items.length,9924 inclusive: true,9925 exact: false,9926 type: "array"9927 });9928 return INVALID;9929 }9930 const rest = this._def.rest;9931 if (!rest && ctx.data.length > this._def.items.length) {9932 addIssueToContext(ctx, {9933 code: ZodIssueCode.too_big,9934 maximum: this._def.items.length,9935 inclusive: true,9936 exact: false,9937 type: "array"9938 });9939 status.dirty();9940 }9941 const items = [...ctx.data].map((item, itemIndex) => {9942 const schema = this._def.items[itemIndex] || this._def.rest;9943 if (!schema)9944 return null;9945 return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));9946 }).filter((x) => !!x);9947 if (ctx.common.async) {9948 return Promise.all(items).then((results) => {9949 return ParseStatus.mergeArray(status, results);9950 });9951 } else {9952 return ParseStatus.mergeArray(status, items);9953 }9954 }9955 get items() {9956 return this._def.items;9957 }9958 rest(rest) {9959 return new _ZodTuple({9960 ...this._def,9961 rest9962 });9963 }9964};9965ZodTuple.create = (schemas, params) => {9966 if (!Array.isArray(schemas)) {9967 throw new Error("You must pass an array of schemas to z.tuple([ ... ])");9968 }9969 return new ZodTuple({9970 items: schemas,9971 typeName: ZodFirstPartyTypeKind.ZodTuple,9972 rest: null,9973 ...processCreateParams(params)9974 });9975};9976var ZodRecord = class _ZodRecord extends ZodType {9977 get keySchema() {9978 return this._def.keyType;9979 }9980 get valueSchema() {9981 return this._def.valueType;9982 }9983 _parse(input) {9984 const { status, ctx } = this._processInputParams(input);9985 if (ctx.parsedType !== ZodParsedType.object) {9986 addIssueToContext(ctx, {9987 code: ZodIssueCode.invalid_type,9988 expected: ZodParsedType.object,9989 received: ctx.parsedType9990 });9991 return INVALID;9992 }9993 const pairs = [];9994 const keyType = this._def.keyType;9995 const valueType = this._def.valueType;9996 for (const key in ctx.data) {9997 pairs.push({9998 key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),9999 value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),10000 alwaysSet: key in ctx.data10001 });10002 }10003 if (ctx.common.async) {10004 return ParseStatus.mergeObjectAsync(status, pairs);10005 } else {10006 return ParseStatus.mergeObjectSync(status, pairs);10007 }10008 }10009 get element() {10010 return this._def.valueType;10011 }10012 static create(first, second, third) {10013 if (second instanceof ZodType) {10014 return new _ZodRecord({10015 keyType: first,10016 valueType: second,10017 typeName: ZodFirstPartyTypeKind.ZodRecord,10018 ...processCreateParams(third)10019 });10020 }10021 return new _ZodRecord({10022 keyType: ZodString.create(),10023 valueType: first,10024 typeName: ZodFirstPartyTypeKind.ZodRecord,10025 ...processCreateParams(second)10026 });10027 }10028};10029var ZodMap = class extends ZodType {10030 get keySchema() {10031 return this._def.keyType;10032 }10033 get valueSchema() {10034 return this._def.valueType;10035 }10036 _parse(input) {10037 const { status, ctx } = this._processInputParams(input);10038 if (ctx.parsedType !== ZodParsedType.map) {10039 addIssueToContext(ctx, {10040 code: ZodIssueCode.invalid_type,10041 expected: ZodParsedType.map,10042 received: ctx.parsedType10043 });10044 return INVALID;10045 }10046 const keyType = this._def.keyType;10047 const valueType = this._def.valueType;10048 const pairs = [...ctx.data.entries()].map(([key, value], index) => {10049 return {10050 key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),10051 value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))10052 };10053 });10054 if (ctx.common.async) {10055 const finalMap = /* @__PURE__ */ new Map();10056 return Promise.resolve().then(async () => {10057 for (const pair of pairs) {10058 const key = await pair.key;10059 const value = await pair.value;10060 if (key.status === "aborted" || value.status === "aborted") {10061 return INVALID;10062 }10063 if (key.status === "dirty" || value.status === "dirty") {10064 status.dirty();10065 }10066 finalMap.set(key.value, value.value);10067 }10068 return { status: status.value, value: finalMap };10069 });10070 } else {10071 const finalMap = /* @__PURE__ */ new Map();10072 for (const pair of pairs) {10073 const key = pair.key;10074 const value = pair.value;10075 if (key.status === "aborted" || value.status === "aborted") {10076 return INVALID;10077 }10078 if (key.status === "dirty" || value.status === "dirty") {10079 status.dirty();10080 }10081 finalMap.set(key.value, value.value);10082 }10083 return { status: status.value, value: finalMap };10084 }10085 }10086};10087ZodMap.create = (keyType, valueType, params) => {10088 return new ZodMap({10089 valueType,10090 keyType,10091 typeName: ZodFirstPartyTypeKind.ZodMap,10092 ...processCreateParams(params)10093 });10094};10095var ZodSet = class _ZodSet extends ZodType {10096 _parse(input) {10097 const { status, ctx } = this._processInputParams(input);10098 if (ctx.parsedType !== ZodParsedType.set) {10099 addIssueToContext(ctx, {10100 code: ZodIssueCode.invalid_type,10101 expected: ZodParsedType.set,10102 received: ctx.parsedType10103 });10104 return INVALID;10105 }10106 const def = this._def;10107 if (def.minSize !== null) {10108 if (ctx.data.size < def.minSize.value) {10109 addIssueToContext(ctx, {10110 code: ZodIssueCode.too_small,10111 minimum: def.minSize.value,10112 type: "set",10113 inclusive: true,10114 exact: false,10115 message: def.minSize.message10116 });10117 status.dirty();10118 }10119 }10120 if (def.maxSize !== null) {10121 if (ctx.data.size > def.maxSize.value) {10122 addIssueToContext(ctx, {10123 code: ZodIssueCode.too_big,10124 maximum: def.maxSize.value,10125 type: "set",10126 inclusive: true,10127 exact: false,10128 message: def.maxSize.message10129 });10130 status.dirty();10131 }10132 }10133 const valueType = this._def.valueType;10134 function finalizeSet(elements2) {10135 const parsedSet = /* @__PURE__ */ new Set();10136 for (const element of elements2) {10137 if (element.status === "aborted")10138 return INVALID;10139 if (element.status === "dirty")10140 status.dirty();10141 parsedSet.add(element.value);10142 }10143 return { status: status.value, value: parsedSet };10144 }10145 const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));10146 if (ctx.common.async) {10147 return Promise.all(elements).then((elements2) => finalizeSet(elements2));10148 } else {10149 return finalizeSet(elements);10150 }10151 }10152 min(minSize, message) {10153 return new _ZodSet({10154 ...this._def,10155 minSize: { value: minSize, message: errorUtil.toString(message) }10156 });10157 }10158 max(maxSize, message) {10159 return new _ZodSet({10160 ...this._def,10161 maxSize: { value: maxSize, message: errorUtil.toString(message) }10162 });10163 }10164 size(size, message) {10165 return this.min(size, message).max(size, message);10166 }10167 nonempty(message) {10168 return this.min(1, message);10169 }10170};10171ZodSet.create = (valueType, params) => {10172 return new ZodSet({10173 valueType,10174 minSize: null,10175 maxSize: null,10176 typeName: ZodFirstPartyTypeKind.ZodSet,10177 ...processCreateParams(params)10178 });10179};10180var ZodFunction = class _ZodFunction extends ZodType {10181 constructor() {10182 super(...arguments);10183 this.validate = this.implement;10184 }10185 _parse(input) {10186 const { ctx } = this._processInputParams(input);10187 if (ctx.parsedType !== ZodParsedType.function) {10188 addIssueToContext(ctx, {10189 code: ZodIssueCode.invalid_type,10190 expected: ZodParsedType.function,10191 received: ctx.parsedType10192 });10193 return INVALID;10194 }10195 function makeArgsIssue(args, error2) {10196 return makeIssue({10197 data: args,10198 path: ctx.path,10199 errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),10200 issueData: {10201 code: ZodIssueCode.invalid_arguments,10202 argumentsError: error210203 }10204 });10205 }10206 function makeReturnsIssue(returns, error2) {10207 return makeIssue({10208 data: returns,10209 path: ctx.path,10210 errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),10211 issueData: {10212 code: ZodIssueCode.invalid_return_type,10213 returnTypeError: error210214 }10215 });10216 }10217 const params = { errorMap: ctx.common.contextualErrorMap };10218 const fn = ctx.data;10219 if (this._def.returns instanceof ZodPromise) {10220 const me = this;10221 return OK(async function(...args) {10222 const error2 = new ZodError([]);10223 const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {10224 error2.addIssue(makeArgsIssue(args, e));10225 throw error2;10226 });10227 const result = await Reflect.apply(fn, this, parsedArgs);10228 const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {10229 error2.addIssue(makeReturnsIssue(result, e));10230 throw error2;10231 });10232 return parsedReturns;10233 });10234 } else {10235 const me = this;10236 return OK(function(...args) {10237 const parsedArgs = me._def.args.safeParse(args, params);10238 if (!parsedArgs.success) {10239 throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);10240 }10241 const result = Reflect.apply(fn, this, parsedArgs.data);10242 const parsedReturns = me._def.returns.safeParse(result, params);10243 if (!parsedReturns.success) {10244 throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);10245 }10246 return parsedReturns.data;10247 });10248 }10249 }10250 parameters() {10251 return this._def.args;10252 }10253 returnType() {10254 return this._def.returns;10255 }10256 args(...items) {10257 return new _ZodFunction({10258 ...this._def,10259 args: ZodTuple.create(items).rest(ZodUnknown.create())10260 });10261 }10262 returns(returnType) {10263 return new _ZodFunction({10264 ...this._def,10265 returns: returnType10266 });10267 }10268 implement(func) {10269 const validatedFunc = this.parse(func);10270 return validatedFunc;10271 }10272 strictImplement(func) {10273 const validatedFunc = this.parse(func);10274 return validatedFunc;10275 }10276 static create(args, returns, params) {10277 return new _ZodFunction({10278 args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),10279 returns: returns || ZodUnknown.create(),10280 typeName: ZodFirstPartyTypeKind.ZodFunction,10281 ...processCreateParams(params)10282 });10283 }10284};10285var ZodLazy = class extends ZodType {10286 get schema() {10287 return this._def.getter();10288 }10289 _parse(input) {10290 const { ctx } = this._processInputParams(input);10291 const lazySchema = this._def.getter();10292 return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });10293 }10294};10295ZodLazy.create = (getter, params) => {10296 return new ZodLazy({10297 getter,10298 typeName: ZodFirstPartyTypeKind.ZodLazy,10299 ...processCreateParams(params)10300 });10301};10302var ZodLiteral = class extends ZodType {10303 _parse(input) {10304 if (input.data !== this._def.value) {10305 const ctx = this._getOrReturnCtx(input);10306 addIssueToContext(ctx, {10307 received: ctx.data,10308 code: ZodIssueCode.invalid_literal,10309 expected: this._def.value10310 });10311 return INVALID;10312 }10313 return { status: "valid", value: input.data };10314 }10315 get value() {10316 return this._def.value;10317 }10318};10319ZodLiteral.create = (value, params) => {10320 return new ZodLiteral({10321 value,10322 typeName: ZodFirstPartyTypeKind.ZodLiteral,10323 ...processCreateParams(params)10324 });10325};10326function createZodEnum(values, params) {10327 return new ZodEnum({10328 values,10329 typeName: ZodFirstPartyTypeKind.ZodEnum,10330 ...processCreateParams(params)10331 });10332}10333var ZodEnum = class _ZodEnum extends ZodType {10334 _parse(input) {10335 if (typeof input.data !== "string") {10336 const ctx = this._getOrReturnCtx(input);10337 const expectedValues = this._def.values;10338 addIssueToContext(ctx, {10339 expected: util.joinValues(expectedValues),10340 received: ctx.parsedType,10341 code: ZodIssueCode.invalid_type10342 });10343 return INVALID;10344 }10345 if (!this._cache) {10346 this._cache = new Set(this._def.values);10347 }10348 if (!this._cache.has(input.data)) {10349 const ctx = this._getOrReturnCtx(input);10350 const expectedValues = this._def.values;10351 addIssueToContext(ctx, {10352 received: ctx.data,10353 code: ZodIssueCode.invalid_enum_value,10354 options: expectedValues10355 });10356 return INVALID;10357 }10358 return OK(input.data);10359 }10360 get options() {10361 return this._def.values;10362 }10363 get enum() {10364 const enumValues = {};10365 for (const val of this._def.values) {10366 enumValues[val] = val;10367 }10368 return enumValues;10369 }10370 get Values() {10371 const enumValues = {};10372 for (const val of this._def.values) {10373 enumValues[val] = val;10374 }10375 return enumValues;10376 }10377 get Enum() {10378 const enumValues = {};10379 for (const val of this._def.values) {10380 enumValues[val] = val;10381 }10382 return enumValues;10383 }10384 extract(values, newDef = this._def) {10385 return _ZodEnum.create(values, {10386 ...this._def,10387 ...newDef10388 });10389 }10390 exclude(values, newDef = this._def) {10391 return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {10392 ...this._def,10393 ...newDef10394 });10395 }10396};10397ZodEnum.create = createZodEnum;10398var ZodNativeEnum = class extends ZodType {10399 _parse(input) {10400 const nativeEnumValues = util.getValidEnumValues(this._def.values);10401 const ctx = this._getOrReturnCtx(input);10402 if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {10403 const expectedValues = util.objectValues(nativeEnumValues);10404 addIssueToContext(ctx, {10405 expected: util.joinValues(expectedValues),10406 received: ctx.parsedType,10407 code: ZodIssueCode.invalid_type10408 });10409 return INVALID;10410 }10411 if (!this._cache) {10412 this._cache = new Set(util.getValidEnumValues(this._def.values));10413 }10414 if (!this._cache.has(input.data)) {10415 const expectedValues = util.objectValues(nativeEnumValues);10416 addIssueToContext(ctx, {10417 received: ctx.data,10418 code: ZodIssueCode.invalid_enum_value,10419 options: expectedValues10420 });10421 return INVALID;10422 }10423 return OK(input.data);10424 }10425 get enum() {10426 return this._def.values;10427 }10428};10429ZodNativeEnum.create = (values, params) => {10430 return new ZodNativeEnum({10431 values,10432 typeName: ZodFirstPartyTypeKind.ZodNativeEnum,10433 ...processCreateParams(params)10434 });10435};10436var ZodPromise = class extends ZodType {10437 unwrap() {10438 return this._def.type;10439 }10440 _parse(input) {10441 const { ctx } = this._processInputParams(input);10442 if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {10443 addIssueToContext(ctx, {10444 code: ZodIssueCode.invalid_type,10445 expected: ZodParsedType.promise,10446 received: ctx.parsedType10447 });10448 return INVALID;10449 }10450 const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);10451 return OK(promisified.then((data) => {10452 return this._def.type.parseAsync(data, {10453 path: ctx.path,10454 errorMap: ctx.common.contextualErrorMap10455 });10456 }));10457 }10458};10459ZodPromise.create = (schema, params) => {10460 return new ZodPromise({10461 type: schema,10462 typeName: ZodFirstPartyTypeKind.ZodPromise,10463 ...processCreateParams(params)10464 });10465};10466var ZodEffects = class extends ZodType {10467 innerType() {10468 return this._def.schema;10469 }10470 sourceType() {10471 return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;10472 }10473 _parse(input) {10474 const { status, ctx } = this._processInputParams(input);10475 const effect = this._def.effect || null;10476 const checkCtx = {10477 addIssue: (arg) => {10478 addIssueToContext(ctx, arg);10479 if (arg.fatal) {10480 status.abort();10481 } else {10482 status.dirty();10483 }10484 },10485 get path() {10486 return ctx.path;10487 }10488 };10489 checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);10490 if (effect.type === "preprocess") {10491 const processed = effect.transform(ctx.data, checkCtx);10492 if (ctx.common.async) {10493 return Promise.resolve(processed).then(async (processed2) => {10494 if (status.value === "aborted")10495 return INVALID;10496 const result = await this._def.schema._parseAsync({10497 data: processed2,10498 path: ctx.path,10499 parent: ctx10500 });10501 if (result.status === "aborted")10502 return INVALID;10503 if (result.status === "dirty")10504 return DIRTY(result.value);10505 if (status.value === "dirty")10506 return DIRTY(result.value);10507 return result;10508 });10509 } else {10510 if (status.value === "aborted")10511 return INVALID;10512 const result = this._def.schema._parseSync({10513 data: processed,10514 path: ctx.path,10515 parent: ctx10516 });10517 if (result.status === "aborted")10518 return INVALID;10519 if (result.status === "dirty")10520 return DIRTY(result.value);10521 if (status.value === "dirty")10522 return DIRTY(result.value);10523 return result;10524 }10525 }10526 if (effect.type === "refinement") {10527 const executeRefinement = (acc) => {10528 const result = effect.refinement(acc, checkCtx);10529 if (ctx.common.async) {10530 return Promise.resolve(result);10531 }10532 if (result instanceof Promise) {10533 throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");10534 }10535 return acc;10536 };10537 if (ctx.common.async === false) {10538 const inner = this._def.schema._parseSync({10539 data: ctx.data,10540 path: ctx.path,10541 parent: ctx10542 });10543 if (inner.status === "aborted")10544 return INVALID;10545 if (inner.status === "dirty")10546 status.dirty();10547 executeRefinement(inner.value);10548 return { status: status.value, value: inner.value };10549 } else {10550 return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {10551 if (inner.status === "aborted")10552 return INVALID;10553 if (inner.status === "dirty")10554 status.dirty();10555 return executeRefinement(inner.value).then(() => {10556 return { status: status.value, value: inner.value };10557 });10558 });10559 }10560 }10561 if (effect.type === "transform") {10562 if (ctx.common.async === false) {10563 const base = this._def.schema._parseSync({10564 data: ctx.data,10565 path: ctx.path,10566 parent: ctx10567 });10568 if (!isValid(base))10569 return INVALID;10570 const result = effect.transform(base.value, checkCtx);10571 if (result instanceof Promise) {10572 throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);10573 }10574 return { status: status.value, value: result };10575 } else {10576 return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {10577 if (!isValid(base))10578 return INVALID;10579 return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({10580 status: status.value,10581 value: result10582 }));10583 });10584 }10585 }10586 util.assertNever(effect);10587 }10588};10589ZodEffects.create = (schema, effect, params) => {10590 return new ZodEffects({10591 schema,10592 typeName: ZodFirstPartyTypeKind.ZodEffects,10593 effect,10594 ...processCreateParams(params)10595 });10596};10597ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {10598 return new ZodEffects({10599 schema,10600 effect: { type: "preprocess", transform: preprocess2 },10601 typeName: ZodFirstPartyTypeKind.ZodEffects,10602 ...processCreateParams(params)10603 });10604};10605var ZodOptional = class extends ZodType {10606 _parse(input) {10607 const parsedType2 = this._getType(input);10608 if (parsedType2 === ZodParsedType.undefined) {10609 return OK(void 0);10610 }10611 return this._def.innerType._parse(input);10612 }10613 unwrap() {10614 return this._def.innerType;10615 }10616};10617ZodOptional.create = (type, params) => {10618 return new ZodOptional({10619 innerType: type,10620 typeName: ZodFirstPartyTypeKind.ZodOptional,10621 ...processCreateParams(params)10622 });10623};10624var ZodNullable = class extends ZodType {10625 _parse(input) {10626 const parsedType2 = this._getType(input);10627 if (parsedType2 === ZodParsedType.null) {10628 return OK(null);10629 }10630 return this._def.innerType._parse(input);10631 }10632 unwrap() {10633 return this._def.innerType;10634 }10635};10636ZodNullable.create = (type, params) => {10637 return new ZodNullable({10638 innerType: type,10639 typeName: ZodFirstPartyTypeKind.ZodNullable,10640 ...processCreateParams(params)10641 });10642};10643var ZodDefault = class extends ZodType {10644 _parse(input) {10645 const { ctx } = this._processInputParams(input);10646 let data = ctx.data;10647 if (ctx.parsedType === ZodParsedType.undefined) {10648 data = this._def.defaultValue();10649 }10650 return this._def.innerType._parse({10651 data,10652 path: ctx.path,10653 parent: ctx10654 });10655 }10656 removeDefault() {10657 return this._def.innerType;10658 }10659};10660ZodDefault.create = (type, params) => {10661 return new ZodDefault({10662 innerType: type,10663 typeName: ZodFirstPartyTypeKind.ZodDefault,10664 defaultValue: typeof params.default === "function" ? params.default : () => params.default,10665 ...processCreateParams(params)10666 });10667};10668var ZodCatch = class extends ZodType {10669 _parse(input) {10670 const { ctx } = this._processInputParams(input);10671 const newCtx = {10672 ...ctx,10673 common: {10674 ...ctx.common,10675 issues: []10676 }10677 };10678 const result = this._def.innerType._parse({10679 data: newCtx.data,10680 path: newCtx.path,10681 parent: {10682 ...newCtx10683 }10684 });10685 if (isAsync(result)) {10686 return result.then((result2) => {10687 return {10688 status: "valid",10689 value: result2.status === "valid" ? result2.value : this._def.catchValue({10690 get error() {10691 return new ZodError(newCtx.common.issues);10692 },10693 input: newCtx.data10694 })10695 };10696 });10697 } else {10698 return {10699 status: "valid",10700 value: result.status === "valid" ? result.value : this._def.catchValue({10701 get error() {10702 return new ZodError(newCtx.common.issues);10703 },10704 input: newCtx.data10705 })10706 };10707 }10708 }10709 removeCatch() {10710 return this._def.innerType;10711 }10712};10713ZodCatch.create = (type, params) => {10714 return new ZodCatch({10715 innerType: type,10716 typeName: ZodFirstPartyTypeKind.ZodCatch,10717 catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,10718 ...processCreateParams(params)10719 });10720};10721var ZodNaN = class extends ZodType {10722 _parse(input) {10723 const parsedType2 = this._getType(input);10724 if (parsedType2 !== ZodParsedType.nan) {10725 const ctx = this._getOrReturnCtx(input);10726 addIssueToContext(ctx, {10727 code: ZodIssueCode.invalid_type,10728 expected: ZodParsedType.nan,10729 received: ctx.parsedType10730 });10731 return INVALID;10732 }10733 return { status: "valid", value: input.data };10734 }10735};10736ZodNaN.create = (params) => {10737 return new ZodNaN({10738 typeName: ZodFirstPartyTypeKind.ZodNaN,10739 ...processCreateParams(params)10740 });10741};10742var BRAND = Symbol("zod_brand");10743var ZodBranded = class extends ZodType {10744 _parse(input) {10745 const { ctx } = this._processInputParams(input);10746 const data = ctx.data;10747 return this._def.type._parse({10748 data,10749 path: ctx.path,10750 parent: ctx10751 });10752 }10753 unwrap() {10754 return this._def.type;10755 }10756};10757var ZodPipeline = class _ZodPipeline extends ZodType {10758 _parse(input) {10759 const { status, ctx } = this._processInputParams(input);10760 if (ctx.common.async) {10761 const handleAsync = async () => {10762 const inResult = await this._def.in._parseAsync({10763 data: ctx.data,10764 path: ctx.path,10765 parent: ctx10766 });10767 if (inResult.status === "aborted")10768 return INVALID;10769 if (inResult.status === "dirty") {10770 status.dirty();10771 return DIRTY(inResult.value);10772 } else {10773 return this._def.out._parseAsync({10774 data: inResult.value,10775 path: ctx.path,10776 parent: ctx10777 });10778 }10779 };10780 return handleAsync();10781 } else {10782 const inResult = this._def.in._parseSync({10783 data: ctx.data,10784 path: ctx.path,10785 parent: ctx10786 });10787 if (inResult.status === "aborted")10788 return INVALID;10789 if (inResult.status === "dirty") {10790 status.dirty();10791 return {10792 status: "dirty",10793 value: inResult.value10794 };10795 } else {10796 return this._def.out._parseSync({10797 data: inResult.value,10798 path: ctx.path,10799 parent: ctx10800 });10801 }10802 }10803 }10804 static create(a, b) {10805 return new _ZodPipeline({10806 in: a,10807 out: b,10808 typeName: ZodFirstPartyTypeKind.ZodPipeline10809 });10810 }10811};10812var ZodReadonly = class extends ZodType {10813 _parse(input) {10814 const result = this._def.innerType._parse(input);10815 const freeze = (data) => {10816 if (isValid(data)) {10817 data.value = Object.freeze(data.value);10818 }10819 return data;10820 };10821 return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);10822 }10823 unwrap() {10824 return this._def.innerType;10825 }10826};10827ZodReadonly.create = (type, params) => {10828 return new ZodReadonly({10829 innerType: type,10830 typeName: ZodFirstPartyTypeKind.ZodReadonly,10831 ...processCreateParams(params)10832 });10833};10834function cleanParams(params, data) {10835 const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;10836 const p2 = typeof p === "string" ? { message: p } : p;10837 return p2;10838}10839function custom(check2, _params = {}, fatal) {10840 if (check2)10841 return ZodAny.create().superRefine((data, ctx) => {10842 const r = check2(data);10843 if (r instanceof Promise) {10844 return r.then((r2) => {10845 if (!r2) {10846 const params = cleanParams(_params, data);10847 const _fatal = params.fatal ?? fatal ?? true;10848 ctx.addIssue({ code: "custom", ...params, fatal: _fatal });10849 }10850 });10851 }10852 if (!r) {10853 const params = cleanParams(_params, data);10854 const _fatal = params.fatal ?? fatal ?? true;10855 ctx.addIssue({ code: "custom", ...params, fatal: _fatal });10856 }10857 return;10858 });10859 return ZodAny.create();10860}10861var late = {10862 object: ZodObject.lazycreate10863};10864var ZodFirstPartyTypeKind;10865(function(ZodFirstPartyTypeKind2) {10866 ZodFirstPartyTypeKind2["ZodString"] = "ZodString";10867 ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";10868 ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";10869 ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";10870 ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";10871 ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";10872 ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";10873 ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";10874 ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";10875 ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";10876 ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";10877 ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";10878 ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";10879 ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";10880 ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";10881 ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";10882 ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";10883 ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";10884 ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";10885 ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";10886 ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";10887 ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";10888 ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";10889 ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";10890 ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";10891 ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";10892 ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";10893 ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";10894 ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";10895 ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";10896 ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";10897 ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";10898 ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";10899 ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";10900 ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";10901 ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";10902})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));10903var instanceOfType = (cls, params = {10904 message: `Input not instance of ${cls.name}`10905}) => custom((data) => data instanceof cls, params);10906var stringType = ZodString.create;10907var numberType = ZodNumber.create;10908var nanType = ZodNaN.create;10909var bigIntType = ZodBigInt.create;10910var booleanType = ZodBoolean.create;10911var dateType = ZodDate.create;10912var symbolType = ZodSymbol.create;10913var undefinedType = ZodUndefined.create;10914var nullType = ZodNull.create;10915var anyType = ZodAny.create;10916var unknownType = ZodUnknown.create;10917var neverType = ZodNever.create;10918var voidType = ZodVoid.create;10919var arrayType = ZodArray.create;10920var objectType = ZodObject.create;10921var strictObjectType = ZodObject.strictCreate;10922var unionType = ZodUnion.create;10923var discriminatedUnionType = ZodDiscriminatedUnion.create;10924var intersectionType = ZodIntersection.create;10925var tupleType = ZodTuple.create;10926var recordType = ZodRecord.create;10927var mapType = ZodMap.create;10928var setType = ZodSet.create;10929var functionType = ZodFunction.create;10930var lazyType = ZodLazy.create;10931var literalType = ZodLiteral.create;10932var enumType = ZodEnum.create;10933var nativeEnumType = ZodNativeEnum.create;10934var promiseType = ZodPromise.create;10935var effectsType = ZodEffects.create;10936var optionalType = ZodOptional.create;10937var nullableType = ZodNullable.create;10938var preprocessType = ZodEffects.createWithPreprocess;10939var pipelineType = ZodPipeline.create;10940var ostring = () => stringType().optional();10941var onumber = () => numberType().optional();10942var oboolean = () => booleanType().optional();10943var coerce = {10944 string: (arg) => ZodString.create({ ...arg, coerce: true }),10945 number: (arg) => ZodNumber.create({ ...arg, coerce: true }),10946 boolean: (arg) => ZodBoolean.create({10947 ...arg,10948 coerce: true10949 }),10950 bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),10951 date: (arg) => ZodDate.create({ ...arg, coerce: true })10952};10953var NEVER = INVALID;1095410955// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js10956var NEVER2 = Object.freeze({10957 status: "aborted"10958});10959// @__NO_SIDE_EFFECTS__10960function $constructor(name, initializer3, params) {10961 function init(inst, def) {10962 var _a;10963 Object.defineProperty(inst, "_zod", {10964 value: inst._zod ?? {},10965 enumerable: false10966 });10967 (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set());10968 inst._zod.traits.add(name);10969 initializer3(inst, def);10970 for (const k in _.prototype) {10971 if (!(k in inst))10972 Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });10973 }10974 inst._zod.constr = _;10975 inst._zod.def = def;10976 }10977 const Parent = params?.Parent ?? Object;10978 class Definition extends Parent {10979 }10980 Object.defineProperty(Definition, "name", { value: name });10981 function _(def) {10982 var _a;10983 const inst = params?.Parent ? new Definition() : this;10984 init(inst, def);10985 (_a = inst._zod).deferred ?? (_a.deferred = []);10986 for (const fn of inst._zod.deferred) {10987 fn();10988 }10989 return inst;10990 }10991 Object.defineProperty(_, "init", { value: init });10992 Object.defineProperty(_, Symbol.hasInstance, {10993 value: (inst) => {10994 if (params?.Parent && inst instanceof params.Parent)10995 return true;10996 return inst?._zod?.traits?.has(name);10997 }10998 });10999 Object.defineProperty(_, "name", { value: name });11000 return _;11001}11002var $brand = Symbol("zod_brand");11003var $ZodAsyncError = class extends Error {11004 constructor() {11005 super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);11006 }11007};11008var globalConfig = {};11009function config(newConfig) {11010 if (newConfig)11011 Object.assign(globalConfig, newConfig);11012 return globalConfig;11013}1101411015// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js11016var util_exports = {};11017__export(util_exports, {11018 BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,11019 Class: () => Class,11020 NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,11021 aborted: () => aborted,11022 allowsEval: () => allowsEval,11023 assert: () => assert,11024 assertEqual: () => assertEqual,11025 assertIs: () => assertIs,11026 assertNever: () => assertNever,11027 assertNotEqual: () => assertNotEqual,11028 assignProp: () => assignProp,11029 cached: () => cached,11030 captureStackTrace: () => captureStackTrace,11031 cleanEnum: () => cleanEnum,11032 cleanRegex: () => cleanRegex,11033 clone: () => clone,11034 createTransparentProxy: () => createTransparentProxy,11035 defineLazy: () => defineLazy,11036 esc: () => esc,11037 escapeRegex: () => escapeRegex,11038 extend: () => extend,11039 finalizeIssue: () => finalizeIssue,11040 floatSafeRemainder: () => floatSafeRemainder2,11041 getElementAtPath: () => getElementAtPath,11042 getEnumValues: () => getEnumValues,11043 getLengthableOrigin: () => getLengthableOrigin,11044 getParsedType: () => getParsedType2,11045 getSizableOrigin: () => getSizableOrigin,11046 isObject: () => isObject,11047 isPlainObject: () => isPlainObject,11048 issue: () => issue,11049 joinValues: () => joinValues,11050 jsonStringifyReplacer: () => jsonStringifyReplacer,11051 merge: () => merge,11052 normalizeParams: () => normalizeParams,11053 nullish: () => nullish,11054 numKeys: () => numKeys,11055 omit: () => omit,11056 optionalKeys: () => optionalKeys,11057 partial: () => partial,11058 pick: () => pick,11059 prefixIssues: () => prefixIssues,11060 primitiveTypes: () => primitiveTypes,11061 promiseAllObject: () => promiseAllObject,11062 propertyKeyTypes: () => propertyKeyTypes,11063 randomString: () => randomString,11064 required: () => required,11065 stringifyPrimitive: () => stringifyPrimitive,11066 unwrapMessage: () => unwrapMessage11067});11068function assertEqual(val) {11069 return val;11070}11071function assertNotEqual(val) {11072 return val;11073}11074function assertIs(_arg) {11075}11076function assertNever(_x) {11077 throw new Error();11078}11079function assert(_) {11080}11081function getEnumValues(entries) {11082 const numericValues = Object.values(entries).filter((v) => typeof v === "number");11083 const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);11084 return values;11085}11086function joinValues(array2, separator = "|") {11087 return array2.map((val) => stringifyPrimitive(val)).join(separator);11088}11089function jsonStringifyReplacer(_, value) {11090 if (typeof value === "bigint")11091 return value.toString();11092 return value;11093}11094function cached(getter) {11095 const set = false;11096 return {11097 get value() {11098 if (!set) {11099 const value = getter();11100 Object.defineProperty(this, "value", { value });11101 return value;11102 }11103 throw new Error("cached value already set");11104 }11105 };11106}11107function nullish(input) {11108 return input === null || input === void 0;11109}11110function cleanRegex(source) {11111 const start = source.startsWith("^") ? 1 : 0;11112 const end = source.endsWith("$") ? source.length - 1 : source.length;11113 return source.slice(start, end);11114}11115function floatSafeRemainder2(val, step) {11116 const valDecCount = (val.toString().split(".")[1] || "").length;11117 const stepDecCount = (step.toString().split(".")[1] || "").length;11118 const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;11119 const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));11120 const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));11121 return valInt % stepInt / 10 ** decCount;11122}11123function defineLazy(object3, key, getter) {11124 const set = false;11125 Object.defineProperty(object3, key, {11126 get() {11127 if (!set) {11128 const value = getter();11129 object3[key] = value;11130 return value;11131 }11132 throw new Error("cached value already set");11133 },11134 set(v) {11135 Object.defineProperty(object3, key, {11136 value: v11137 // configurable: true,11138 });11139 },11140 configurable: true11141 });11142}11143function assignProp(target, prop, value) {11144 Object.defineProperty(target, prop, {11145 value,11146 writable: true,11147 enumerable: true,11148 configurable: true11149 });11150}11151function getElementAtPath(obj, path) {11152 if (!path)11153 return obj;11154 return path.reduce((acc, key) => acc?.[key], obj);11155}11156function promiseAllObject(promisesObj) {11157 const keys = Object.keys(promisesObj);11158 const promises = keys.map((key) => promisesObj[key]);11159 return Promise.all(promises).then((results) => {11160 const resolvedObj = {};11161 for (let i = 0; i < keys.length; i++) {11162 resolvedObj[keys[i]] = results[i];11163 }11164 return resolvedObj;11165 });11166}11167function randomString(length = 10) {11168 const chars = "abcdefghijklmnopqrstuvwxyz";11169 let str = "";11170 for (let i = 0; i < length; i++) {11171 str += chars[Math.floor(Math.random() * chars.length)];11172 }11173 return str;11174}11175function esc(str) {11176 return JSON.stringify(str);11177}11178var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {11179};11180function isObject(data) {11181 return typeof data === "object" && data !== null && !Array.isArray(data);11182}11183var allowsEval = cached(() => {11184 if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {11185 return false;11186 }11187 try {11188 const F = Function;11189 new F("");11190 return true;11191 } catch (_) {11192 return false;11193 }11194});11195function isPlainObject(o) {11196 if (isObject(o) === false)11197 return false;11198 const ctor = o.constructor;11199 if (ctor === void 0)11200 return true;11201 const prot = ctor.prototype;11202 if (isObject(prot) === false)11203 return false;11204 if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {11205 return false;11206 }11207 return true;11208}11209function numKeys(data) {11210 let keyCount = 0;11211 for (const key in data) {11212 if (Object.prototype.hasOwnProperty.call(data, key)) {11213 keyCount++;11214 }11215 }11216 return keyCount;11217}11218var getParsedType2 = (data) => {11219 const t = typeof data;11220 switch (t) {11221 case "undefined":11222 return "undefined";11223 case "string":11224 return "string";11225 case "number":11226 return Number.isNaN(data) ? "nan" : "number";11227 case "boolean":11228 return "boolean";11229 case "function":11230 return "function";11231 case "bigint":11232 return "bigint";11233 case "symbol":11234 return "symbol";11235 case "object":11236 if (Array.isArray(data)) {11237 return "array";11238 }11239 if (data === null) {11240 return "null";11241 }11242 if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {11243 return "promise";11244 }11245 if (typeof Map !== "undefined" && data instanceof Map) {11246 return "map";11247 }11248 if (typeof Set !== "undefined" && data instanceof Set) {11249 return "set";11250 }11251 if (typeof Date !== "undefined" && data instanceof Date) {11252 return "date";11253 }11254 if (typeof File !== "undefined" && data instanceof File) {11255 return "file";11256 }11257 return "object";11258 default:11259 throw new Error(`Unknown data type: ${t}`);11260 }11261};11262var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);11263var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);11264function escapeRegex(str) {11265 return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");11266}11267function clone(inst, def, params) {11268 const cl = new inst._zod.constr(def ?? inst._zod.def);11269 if (!def || params?.parent)11270 cl._zod.parent = inst;11271 return cl;11272}11273function normalizeParams(_params) {11274 const params = _params;11275 if (!params)11276 return {};11277 if (typeof params === "string")11278 return { error: () => params };11279 if (params?.message !== void 0) {11280 if (params?.error !== void 0)11281 throw new Error("Cannot specify both `message` and `error` params");11282 params.error = params.message;11283 }11284 delete params.message;11285 if (typeof params.error === "string")11286 return { ...params, error: () => params.error };11287 return params;11288}11289function createTransparentProxy(getter) {11290 let target;11291 return new Proxy({}, {11292 get(_, prop, receiver) {11293 target ?? (target = getter());11294 return Reflect.get(target, prop, receiver);11295 },11296 set(_, prop, value, receiver) {11297 target ?? (target = getter());11298 return Reflect.set(target, prop, value, receiver);11299 },11300 has(_, prop) {11301 target ?? (target = getter());11302 return Reflect.has(target, prop);11303 },11304 deleteProperty(_, prop) {11305 target ?? (target = getter());11306 return Reflect.deleteProperty(target, prop);11307 },11308 ownKeys(_) {11309 target ?? (target = getter());11310 return Reflect.ownKeys(target);11311 },11312 getOwnPropertyDescriptor(_, prop) {11313 target ?? (target = getter());11314 return Reflect.getOwnPropertyDescriptor(target, prop);11315 },11316 defineProperty(_, prop, descriptor) {11317 target ?? (target = getter());11318 return Reflect.defineProperty(target, prop, descriptor);11319 }11320 });11321}11322function stringifyPrimitive(value) {11323 if (typeof value === "bigint")11324 return value.toString() + "n";11325 if (typeof value === "string")11326 return `"${value}"`;11327 return `${value}`;11328}11329function optionalKeys(shape) {11330 return Object.keys(shape).filter((k) => {11331 return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";11332 });11333}11334var NUMBER_FORMAT_RANGES = {11335 safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],11336 int32: [-2147483648, 2147483647],11337 uint32: [0, 4294967295],11338 float32: [-34028234663852886e22, 34028234663852886e22],11339 float64: [-Number.MAX_VALUE, Number.MAX_VALUE]11340};11341var BIGINT_FORMAT_RANGES = {11342 int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],11343 uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]11344};11345function pick(schema, mask) {11346 const newShape = {};11347 const currDef = schema._zod.def;11348 for (const key in mask) {11349 if (!(key in currDef.shape)) {11350 throw new Error(`Unrecognized key: "${key}"`);11351 }11352 if (!mask[key])11353 continue;11354 newShape[key] = currDef.shape[key];11355 }11356 return clone(schema, {11357 ...schema._zod.def,11358 shape: newShape,11359 checks: []11360 });11361}11362function omit(schema, mask) {11363 const newShape = { ...schema._zod.def.shape };11364 const currDef = schema._zod.def;11365 for (const key in mask) {11366 if (!(key in currDef.shape)) {11367 throw new Error(`Unrecognized key: "${key}"`);11368 }11369 if (!mask[key])11370 continue;11371 delete newShape[key];11372 }11373 return clone(schema, {11374 ...schema._zod.def,11375 shape: newShape,11376 checks: []11377 });11378}11379function extend(schema, shape) {11380 if (!isPlainObject(shape)) {11381 throw new Error("Invalid input to extend: expected a plain object");11382 }11383 const def = {11384 ...schema._zod.def,11385 get shape() {11386 const _shape = { ...schema._zod.def.shape, ...shape };11387 assignProp(this, "shape", _shape);11388 return _shape;11389 },11390 checks: []11391 // delete existing checks11392 };11393 return clone(schema, def);11394}11395function merge(a, b) {11396 return clone(a, {11397 ...a._zod.def,11398 get shape() {11399 const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };11400 assignProp(this, "shape", _shape);11401 return _shape;11402 },11403 catchall: b._zod.def.catchall,11404 checks: []11405 // delete existing checks11406 });11407}11408function partial(Class2, schema, mask) {11409 const oldShape = schema._zod.def.shape;11410 const shape = { ...oldShape };11411 if (mask) {11412 for (const key in mask) {11413 if (!(key in oldShape)) {11414 throw new Error(`Unrecognized key: "${key}"`);11415 }11416 if (!mask[key])11417 continue;11418 shape[key] = Class2 ? new Class2({11419 type: "optional",11420 innerType: oldShape[key]11421 }) : oldShape[key];11422 }11423 } else {11424 for (const key in oldShape) {11425 shape[key] = Class2 ? new Class2({11426 type: "optional",11427 innerType: oldShape[key]11428 }) : oldShape[key];11429 }11430 }11431 return clone(schema, {11432 ...schema._zod.def,11433 shape,11434 checks: []11435 });11436}11437function required(Class2, schema, mask) {11438 const oldShape = schema._zod.def.shape;11439 const shape = { ...oldShape };11440 if (mask) {11441 for (const key in mask) {11442 if (!(key in shape)) {11443 throw new Error(`Unrecognized key: "${key}"`);11444 }11445 if (!mask[key])11446 continue;11447 shape[key] = new Class2({11448 type: "nonoptional",11449 innerType: oldShape[key]11450 });11451 }11452 } else {11453 for (const key in oldShape) {11454 shape[key] = new Class2({11455 type: "nonoptional",11456 innerType: oldShape[key]11457 });11458 }11459 }11460 return clone(schema, {11461 ...schema._zod.def,11462 shape,11463 // optional: [],11464 checks: []11465 });11466}11467function aborted(x, startIndex = 0) {11468 for (let i = startIndex; i < x.issues.length; i++) {11469 if (x.issues[i]?.continue !== true)11470 return true;11471 }11472 return false;11473}11474function prefixIssues(path, issues) {11475 return issues.map((iss) => {11476 var _a;11477 (_a = iss).path ?? (_a.path = []);11478 iss.path.unshift(path);11479 return iss;11480 });11481}11482function unwrapMessage(message) {11483 return typeof message === "string" ? message : message?.message;11484}11485function finalizeIssue(iss, ctx, config2) {11486 const full = { ...iss, path: iss.path ?? [] };11487 if (!iss.message) {11488 const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";11489 full.message = message;11490 }11491 delete full.inst;11492 delete full.continue;11493 if (!ctx?.reportInput) {11494 delete full.input;11495 }11496 return full;11497}11498function getSizableOrigin(input) {11499 if (input instanceof Set)11500 return "set";11501 if (input instanceof Map)11502 return "map";11503 if (input instanceof File)11504 return "file";11505 return "unknown";11506}11507function getLengthableOrigin(input) {11508 if (Array.isArray(input))11509 return "array";11510 if (typeof input === "string")11511 return "string";11512 return "unknown";11513}11514function issue(...args) {11515 const [iss, input, inst] = args;11516 if (typeof iss === "string") {11517 return {11518 message: iss,11519 code: "custom",11520 input,11521 inst11522 };11523 }11524 return { ...iss };11525}11526function cleanEnum(obj) {11527 return Object.entries(obj).filter(([k, _]) => {11528 return Number.isNaN(Number.parseInt(k, 10));11529 }).map((el) => el[1]);11530}11531var Class = class {11532 constructor(..._args) {11533 }11534};1153511536// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js11537var initializer = (inst, def) => {11538 inst.name = "$ZodError";11539 Object.defineProperty(inst, "_zod", {11540 value: inst._zod,11541 enumerable: false11542 });11543 Object.defineProperty(inst, "issues", {11544 value: def,11545 enumerable: false11546 });11547 Object.defineProperty(inst, "message", {11548 get() {11549 return JSON.stringify(def, jsonStringifyReplacer, 2);11550 },11551 enumerable: true11552 // configurable: false,11553 });11554 Object.defineProperty(inst, "toString", {11555 value: () => inst.message,11556 enumerable: false11557 });11558};11559var $ZodError = $constructor("$ZodError", initializer);11560var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });11561function flattenError(error2, mapper = (issue2) => issue2.message) {11562 const fieldErrors = {};11563 const formErrors = [];11564 for (const sub of error2.issues) {11565 if (sub.path.length > 0) {11566 fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];11567 fieldErrors[sub.path[0]].push(mapper(sub));11568 } else {11569 formErrors.push(mapper(sub));11570 }11571 }11572 return { formErrors, fieldErrors };11573}11574function formatError(error2, _mapper) {11575 const mapper = _mapper || function(issue2) {11576 return issue2.message;11577 };11578 const fieldErrors = { _errors: [] };11579 const processError = (error3) => {11580 for (const issue2 of error3.issues) {11581 if (issue2.code === "invalid_union" && issue2.errors.length) {11582 issue2.errors.map((issues) => processError({ issues }));11583 } else if (issue2.code === "invalid_key") {11584 processError({ issues: issue2.issues });11585 } else if (issue2.code === "invalid_element") {11586 processError({ issues: issue2.issues });11587 } else if (issue2.path.length === 0) {11588 fieldErrors._errors.push(mapper(issue2));11589 } else {11590 let curr = fieldErrors;11591 let i = 0;11592 while (i < issue2.path.length) {11593 const el = issue2.path[i];11594 const terminal = i === issue2.path.length - 1;11595 if (!terminal) {11596 curr[el] = curr[el] || { _errors: [] };11597 } else {11598 curr[el] = curr[el] || { _errors: [] };11599 curr[el]._errors.push(mapper(issue2));11600 }11601 curr = curr[el];11602 i++;11603 }11604 }11605 }11606 };11607 processError(error2);11608 return fieldErrors;11609}1161011611// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js11612var _parse = (_Err) => (schema, value, _ctx, _params) => {11613 const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };11614 const result = schema._zod.run({ value, issues: [] }, ctx);11615 if (result instanceof Promise) {11616 throw new $ZodAsyncError();11617 }11618 if (result.issues.length) {11619 const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));11620 captureStackTrace(e, _params?.callee);11621 throw e;11622 }11623 return result.value;11624};11625var parse = /* @__PURE__ */ _parse($ZodRealError);11626var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {11627 const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };11628 let result = schema._zod.run({ value, issues: [] }, ctx);11629 if (result instanceof Promise)11630 result = await result;11631 if (result.issues.length) {11632 const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));11633 captureStackTrace(e, params?.callee);11634 throw e;11635 }11636 return result.value;11637};11638var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);11639var _safeParse = (_Err) => (schema, value, _ctx) => {11640 const ctx = _ctx ? { ..._ctx, async: false } : { async: false };11641 const result = schema._zod.run({ value, issues: [] }, ctx);11642 if (result instanceof Promise) {11643 throw new $ZodAsyncError();11644 }11645 return result.issues.length ? {11646 success: false,11647 error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))11648 } : { success: true, data: result.value };11649};11650var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);11651var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {11652 const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };11653 let result = schema._zod.run({ value, issues: [] }, ctx);11654 if (result instanceof Promise)11655 result = await result;11656 return result.issues.length ? {11657 success: false,11658 error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))11659 } : { success: true, data: result.value };11660};11661var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);1166211663// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js11664var cuid = /^[cC][^\s-]{8,}$/;11665var cuid2 = /^[0-9a-z]+$/;11666var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;11667var xid = /^[0-9a-vA-V]{20}$/;11668var ksuid = /^[A-Za-z0-9]{27}$/;11669var nanoid = /^[a-zA-Z0-9_-]{21}$/;11670var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;11671var 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})$/;11672var uuid = (version2) => {11673 if (!version2)11674 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)$/;11675 return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);11676};11677var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;11678var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;11679function emoji() {11680 return new RegExp(_emoji, "u");11681}11682var 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])$/;11683var ipv6 = /^(([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})$/;11684var 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])$/;11685var 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])$/;11686var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;11687var base64url = /^[A-Za-z0-9_-]*$/;11688var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;11689var e164 = /^\+(?:[0-9]){6,14}[0-9]$/;11690var 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])))`;11691var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);11692function timeSource(args) {11693 const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;11694 const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;11695 return regex;11696}11697function time(args) {11698 return new RegExp(`^${timeSource(args)}$`);11699}11700function datetime(args) {11701 const time3 = timeSource({ precision: args.precision });11702 const opts = ["Z"];11703 if (args.local)11704 opts.push("");11705 if (args.offset)11706 opts.push(`([+-]\\d{2}:\\d{2})`);11707 const timeRegex2 = `${time3}(?:${opts.join("|")})`;11708 return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);11709}11710var string = (params) => {11711 const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;11712 return new RegExp(`^${regex}$`);11713};11714var integer = /^\d+$/;11715var number = /^-?\d+(?:\.\d+)?/i;11716var boolean = /true|false/i;11717var _null = /null/i;11718var lowercase = /^[^A-Z]*$/;11719var uppercase = /^[^a-z]*$/;1172011721// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js11722var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {11723 var _a;11724 inst._zod ?? (inst._zod = {});11725 inst._zod.def = def;11726 (_a = inst._zod).onattach ?? (_a.onattach = []);11727});11728var numericOriginMap = {11729 number: "number",11730 bigint: "bigint",11731 object: "date"11732};11733var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {11734 $ZodCheck.init(inst, def);11735 const origin = numericOriginMap[typeof def.value];11736 inst._zod.onattach.push((inst2) => {11737 const bag = inst2._zod.bag;11738 const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;11739 if (def.value < curr) {11740 if (def.inclusive)11741 bag.maximum = def.value;11742 else11743 bag.exclusiveMaximum = def.value;11744 }11745 });11746 inst._zod.check = (payload) => {11747 if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {11748 return;11749 }11750 payload.issues.push({11751 origin,11752 code: "too_big",11753 maximum: def.value,11754 input: payload.value,11755 inclusive: def.inclusive,11756 inst,11757 continue: !def.abort11758 });11759 };11760});11761var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {11762 $ZodCheck.init(inst, def);11763 const origin = numericOriginMap[typeof def.value];11764 inst._zod.onattach.push((inst2) => {11765 const bag = inst2._zod.bag;11766 const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;11767 if (def.value > curr) {11768 if (def.inclusive)11769 bag.minimum = def.value;11770 else11771 bag.exclusiveMinimum = def.value;11772 }11773 });11774 inst._zod.check = (payload) => {11775 if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {11776 return;11777 }11778 payload.issues.push({11779 origin,11780 code: "too_small",11781 minimum: def.value,11782 input: payload.value,11783 inclusive: def.inclusive,11784 inst,11785 continue: !def.abort11786 });11787 };11788});11789var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {11790 $ZodCheck.init(inst, def);11791 inst._zod.onattach.push((inst2) => {11792 var _a;11793 (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value);11794 });11795 inst._zod.check = (payload) => {11796 if (typeof payload.value !== typeof def.value)11797 throw new Error("Cannot mix number and bigint in multiple_of check.");11798 const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0;11799 if (isMultiple)11800 return;11801 payload.issues.push({11802 origin: typeof payload.value,11803 code: "not_multiple_of",11804 divisor: def.value,11805 input: payload.value,11806 inst,11807 continue: !def.abort11808 });11809 };11810});11811var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {11812 $ZodCheck.init(inst, def);11813 def.format = def.format || "float64";11814 const isInt = def.format?.includes("int");11815 const origin = isInt ? "int" : "number";11816 const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];11817 inst._zod.onattach.push((inst2) => {11818 const bag = inst2._zod.bag;11819 bag.format = def.format;11820 bag.minimum = minimum;11821 bag.maximum = maximum;11822 if (isInt)11823 bag.pattern = integer;11824 });11825 inst._zod.check = (payload) => {11826 const input = payload.value;11827 if (isInt) {11828 if (!Number.isInteger(input)) {11829 payload.issues.push({11830 expected: origin,11831 format: def.format,11832 code: "invalid_type",11833 input,11834 inst11835 });11836 return;11837 }11838 if (!Number.isSafeInteger(input)) {11839 if (input > 0) {11840 payload.issues.push({11841 input,11842 code: "too_big",11843 maximum: Number.MAX_SAFE_INTEGER,11844 note: "Integers must be within the safe integer range.",11845 inst,11846 origin,11847 continue: !def.abort11848 });11849 } else {11850 payload.issues.push({11851 input,11852 code: "too_small",11853 minimum: Number.MIN_SAFE_INTEGER,11854 note: "Integers must be within the safe integer range.",11855 inst,11856 origin,11857 continue: !def.abort11858 });11859 }11860 return;11861 }11862 }11863 if (input < minimum) {11864 payload.issues.push({11865 origin: "number",11866 input,11867 code: "too_small",11868 minimum,11869 inclusive: true,11870 inst,11871 continue: !def.abort11872 });11873 }11874 if (input > maximum) {11875 payload.issues.push({11876 origin: "number",11877 input,11878 code: "too_big",11879 maximum,11880 inst11881 });11882 }11883 };11884});11885var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {11886 var _a;11887 $ZodCheck.init(inst, def);11888 (_a = inst._zod.def).when ?? (_a.when = (payload) => {11889 const val = payload.value;11890 return !nullish(val) && val.length !== void 0;11891 });11892 inst._zod.onattach.push((inst2) => {11893 const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;11894 if (def.maximum < curr)11895 inst2._zod.bag.maximum = def.maximum;11896 });11897 inst._zod.check = (payload) => {11898 const input = payload.value;11899 const length = input.length;11900 if (length <= def.maximum)11901 return;11902 const origin = getLengthableOrigin(input);11903 payload.issues.push({11904 origin,11905 code: "too_big",11906 maximum: def.maximum,11907 inclusive: true,11908 input,11909 inst,11910 continue: !def.abort11911 });11912 };11913});11914var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {11915 var _a;11916 $ZodCheck.init(inst, def);11917 (_a = inst._zod.def).when ?? (_a.when = (payload) => {11918 const val = payload.value;11919 return !nullish(val) && val.length !== void 0;11920 });11921 inst._zod.onattach.push((inst2) => {11922 const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;11923 if (def.minimum > curr)11924 inst2._zod.bag.minimum = def.minimum;11925 });11926 inst._zod.check = (payload) => {11927 const input = payload.value;11928 const length = input.length;11929 if (length >= def.minimum)11930 return;11931 const origin = getLengthableOrigin(input);11932 payload.issues.push({11933 origin,11934 code: "too_small",11935 minimum: def.minimum,11936 inclusive: true,11937 input,11938 inst,11939 continue: !def.abort11940 });11941 };11942});11943var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {11944 var _a;11945 $ZodCheck.init(inst, def);11946 (_a = inst._zod.def).when ?? (_a.when = (payload) => {11947 const val = payload.value;11948 return !nullish(val) && val.length !== void 0;11949 });11950 inst._zod.onattach.push((inst2) => {11951 const bag = inst2._zod.bag;11952 bag.minimum = def.length;11953 bag.maximum = def.length;11954 bag.length = def.length;11955 });11956 inst._zod.check = (payload) => {11957 const input = payload.value;11958 const length = input.length;11959 if (length === def.length)11960 return;11961 const origin = getLengthableOrigin(input);11962 const tooBig = length > def.length;11963 payload.issues.push({11964 origin,11965 ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },11966 inclusive: true,11967 exact: true,11968 input: payload.value,11969 inst,11970 continue: !def.abort11971 });11972 };11973});11974var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {11975 var _a, _b;11976 $ZodCheck.init(inst, def);11977 inst._zod.onattach.push((inst2) => {11978 const bag = inst2._zod.bag;11979 bag.format = def.format;11980 if (def.pattern) {11981 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());11982 bag.patterns.add(def.pattern);11983 }11984 });11985 if (def.pattern)11986 (_a = inst._zod).check ?? (_a.check = (payload) => {11987 def.pattern.lastIndex = 0;11988 if (def.pattern.test(payload.value))11989 return;11990 payload.issues.push({11991 origin: "string",11992 code: "invalid_format",11993 format: def.format,11994 input: payload.value,11995 ...def.pattern ? { pattern: def.pattern.toString() } : {},11996 inst,11997 continue: !def.abort11998 });11999 });12000 else12001 (_b = inst._zod).check ?? (_b.check = () => {12002 });12003});12004var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {12005 $ZodCheckStringFormat.init(inst, def);12006 inst._zod.check = (payload) => {12007 def.pattern.lastIndex = 0;12008 if (def.pattern.test(payload.value))12009 return;12010 payload.issues.push({12011 origin: "string",12012 code: "invalid_format",12013 format: "regex",12014 input: payload.value,12015 pattern: def.pattern.toString(),12016 inst,12017 continue: !def.abort12018 });12019 };12020});12021var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {12022 def.pattern ?? (def.pattern = lowercase);12023 $ZodCheckStringFormat.init(inst, def);12024});12025var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {12026 def.pattern ?? (def.pattern = uppercase);12027 $ZodCheckStringFormat.init(inst, def);12028});12029var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {12030 $ZodCheck.init(inst, def);12031 const escapedRegex = escapeRegex(def.includes);12032 const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);12033 def.pattern = pattern;12034 inst._zod.onattach.push((inst2) => {12035 const bag = inst2._zod.bag;12036 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());12037 bag.patterns.add(pattern);12038 });12039 inst._zod.check = (payload) => {12040 if (payload.value.includes(def.includes, def.position))12041 return;12042 payload.issues.push({12043 origin: "string",12044 code: "invalid_format",12045 format: "includes",12046 includes: def.includes,12047 input: payload.value,12048 inst,12049 continue: !def.abort12050 });12051 };12052});12053var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {12054 $ZodCheck.init(inst, def);12055 const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);12056 def.pattern ?? (def.pattern = pattern);12057 inst._zod.onattach.push((inst2) => {12058 const bag = inst2._zod.bag;12059 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());12060 bag.patterns.add(pattern);12061 });12062 inst._zod.check = (payload) => {12063 if (payload.value.startsWith(def.prefix))12064 return;12065 payload.issues.push({12066 origin: "string",12067 code: "invalid_format",12068 format: "starts_with",12069 prefix: def.prefix,12070 input: payload.value,12071 inst,12072 continue: !def.abort12073 });12074 };12075});12076var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {12077 $ZodCheck.init(inst, def);12078 const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);12079 def.pattern ?? (def.pattern = pattern);12080 inst._zod.onattach.push((inst2) => {12081 const bag = inst2._zod.bag;12082 bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());12083 bag.patterns.add(pattern);12084 });12085 inst._zod.check = (payload) => {12086 if (payload.value.endsWith(def.suffix))12087 return;12088 payload.issues.push({12089 origin: "string",12090 code: "invalid_format",12091 format: "ends_with",12092 suffix: def.suffix,12093 input: payload.value,12094 inst,12095 continue: !def.abort12096 });12097 };12098});12099var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {12100 $ZodCheck.init(inst, def);12101 inst._zod.check = (payload) => {12102 payload.value = def.tx(payload.value);12103 };12104});1210512106// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js12107var Doc = class {12108 constructor(args = []) {12109 this.content = [];12110 this.indent = 0;12111 if (this)12112 this.args = args;12113 }12114 indented(fn) {12115 this.indent += 1;12116 fn(this);12117 this.indent -= 1;12118 }12119 write(arg) {12120 if (typeof arg === "function") {12121 arg(this, { execution: "sync" });12122 arg(this, { execution: "async" });12123 return;12124 }12125 const content = arg;12126 const lines = content.split("\n").filter((x) => x);12127 const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));12128 const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);12129 for (const line of dedented) {12130 this.content.push(line);12131 }12132 }12133 compile() {12134 const F = Function;12135 const args = this?.args;12136 const content = this?.content ?? [``];12137 const lines = [...content.map((x) => ` ${x}`)];12138 return new F(...args, lines.join("\n"));12139 }12140};1214112142// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js12143var version = {12144 major: 4,12145 minor: 0,12146 patch: 012147};1214812149// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js12150var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {12151 var _a;12152 inst ?? (inst = {});12153 inst._zod.def = def;12154 inst._zod.bag = inst._zod.bag || {};12155 inst._zod.version = version;12156 const checks = [...inst._zod.def.checks ?? []];12157 if (inst._zod.traits.has("$ZodCheck")) {12158 checks.unshift(inst);12159 }12160 for (const ch of checks) {12161 for (const fn of ch._zod.onattach) {12162 fn(inst);12163 }12164 }12165 if (checks.length === 0) {12166 (_a = inst._zod).deferred ?? (_a.deferred = []);12167 inst._zod.deferred?.push(() => {12168 inst._zod.run = inst._zod.parse;12169 });12170 } else {12171 const runChecks = (payload, checks2, ctx) => {12172 let isAborted2 = aborted(payload);12173 let asyncResult;12174 for (const ch of checks2) {12175 if (ch._zod.def.when) {12176 const shouldRun = ch._zod.def.when(payload);12177 if (!shouldRun)12178 continue;12179 } else if (isAborted2) {12180 continue;12181 }12182 const currLen = payload.issues.length;12183 const _ = ch._zod.check(payload);12184 if (_ instanceof Promise && ctx?.async === false) {12185 throw new $ZodAsyncError();12186 }12187 if (asyncResult || _ instanceof Promise) {12188 asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {12189 await _;12190 const nextLen = payload.issues.length;12191 if (nextLen === currLen)12192 return;12193 if (!isAborted2)12194 isAborted2 = aborted(payload, currLen);12195 });12196 } else {12197 const nextLen = payload.issues.length;12198 if (nextLen === currLen)12199 continue;12200 if (!isAborted2)12201 isAborted2 = aborted(payload, currLen);12202 }12203 }12204 if (asyncResult) {12205 return asyncResult.then(() => {12206 return payload;12207 });12208 }12209 return payload;12210 };12211 inst._zod.run = (payload, ctx) => {12212 const result = inst._zod.parse(payload, ctx);12213 if (result instanceof Promise) {12214 if (ctx.async === false)12215 throw new $ZodAsyncError();12216 return result.then((result2) => runChecks(result2, checks, ctx));12217 }12218 return runChecks(result, checks, ctx);12219 };12220 }12221 inst["~standard"] = {12222 validate: (value) => {12223 try {12224 const r = safeParse(inst, value);12225 return r.success ? { value: r.data } : { issues: r.error?.issues };12226 } catch (_) {12227 return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });12228 }12229 },12230 vendor: "zod",12231 version: 112232 };12233});12234var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {12235 $ZodType.init(inst, def);12236 inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);12237 inst._zod.parse = (payload, _) => {12238 if (def.coerce)12239 try {12240 payload.value = String(payload.value);12241 } catch (_2) {12242 }12243 if (typeof payload.value === "string")12244 return payload;12245 payload.issues.push({12246 expected: "string",12247 code: "invalid_type",12248 input: payload.value,12249 inst12250 });12251 return payload;12252 };12253});12254var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {12255 $ZodCheckStringFormat.init(inst, def);12256 $ZodString.init(inst, def);12257});12258var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {12259 def.pattern ?? (def.pattern = guid);12260 $ZodStringFormat.init(inst, def);12261});12262var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {12263 if (def.version) {12264 const versionMap = {12265 v1: 1,12266 v2: 2,12267 v3: 3,12268 v4: 4,12269 v5: 5,12270 v6: 6,12271 v7: 7,12272 v8: 812273 };12274 const v = versionMap[def.version];12275 if (v === void 0)12276 throw new Error(`Invalid UUID version: "${def.version}"`);12277 def.pattern ?? (def.pattern = uuid(v));12278 } else12279 def.pattern ?? (def.pattern = uuid());12280 $ZodStringFormat.init(inst, def);12281});12282var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {12283 def.pattern ?? (def.pattern = email);12284 $ZodStringFormat.init(inst, def);12285});12286var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {12287 $ZodStringFormat.init(inst, def);12288 inst._zod.check = (payload) => {12289 try {12290 const orig = payload.value;12291 const url = new URL(orig);12292 const href = url.href;12293 if (def.hostname) {12294 def.hostname.lastIndex = 0;12295 if (!def.hostname.test(url.hostname)) {12296 payload.issues.push({12297 code: "invalid_format",12298 format: "url",12299 note: "Invalid hostname",12300 pattern: hostname.source,12301 input: payload.value,12302 inst,12303 continue: !def.abort12304 });12305 }12306 }12307 if (def.protocol) {12308 def.protocol.lastIndex = 0;12309 if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {12310 payload.issues.push({12311 code: "invalid_format",12312 format: "url",12313 note: "Invalid protocol",12314 pattern: def.protocol.source,12315 input: payload.value,12316 inst,12317 continue: !def.abort12318 });12319 }12320 }12321 if (!orig.endsWith("/") && href.endsWith("/")) {12322 payload.value = href.slice(0, -1);12323 } else {12324 payload.value = href;12325 }12326 return;12327 } catch (_) {12328 payload.issues.push({12329 code: "invalid_format",12330 format: "url",12331 input: payload.value,12332 inst,12333 continue: !def.abort12334 });12335 }12336 };12337});12338var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {12339 def.pattern ?? (def.pattern = emoji());12340 $ZodStringFormat.init(inst, def);12341});12342var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {12343 def.pattern ?? (def.pattern = nanoid);12344 $ZodStringFormat.init(inst, def);12345});12346var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {12347 def.pattern ?? (def.pattern = cuid);12348 $ZodStringFormat.init(inst, def);12349});12350var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {12351 def.pattern ?? (def.pattern = cuid2);12352 $ZodStringFormat.init(inst, def);12353});12354var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {12355 def.pattern ?? (def.pattern = ulid);12356 $ZodStringFormat.init(inst, def);12357});12358var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {12359 def.pattern ?? (def.pattern = xid);12360 $ZodStringFormat.init(inst, def);12361});12362var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {12363 def.pattern ?? (def.pattern = ksuid);12364 $ZodStringFormat.init(inst, def);12365});12366var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {12367 def.pattern ?? (def.pattern = datetime(def));12368 $ZodStringFormat.init(inst, def);12369});12370var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {12371 def.pattern ?? (def.pattern = date);12372 $ZodStringFormat.init(inst, def);12373});12374var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {12375 def.pattern ?? (def.pattern = time(def));12376 $ZodStringFormat.init(inst, def);12377});12378var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {12379 def.pattern ?? (def.pattern = duration);12380 $ZodStringFormat.init(inst, def);12381});12382var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {12383 def.pattern ?? (def.pattern = ipv4);12384 $ZodStringFormat.init(inst, def);12385 inst._zod.onattach.push((inst2) => {12386 const bag = inst2._zod.bag;12387 bag.format = `ipv4`;12388 });12389});12390var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {12391 def.pattern ?? (def.pattern = ipv6);12392 $ZodStringFormat.init(inst, def);12393 inst._zod.onattach.push((inst2) => {12394 const bag = inst2._zod.bag;12395 bag.format = `ipv6`;12396 });12397 inst._zod.check = (payload) => {12398 try {12399 new URL(`http://[${payload.value}]`);12400 } catch {12401 payload.issues.push({12402 code: "invalid_format",12403 format: "ipv6",12404 input: payload.value,12405 inst,12406 continue: !def.abort12407 });12408 }12409 };12410});12411var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {12412 def.pattern ?? (def.pattern = cidrv4);12413 $ZodStringFormat.init(inst, def);12414});12415var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {12416 def.pattern ?? (def.pattern = cidrv6);12417 $ZodStringFormat.init(inst, def);12418 inst._zod.check = (payload) => {12419 const [address, prefix] = payload.value.split("/");12420 try {12421 if (!prefix)12422 throw new Error();12423 const prefixNum = Number(prefix);12424 if (`${prefixNum}` !== prefix)12425 throw new Error();12426 if (prefixNum < 0 || prefixNum > 128)12427 throw new Error();12428 new URL(`http://[${address}]`);12429 } catch {12430 payload.issues.push({12431 code: "invalid_format",12432 format: "cidrv6",12433 input: payload.value,12434 inst,12435 continue: !def.abort12436 });12437 }12438 };12439});12440function isValidBase64(data) {12441 if (data === "")12442 return true;12443 if (data.length % 4 !== 0)12444 return false;12445 try {12446 atob(data);12447 return true;12448 } catch {12449 return false;12450 }12451}12452var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {12453 def.pattern ?? (def.pattern = base64);12454 $ZodStringFormat.init(inst, def);12455 inst._zod.onattach.push((inst2) => {12456 inst2._zod.bag.contentEncoding = "base64";12457 });12458 inst._zod.check = (payload) => {12459 if (isValidBase64(payload.value))12460 return;12461 payload.issues.push({12462 code: "invalid_format",12463 format: "base64",12464 input: payload.value,12465 inst,12466 continue: !def.abort12467 });12468 };12469});12470function isValidBase64URL(data) {12471 if (!base64url.test(data))12472 return false;12473 const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");12474 const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");12475 return isValidBase64(padded);12476}12477var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {12478 def.pattern ?? (def.pattern = base64url);12479 $ZodStringFormat.init(inst, def);12480 inst._zod.onattach.push((inst2) => {12481 inst2._zod.bag.contentEncoding = "base64url";12482 });12483 inst._zod.check = (payload) => {12484 if (isValidBase64URL(payload.value))12485 return;12486 payload.issues.push({12487 code: "invalid_format",12488 format: "base64url",12489 input: payload.value,12490 inst,12491 continue: !def.abort12492 });12493 };12494});12495var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {12496 def.pattern ?? (def.pattern = e164);12497 $ZodStringFormat.init(inst, def);12498});12499function isValidJWT2(token, algorithm = null) {12500 try {12501 const tokensParts = token.split(".");12502 if (tokensParts.length !== 3)12503 return false;12504 const [header] = tokensParts;12505 if (!header)12506 return false;12507 const parsedHeader = JSON.parse(atob(header));12508 if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")12509 return false;12510 if (!parsedHeader.alg)12511 return false;12512 if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))12513 return false;12514 return true;12515 } catch {12516 return false;12517 }12518}12519var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {12520 $ZodStringFormat.init(inst, def);12521 inst._zod.check = (payload) => {12522 if (isValidJWT2(payload.value, def.alg))12523 return;12524 payload.issues.push({12525 code: "invalid_format",12526 format: "jwt",12527 input: payload.value,12528 inst,12529 continue: !def.abort12530 });12531 };12532});12533var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {12534 $ZodType.init(inst, def);12535 inst._zod.pattern = inst._zod.bag.pattern ?? number;12536 inst._zod.parse = (payload, _ctx) => {12537 if (def.coerce)12538 try {12539 payload.value = Number(payload.value);12540 } catch (_) {12541 }12542 const input = payload.value;12543 if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {12544 return payload;12545 }12546 const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;12547 payload.issues.push({12548 expected: "number",12549 code: "invalid_type",12550 input,12551 inst,12552 ...received ? { received } : {}12553 });12554 return payload;12555 };12556});12557var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {12558 $ZodCheckNumberFormat.init(inst, def);12559 $ZodNumber.init(inst, def);12560});12561var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {12562 $ZodType.init(inst, def);12563 inst._zod.pattern = boolean;12564 inst._zod.parse = (payload, _ctx) => {12565 if (def.coerce)12566 try {12567 payload.value = Boolean(payload.value);12568 } catch (_) {12569 }12570 const input = payload.value;12571 if (typeof input === "boolean")12572 return payload;12573 payload.issues.push({12574 expected: "boolean",12575 code: "invalid_type",12576 input,12577 inst12578 });12579 return payload;12580 };12581});12582var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {12583 $ZodType.init(inst, def);12584 inst._zod.pattern = _null;12585 inst._zod.values = /* @__PURE__ */ new Set([null]);12586 inst._zod.parse = (payload, _ctx) => {12587 const input = payload.value;12588 if (input === null)12589 return payload;12590 payload.issues.push({12591 expected: "null",12592 code: "invalid_type",12593 input,12594 inst12595 });12596 return payload;12597 };12598});12599var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {12600 $ZodType.init(inst, def);12601 inst._zod.parse = (payload) => payload;12602});12603var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {12604 $ZodType.init(inst, def);12605 inst._zod.parse = (payload, _ctx) => {12606 payload.issues.push({12607 expected: "never",12608 code: "invalid_type",12609 input: payload.value,12610 inst12611 });12612 return payload;12613 };12614});12615function handleArrayResult(result, final, index) {12616 if (result.issues.length) {12617 final.issues.push(...prefixIssues(index, result.issues));12618 }12619 final.value[index] = result.value;12620}12621var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {12622 $ZodType.init(inst, def);12623 inst._zod.parse = (payload, ctx) => {12624 const input = payload.value;12625 if (!Array.isArray(input)) {12626 payload.issues.push({12627 expected: "array",12628 code: "invalid_type",12629 input,12630 inst12631 });12632 return payload;12633 }12634 payload.value = Array(input.length);12635 const proms = [];12636 for (let i = 0; i < input.length; i++) {12637 const item = input[i];12638 const result = def.element._zod.run({12639 value: item,12640 issues: []12641 }, ctx);12642 if (result instanceof Promise) {12643 proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));12644 } else {12645 handleArrayResult(result, payload, i);12646 }12647 }12648 if (proms.length) {12649 return Promise.all(proms).then(() => payload);12650 }12651 return payload;12652 };12653});12654function handleObjectResult(result, final, key) {12655 if (result.issues.length) {12656 final.issues.push(...prefixIssues(key, result.issues));12657 }12658 final.value[key] = result.value;12659}12660function handleOptionalObjectResult(result, final, key, input) {12661 if (result.issues.length) {12662 if (input[key] === void 0) {12663 if (key in input) {12664 final.value[key] = void 0;12665 } else {12666 final.value[key] = result.value;12667 }12668 } else {12669 final.issues.push(...prefixIssues(key, result.issues));12670 }12671 } else if (result.value === void 0) {12672 if (key in input)12673 final.value[key] = void 0;12674 } else {12675 final.value[key] = result.value;12676 }12677}12678var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {12679 $ZodType.init(inst, def);12680 const _normalized = cached(() => {12681 const keys = Object.keys(def.shape);12682 for (const k of keys) {12683 if (!(def.shape[k] instanceof $ZodType)) {12684 throw new Error(`Invalid element at key "${k}": expected a Zod schema`);12685 }12686 }12687 const okeys = optionalKeys(def.shape);12688 return {12689 shape: def.shape,12690 keys,12691 keySet: new Set(keys),12692 numKeys: keys.length,12693 optionalKeys: new Set(okeys)12694 };12695 });12696 defineLazy(inst._zod, "propValues", () => {12697 const shape = def.shape;12698 const propValues = {};12699 for (const key in shape) {12700 const field = shape[key]._zod;12701 if (field.values) {12702 propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());12703 for (const v of field.values)12704 propValues[key].add(v);12705 }12706 }12707 return propValues;12708 });12709 const generateFastpass = (shape) => {12710 const doc = new Doc(["shape", "payload", "ctx"]);12711 const normalized = _normalized.value;12712 const parseStr = (key) => {12713 const k = esc(key);12714 return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;12715 };12716 doc.write(`const input = payload.value;`);12717 const ids = /* @__PURE__ */ Object.create(null);12718 let counter = 0;12719 for (const key of normalized.keys) {12720 ids[key] = `key_${counter++}`;12721 }12722 doc.write(`const newResult = {}`);12723 for (const key of normalized.keys) {12724 if (normalized.optionalKeys.has(key)) {12725 const id = ids[key];12726 doc.write(`const ${id} = ${parseStr(key)};`);12727 const k = esc(key);12728 doc.write(`12729 if (${id}.issues.length) {12730 if (input[${k}] === undefined) {12731 if (${k} in input) {12732 newResult[${k}] = undefined;12733 }12734 } else {12735 payload.issues = payload.issues.concat(12736 ${id}.issues.map((iss) => ({12737 ...iss,12738 path: iss.path ? [${k}, ...iss.path] : [${k}],12739 }))12740 );12741 }12742 } else if (${id}.value === undefined) {12743 if (${k} in input) newResult[${k}] = undefined;12744 } else {12745 newResult[${k}] = ${id}.value;12746 }12747 `);12748 } else {12749 const id = ids[key];12750 doc.write(`const ${id} = ${parseStr(key)};`);12751 doc.write(`12752 if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({12753 ...iss,12754 path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]12755 })));`);12756 doc.write(`newResult[${esc(key)}] = ${id}.value`);12757 }12758 }12759 doc.write(`payload.value = newResult;`);12760 doc.write(`return payload;`);12761 const fn = doc.compile();12762 return (payload, ctx) => fn(shape, payload, ctx);12763 };12764 let fastpass;12765 const isObject2 = isObject;12766 const jit = !globalConfig.jitless;12767 const allowsEval2 = allowsEval;12768 const fastEnabled = jit && allowsEval2.value;12769 const catchall = def.catchall;12770 let value;12771 inst._zod.parse = (payload, ctx) => {12772 value ?? (value = _normalized.value);12773 const input = payload.value;12774 if (!isObject2(input)) {12775 payload.issues.push({12776 expected: "object",12777 code: "invalid_type",12778 input,12779 inst12780 });12781 return payload;12782 }12783 const proms = [];12784 if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {12785 if (!fastpass)12786 fastpass = generateFastpass(def.shape);12787 payload = fastpass(payload, ctx);12788 } else {12789 payload.value = {};12790 const shape = value.shape;12791 for (const key of value.keys) {12792 const el = shape[key];12793 const r = el._zod.run({ value: input[key], issues: [] }, ctx);12794 const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";12795 if (r instanceof Promise) {12796 proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key)));12797 } else if (isOptional) {12798 handleOptionalObjectResult(r, payload, key, input);12799 } else {12800 handleObjectResult(r, payload, key);12801 }12802 }12803 }12804 if (!catchall) {12805 return proms.length ? Promise.all(proms).then(() => payload) : payload;12806 }12807 const unrecognized = [];12808 const keySet = value.keySet;12809 const _catchall = catchall._zod;12810 const t = _catchall.def.type;12811 for (const key of Object.keys(input)) {12812 if (keySet.has(key))12813 continue;12814 if (t === "never") {12815 unrecognized.push(key);12816 continue;12817 }12818 const r = _catchall.run({ value: input[key], issues: [] }, ctx);12819 if (r instanceof Promise) {12820 proms.push(r.then((r2) => handleObjectResult(r2, payload, key)));12821 } else {12822 handleObjectResult(r, payload, key);12823 }12824 }12825 if (unrecognized.length) {12826 payload.issues.push({12827 code: "unrecognized_keys",12828 keys: unrecognized,12829 input,12830 inst12831 });12832 }12833 if (!proms.length)12834 return payload;12835 return Promise.all(proms).then(() => {12836 return payload;12837 });12838 };12839});12840function handleUnionResults(results, final, inst, ctx) {12841 for (const result of results) {12842 if (result.issues.length === 0) {12843 final.value = result.value;12844 return final;12845 }12846 }12847 final.issues.push({12848 code: "invalid_union",12849 input: final.value,12850 inst,12851 errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))12852 });12853 return final;12854}12855var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {12856 $ZodType.init(inst, def);12857 defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);12858 defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);12859 defineLazy(inst._zod, "values", () => {12860 if (def.options.every((o) => o._zod.values)) {12861 return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));12862 }12863 return void 0;12864 });12865 defineLazy(inst._zod, "pattern", () => {12866 if (def.options.every((o) => o._zod.pattern)) {12867 const patterns = def.options.map((o) => o._zod.pattern);12868 return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);12869 }12870 return void 0;12871 });12872 inst._zod.parse = (payload, ctx) => {12873 let async = false;12874 const results = [];12875 for (const option of def.options) {12876 const result = option._zod.run({12877 value: payload.value,12878 issues: []12879 }, ctx);12880 if (result instanceof Promise) {12881 results.push(result);12882 async = true;12883 } else {12884 if (result.issues.length === 0)12885 return result;12886 results.push(result);12887 }12888 }12889 if (!async)12890 return handleUnionResults(results, payload, inst, ctx);12891 return Promise.all(results).then((results2) => {12892 return handleUnionResults(results2, payload, inst, ctx);12893 });12894 };12895});12896var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {12897 $ZodUnion.init(inst, def);12898 const _super = inst._zod.parse;12899 defineLazy(inst._zod, "propValues", () => {12900 const propValues = {};12901 for (const option of def.options) {12902 const pv = option._zod.propValues;12903 if (!pv || Object.keys(pv).length === 0)12904 throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);12905 for (const [k, v] of Object.entries(pv)) {12906 if (!propValues[k])12907 propValues[k] = /* @__PURE__ */ new Set();12908 for (const val of v) {12909 propValues[k].add(val);12910 }12911 }12912 }12913 return propValues;12914 });12915 const disc = cached(() => {12916 const opts = def.options;12917 const map = /* @__PURE__ */ new Map();12918 for (const o of opts) {12919 const values = o._zod.propValues[def.discriminator];12920 if (!values || values.size === 0)12921 throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);12922 for (const v of values) {12923 if (map.has(v)) {12924 throw new Error(`Duplicate discriminator value "${String(v)}"`);12925 }12926 map.set(v, o);12927 }12928 }12929 return map;12930 });12931 inst._zod.parse = (payload, ctx) => {12932 const input = payload.value;12933 if (!isObject(input)) {12934 payload.issues.push({12935 code: "invalid_type",12936 expected: "object",12937 input,12938 inst12939 });12940 return payload;12941 }12942 const opt = disc.value.get(input?.[def.discriminator]);12943 if (opt) {12944 return opt._zod.run(payload, ctx);12945 }12946 if (def.unionFallback) {12947 return _super(payload, ctx);12948 }12949 payload.issues.push({12950 code: "invalid_union",12951 errors: [],12952 note: "No matching discriminator",12953 input,12954 path: [def.discriminator],12955 inst12956 });12957 return payload;12958 };12959});12960var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {12961 $ZodType.init(inst, def);12962 inst._zod.parse = (payload, ctx) => {12963 const input = payload.value;12964 const left = def.left._zod.run({ value: input, issues: [] }, ctx);12965 const right = def.right._zod.run({ value: input, issues: [] }, ctx);12966 const async = left instanceof Promise || right instanceof Promise;12967 if (async) {12968 return Promise.all([left, right]).then(([left2, right2]) => {12969 return handleIntersectionResults(payload, left2, right2);12970 });12971 }12972 return handleIntersectionResults(payload, left, right);12973 };12974});12975function mergeValues2(a, b) {12976 if (a === b) {12977 return { valid: true, data: a };12978 }12979 if (a instanceof Date && b instanceof Date && +a === +b) {12980 return { valid: true, data: a };12981 }12982 if (isPlainObject(a) && isPlainObject(b)) {12983 const bKeys = Object.keys(b);12984 const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);12985 const newObj = { ...a, ...b };12986 for (const key of sharedKeys) {12987 const sharedValue = mergeValues2(a[key], b[key]);12988 if (!sharedValue.valid) {12989 return {12990 valid: false,12991 mergeErrorPath: [key, ...sharedValue.mergeErrorPath]12992 };12993 }12994 newObj[key] = sharedValue.data;12995 }12996 return { valid: true, data: newObj };12997 }12998 if (Array.isArray(a) && Array.isArray(b)) {12999 if (a.length !== b.length) {13000 return { valid: false, mergeErrorPath: [] };13001 }13002 const newArray = [];13003 for (let index = 0; index < a.length; index++) {13004 const itemA = a[index];13005 const itemB = b[index];13006 const sharedValue = mergeValues2(itemA, itemB);13007 if (!sharedValue.valid) {13008 return {13009 valid: false,13010 mergeErrorPath: [index, ...sharedValue.mergeErrorPath]13011 };13012 }13013 newArray.push(sharedValue.data);13014 }13015 return { valid: true, data: newArray };13016 }13017 return { valid: false, mergeErrorPath: [] };13018}13019function handleIntersectionResults(result, left, right) {13020 if (left.issues.length) {13021 result.issues.push(...left.issues);13022 }13023 if (right.issues.length) {13024 result.issues.push(...right.issues);13025 }13026 if (aborted(result))13027 return result;13028 const merged = mergeValues2(left.value, right.value);13029 if (!merged.valid) {13030 throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);13031 }13032 result.value = merged.data;13033 return result;13034}13035var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {13036 $ZodType.init(inst, def);13037 inst._zod.parse = (payload, ctx) => {13038 const input = payload.value;13039 if (!isPlainObject(input)) {13040 payload.issues.push({13041 expected: "record",13042 code: "invalid_type",13043 input,13044 inst13045 });13046 return payload;13047 }13048 const proms = [];13049 if (def.keyType._zod.values) {13050 const values = def.keyType._zod.values;13051 payload.value = {};13052 for (const key of values) {13053 if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {13054 const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);13055 if (result instanceof Promise) {13056 proms.push(result.then((result2) => {13057 if (result2.issues.length) {13058 payload.issues.push(...prefixIssues(key, result2.issues));13059 }13060 payload.value[key] = result2.value;13061 }));13062 } else {13063 if (result.issues.length) {13064 payload.issues.push(...prefixIssues(key, result.issues));13065 }13066 payload.value[key] = result.value;13067 }13068 }13069 }13070 let unrecognized;13071 for (const key in input) {13072 if (!values.has(key)) {13073 unrecognized = unrecognized ?? [];13074 unrecognized.push(key);13075 }13076 }13077 if (unrecognized && unrecognized.length > 0) {13078 payload.issues.push({13079 code: "unrecognized_keys",13080 input,13081 inst,13082 keys: unrecognized13083 });13084 }13085 } else {13086 payload.value = {};13087 for (const key of Reflect.ownKeys(input)) {13088 if (key === "__proto__")13089 continue;13090 const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);13091 if (keyResult instanceof Promise) {13092 throw new Error("Async schemas not supported in object keys currently");13093 }13094 if (keyResult.issues.length) {13095 payload.issues.push({13096 origin: "record",13097 code: "invalid_key",13098 issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),13099 input: key,13100 path: [key],13101 inst13102 });13103 payload.value[keyResult.value] = keyResult.value;13104 continue;13105 }13106 const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);13107 if (result instanceof Promise) {13108 proms.push(result.then((result2) => {13109 if (result2.issues.length) {13110 payload.issues.push(...prefixIssues(key, result2.issues));13111 }13112 payload.value[keyResult.value] = result2.value;13113 }));13114 } else {13115 if (result.issues.length) {13116 payload.issues.push(...prefixIssues(key, result.issues));13117 }13118 payload.value[keyResult.value] = result.value;13119 }13120 }13121 }13122 if (proms.length) {13123 return Promise.all(proms).then(() => payload);13124 }13125 return payload;13126 };13127});13128var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {13129 $ZodType.init(inst, def);13130 const values = getEnumValues(def.entries);13131 inst._zod.values = new Set(values);13132 inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);13133 inst._zod.parse = (payload, _ctx) => {13134 const input = payload.value;13135 if (inst._zod.values.has(input)) {13136 return payload;13137 }13138 payload.issues.push({13139 code: "invalid_value",13140 values,13141 input,13142 inst13143 });13144 return payload;13145 };13146});13147var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {13148 $ZodType.init(inst, def);13149 inst._zod.values = new Set(def.values);13150 inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`);13151 inst._zod.parse = (payload, _ctx) => {13152 const input = payload.value;13153 if (inst._zod.values.has(input)) {13154 return payload;13155 }13156 payload.issues.push({13157 code: "invalid_value",13158 values: def.values,13159 input,13160 inst13161 });13162 return payload;13163 };13164});13165var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {13166 $ZodType.init(inst, def);13167 inst._zod.parse = (payload, _ctx) => {13168 const _out = def.transform(payload.value, payload);13169 if (_ctx.async) {13170 const output = _out instanceof Promise ? _out : Promise.resolve(_out);13171 return output.then((output2) => {13172 payload.value = output2;13173 return payload;13174 });13175 }13176 if (_out instanceof Promise) {13177 throw new $ZodAsyncError();13178 }13179 payload.value = _out;13180 return payload;13181 };13182});13183var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {13184 $ZodType.init(inst, def);13185 inst._zod.optin = "optional";13186 inst._zod.optout = "optional";13187 defineLazy(inst._zod, "values", () => {13188 return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;13189 });13190 defineLazy(inst._zod, "pattern", () => {13191 const pattern = def.innerType._zod.pattern;13192 return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;13193 });13194 inst._zod.parse = (payload, ctx) => {13195 if (def.innerType._zod.optin === "optional") {13196 return def.innerType._zod.run(payload, ctx);13197 }13198 if (payload.value === void 0) {13199 return payload;13200 }13201 return def.innerType._zod.run(payload, ctx);13202 };13203});13204var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {13205 $ZodType.init(inst, def);13206 defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);13207 defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);13208 defineLazy(inst._zod, "pattern", () => {13209 const pattern = def.innerType._zod.pattern;13210 return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;13211 });13212 defineLazy(inst._zod, "values", () => {13213 return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;13214 });13215 inst._zod.parse = (payload, ctx) => {13216 if (payload.value === null)13217 return payload;13218 return def.innerType._zod.run(payload, ctx);13219 };13220});13221var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {13222 $ZodType.init(inst, def);13223 inst._zod.optin = "optional";13224 defineLazy(inst._zod, "values", () => def.innerType._zod.values);13225 inst._zod.parse = (payload, ctx) => {13226 if (payload.value === void 0) {13227 payload.value = def.defaultValue;13228 return payload;13229 }13230 const result = def.innerType._zod.run(payload, ctx);13231 if (result instanceof Promise) {13232 return result.then((result2) => handleDefaultResult(result2, def));13233 }13234 return handleDefaultResult(result, def);13235 };13236});13237function handleDefaultResult(payload, def) {13238 if (payload.value === void 0) {13239 payload.value = def.defaultValue;13240 }13241 return payload;13242}13243var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {13244 $ZodType.init(inst, def);13245 inst._zod.optin = "optional";13246 defineLazy(inst._zod, "values", () => def.innerType._zod.values);13247 inst._zod.parse = (payload, ctx) => {13248 if (payload.value === void 0) {13249 payload.value = def.defaultValue;13250 }13251 return def.innerType._zod.run(payload, ctx);13252 };13253});13254var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {13255 $ZodType.init(inst, def);13256 defineLazy(inst._zod, "values", () => {13257 const v = def.innerType._zod.values;13258 return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;13259 });13260 inst._zod.parse = (payload, ctx) => {13261 const result = def.innerType._zod.run(payload, ctx);13262 if (result instanceof Promise) {13263 return result.then((result2) => handleNonOptionalResult(result2, inst));13264 }13265 return handleNonOptionalResult(result, inst);13266 };13267});13268function handleNonOptionalResult(payload, inst) {13269 if (!payload.issues.length && payload.value === void 0) {13270 payload.issues.push({13271 code: "invalid_type",13272 expected: "nonoptional",13273 input: payload.value,13274 inst13275 });13276 }13277 return payload;13278}13279var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {13280 $ZodType.init(inst, def);13281 inst._zod.optin = "optional";13282 defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);13283 defineLazy(inst._zod, "values", () => def.innerType._zod.values);13284 inst._zod.parse = (payload, ctx) => {13285 const result = def.innerType._zod.run(payload, ctx);13286 if (result instanceof Promise) {13287 return result.then((result2) => {13288 payload.value = result2.value;13289 if (result2.issues.length) {13290 payload.value = def.catchValue({13291 ...payload,13292 error: {13293 issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))13294 },13295 input: payload.value13296 });13297 payload.issues = [];13298 }13299 return payload;13300 });13301 }13302 payload.value = result.value;13303 if (result.issues.length) {13304 payload.value = def.catchValue({13305 ...payload,13306 error: {13307 issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))13308 },13309 input: payload.value13310 });13311 payload.issues = [];13312 }13313 return payload;13314 };13315});13316var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {13317 $ZodType.init(inst, def);13318 defineLazy(inst._zod, "values", () => def.in._zod.values);13319 defineLazy(inst._zod, "optin", () => def.in._zod.optin);13320 defineLazy(inst._zod, "optout", () => def.out._zod.optout);13321 inst._zod.parse = (payload, ctx) => {13322 const left = def.in._zod.run(payload, ctx);13323 if (left instanceof Promise) {13324 return left.then((left2) => handlePipeResult(left2, def, ctx));13325 }13326 return handlePipeResult(left, def, ctx);13327 };13328});13329function handlePipeResult(left, def, ctx) {13330 if (aborted(left)) {13331 return left;13332 }13333 return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);13334}13335var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {13336 $ZodType.init(inst, def);13337 defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);13338 defineLazy(inst._zod, "values", () => def.innerType._zod.values);13339 defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);13340 defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);13341 inst._zod.parse = (payload, ctx) => {13342 const result = def.innerType._zod.run(payload, ctx);13343 if (result instanceof Promise) {13344 return result.then(handleReadonlyResult);13345 }13346 return handleReadonlyResult(result);13347 };13348});13349function handleReadonlyResult(payload) {13350 payload.value = Object.freeze(payload.value);13351 return payload;13352}13353var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {13354 $ZodCheck.init(inst, def);13355 $ZodType.init(inst, def);13356 inst._zod.parse = (payload, _) => {13357 return payload;13358 };13359 inst._zod.check = (payload) => {13360 const input = payload.value;13361 const r = def.fn(input);13362 if (r instanceof Promise) {13363 return r.then((r2) => handleRefineResult(r2, payload, input, inst));13364 }13365 handleRefineResult(r, payload, input, inst);13366 return;13367 };13368});13369function handleRefineResult(result, payload, input, inst) {13370 if (!result) {13371 const _iss = {13372 code: "custom",13373 input,13374 inst,13375 // incorporates params.error into issue reporting13376 path: [...inst._zod.def.path ?? []],13377 // incorporates params.error into issue reporting13378 continue: !inst._zod.def.abort13379 // params: inst._zod.def.params,13380 };13381 if (inst._zod.def.params)13382 _iss.params = inst._zod.def.params;13383 payload.issues.push(issue(_iss));13384 }13385}1338613387// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/en.js13388var parsedType = (data) => {13389 const t = typeof data;13390 switch (t) {13391 case "number": {13392 return Number.isNaN(data) ? "NaN" : "number";13393 }13394 case "object": {13395 if (Array.isArray(data)) {13396 return "array";13397 }13398 if (data === null) {13399 return "null";13400 }13401 if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {13402 return data.constructor.name;13403 }13404 }13405 }13406 return t;13407};13408var error = () => {13409 const Sizable = {13410 string: { unit: "characters", verb: "to have" },13411 file: { unit: "bytes", verb: "to have" },13412 array: { unit: "items", verb: "to have" },13413 set: { unit: "items", verb: "to have" }13414 };13415 function getSizing(origin) {13416 return Sizable[origin] ?? null;13417 }13418 const Nouns = {13419 regex: "input",13420 email: "email address",13421 url: "URL",13422 emoji: "emoji",13423 uuid: "UUID",13424 uuidv4: "UUIDv4",13425 uuidv6: "UUIDv6",13426 nanoid: "nanoid",13427 guid: "GUID",13428 cuid: "cuid",13429 cuid2: "cuid2",13430 ulid: "ULID",13431 xid: "XID",13432 ksuid: "KSUID",13433 datetime: "ISO datetime",13434 date: "ISO date",13435 time: "ISO time",13436 duration: "ISO duration",13437 ipv4: "IPv4 address",13438 ipv6: "IPv6 address",13439 cidrv4: "IPv4 range",13440 cidrv6: "IPv6 range",13441 base64: "base64-encoded string",13442 base64url: "base64url-encoded string",13443 json_string: "JSON string",13444 e164: "E.164 number",13445 jwt: "JWT",13446 template_literal: "input"13447 };13448 return (issue2) => {13449 switch (issue2.code) {13450 case "invalid_type":13451 return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`;13452 case "invalid_value":13453 if (issue2.values.length === 1)13454 return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;13455 return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;13456 case "too_big": {13457 const adj = issue2.inclusive ? "<=" : "<";13458 const sizing = getSizing(issue2.origin);13459 if (sizing)13460 return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;13461 return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;13462 }13463 case "too_small": {13464 const adj = issue2.inclusive ? ">=" : ">";13465 const sizing = getSizing(issue2.origin);13466 if (sizing) {13467 return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;13468 }13469 return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;13470 }13471 case "invalid_format": {13472 const _issue = issue2;13473 if (_issue.format === "starts_with") {13474 return `Invalid string: must start with "${_issue.prefix}"`;13475 }13476 if (_issue.format === "ends_with")13477 return `Invalid string: must end with "${_issue.suffix}"`;13478 if (_issue.format === "includes")13479 return `Invalid string: must include "${_issue.includes}"`;13480 if (_issue.format === "regex")13481 return `Invalid string: must match pattern ${_issue.pattern}`;13482 return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;13483 }13484 case "not_multiple_of":13485 return `Invalid number: must be a multiple of ${issue2.divisor}`;13486 case "unrecognized_keys":13487 return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;13488 case "invalid_key":13489 return `Invalid key in ${issue2.origin}`;13490 case "invalid_union":13491 return "Invalid input";13492 case "invalid_element":13493 return `Invalid value in ${issue2.origin}`;13494 default:13495 return `Invalid input`;13496 }13497 };13498};13499function en_default2() {13500 return {13501 localeError: error()13502 };13503}1350413505// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js13506var $output = Symbol("ZodOutput");13507var $input = Symbol("ZodInput");13508var $ZodRegistry = class {13509 constructor() {13510 this._map = /* @__PURE__ */ new Map();13511 this._idmap = /* @__PURE__ */ new Map();13512 }13513 add(schema, ..._meta) {13514 const meta = _meta[0];13515 this._map.set(schema, meta);13516 if (meta && typeof meta === "object" && "id" in meta) {13517 if (this._idmap.has(meta.id)) {13518 throw new Error(`ID ${meta.id} already exists in the registry`);13519 }13520 this._idmap.set(meta.id, schema);13521 }13522 return this;13523 }13524 clear() {13525 this._map = /* @__PURE__ */ new Map();13526 this._idmap = /* @__PURE__ */ new Map();13527 return this;13528 }13529 remove(schema) {13530 const meta = this._map.get(schema);13531 if (meta && typeof meta === "object" && "id" in meta) {13532 this._idmap.delete(meta.id);13533 }13534 this._map.delete(schema);13535 return this;13536 }13537 get(schema) {13538 const p = schema._zod.parent;13539 if (p) {13540 const pm = { ...this.get(p) ?? {} };13541 delete pm.id;13542 return { ...pm, ...this._map.get(schema) };13543 }13544 return this._map.get(schema);13545 }13546 has(schema) {13547 return this._map.has(schema);13548 }13549};13550function registry() {13551 return new $ZodRegistry();13552}13553var globalRegistry = /* @__PURE__ */ registry();1355413555// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js13556function _string(Class2, params) {13557 return new Class2({13558 type: "string",13559 ...normalizeParams(params)13560 });13561}13562function _email(Class2, params) {13563 return new Class2({13564 type: "string",13565 format: "email",13566 check: "string_format",13567 abort: false,13568 ...normalizeParams(params)13569 });13570}13571function _guid(Class2, params) {13572 return new Class2({13573 type: "string",13574 format: "guid",13575 check: "string_format",13576 abort: false,13577 ...normalizeParams(params)13578 });13579}13580function _uuid(Class2, params) {13581 return new Class2({13582 type: "string",13583 format: "uuid",13584 check: "string_format",13585 abort: false,13586 ...normalizeParams(params)13587 });13588}13589function _uuidv4(Class2, params) {13590 return new Class2({13591 type: "string",13592 format: "uuid",13593 check: "string_format",13594 abort: false,13595 version: "v4",13596 ...normalizeParams(params)13597 });13598}13599function _uuidv6(Class2, params) {13600 return new Class2({13601 type: "string",13602 format: "uuid",13603 check: "string_format",13604 abort: false,13605 version: "v6",13606 ...normalizeParams(params)13607 });13608}13609function _uuidv7(Class2, params) {13610 return new Class2({13611 type: "string",13612 format: "uuid",13613 check: "string_format",13614 abort: false,13615 version: "v7",13616 ...normalizeParams(params)13617 });13618}13619function _url(Class2, params) {13620 return new Class2({13621 type: "string",13622 format: "url",13623 check: "string_format",13624 abort: false,13625 ...normalizeParams(params)13626 });13627}13628function _emoji2(Class2, params) {13629 return new Class2({13630 type: "string",13631 format: "emoji",13632 check: "string_format",13633 abort: false,13634 ...normalizeParams(params)13635 });13636}13637function _nanoid(Class2, params) {13638 return new Class2({13639 type: "string",13640 format: "nanoid",13641 check: "string_format",13642 abort: false,13643 ...normalizeParams(params)13644 });13645}13646function _cuid(Class2, params) {13647 return new Class2({13648 type: "string",13649 format: "cuid",13650 check: "string_format",13651 abort: false,13652 ...normalizeParams(params)13653 });13654}13655function _cuid2(Class2, params) {13656 return new Class2({13657 type: "string",13658 format: "cuid2",13659 check: "string_format",13660 abort: false,13661 ...normalizeParams(params)13662 });13663}13664function _ulid(Class2, params) {13665 return new Class2({13666 type: "string",13667 format: "ulid",13668 check: "string_format",13669 abort: false,13670 ...normalizeParams(params)13671 });13672}13673function _xid(Class2, params) {13674 return new Class2({13675 type: "string",13676 format: "xid",13677 check: "string_format",13678 abort: false,13679 ...normalizeParams(params)13680 });13681}13682function _ksuid(Class2, params) {13683 return new Class2({13684 type: "string",13685 format: "ksuid",13686 check: "string_format",13687 abort: false,13688 ...normalizeParams(params)13689 });13690}13691function _ipv4(Class2, params) {13692 return new Class2({13693 type: "string",13694 format: "ipv4",13695 check: "string_format",13696 abort: false,13697 ...normalizeParams(params)13698 });13699}13700function _ipv6(Class2, params) {13701 return new Class2({13702 type: "string",13703 format: "ipv6",13704 check: "string_format",13705 abort: false,13706 ...normalizeParams(params)13707 });13708}13709function _cidrv4(Class2, params) {13710 return new Class2({13711 type: "string",13712 format: "cidrv4",13713 check: "string_format",13714 abort: false,13715 ...normalizeParams(params)13716 });13717}13718function _cidrv6(Class2, params) {13719 return new Class2({13720 type: "string",13721 format: "cidrv6",13722 check: "string_format",13723 abort: false,13724 ...normalizeParams(params)13725 });13726}13727function _base64(Class2, params) {13728 return new Class2({13729 type: "string",13730 format: "base64",13731 check: "string_format",13732 abort: false,13733 ...normalizeParams(params)13734 });13735}13736function _base64url(Class2, params) {13737 return new Class2({13738 type: "string",13739 format: "base64url",13740 check: "string_format",13741 abort: false,13742 ...normalizeParams(params)13743 });13744}13745function _e164(Class2, params) {13746 return new Class2({13747 type: "string",13748 format: "e164",13749 check: "string_format",13750 abort: false,13751 ...normalizeParams(params)13752 });13753}13754function _jwt(Class2, params) {13755 return new Class2({13756 type: "string",13757 format: "jwt",13758 check: "string_format",13759 abort: false,13760 ...normalizeParams(params)13761 });13762}13763function _isoDateTime(Class2, params) {13764 return new Class2({13765 type: "string",13766 format: "datetime",13767 check: "string_format",13768 offset: false,13769 local: false,13770 precision: null,13771 ...normalizeParams(params)13772 });13773}13774function _isoDate(Class2, params) {13775 return new Class2({13776 type: "string",13777 format: "date",13778 check: "string_format",13779 ...normalizeParams(params)13780 });13781}13782function _isoTime(Class2, params) {13783 return new Class2({13784 type: "string",13785 format: "time",13786 check: "string_format",13787 precision: null,13788 ...normalizeParams(params)13789 });13790}13791function _isoDuration(Class2, params) {13792 return new Class2({13793 type: "string",13794 format: "duration",13795 check: "string_format",13796 ...normalizeParams(params)13797 });13798}13799function _number(Class2, params) {13800 return new Class2({13801 type: "number",13802 checks: [],13803 ...normalizeParams(params)13804 });13805}13806function _int(Class2, params) {13807 return new Class2({13808 type: "number",13809 check: "number_format",13810 abort: false,13811 format: "safeint",13812 ...normalizeParams(params)13813 });13814}13815function _boolean(Class2, params) {13816 return new Class2({13817 type: "boolean",13818 ...normalizeParams(params)13819 });13820}13821function _null2(Class2, params) {13822 return new Class2({13823 type: "null",13824 ...normalizeParams(params)13825 });13826}13827function _unknown(Class2) {13828 return new Class2({13829 type: "unknown"13830 });13831}13832function _never(Class2, params) {13833 return new Class2({13834 type: "never",13835 ...normalizeParams(params)13836 });13837}13838function _lt(value, params) {13839 return new $ZodCheckLessThan({13840 check: "less_than",13841 ...normalizeParams(params),13842 value,13843 inclusive: false13844 });13845}13846function _lte(value, params) {13847 return new $ZodCheckLessThan({13848 check: "less_than",13849 ...normalizeParams(params),13850 value,13851 inclusive: true13852 });13853}13854function _gt(value, params) {13855 return new $ZodCheckGreaterThan({13856 check: "greater_than",13857 ...normalizeParams(params),13858 value,13859 inclusive: false13860 });13861}13862function _gte(value, params) {13863 return new $ZodCheckGreaterThan({13864 check: "greater_than",13865 ...normalizeParams(params),13866 value,13867 inclusive: true13868 });13869}13870function _multipleOf(value, params) {13871 return new $ZodCheckMultipleOf({13872 check: "multiple_of",13873 ...normalizeParams(params),13874 value13875 });13876}13877function _maxLength(maximum, params) {13878 const ch = new $ZodCheckMaxLength({13879 check: "max_length",13880 ...normalizeParams(params),13881 maximum13882 });13883 return ch;13884}13885function _minLength(minimum, params) {13886 return new $ZodCheckMinLength({13887 check: "min_length",13888 ...normalizeParams(params),13889 minimum13890 });13891}13892function _length(length, params) {13893 return new $ZodCheckLengthEquals({13894 check: "length_equals",13895 ...normalizeParams(params),13896 length13897 });13898}13899function _regex(pattern, params) {13900 return new $ZodCheckRegex({13901 check: "string_format",13902 format: "regex",13903 ...normalizeParams(params),13904 pattern13905 });13906}13907function _lowercase(params) {13908 return new $ZodCheckLowerCase({13909 check: "string_format",13910 format: "lowercase",13911 ...normalizeParams(params)13912 });13913}13914function _uppercase(params) {13915 return new $ZodCheckUpperCase({13916 check: "string_format",13917 format: "uppercase",13918 ...normalizeParams(params)13919 });13920}13921function _includes(includes, params) {13922 return new $ZodCheckIncludes({13923 check: "string_format",13924 format: "includes",13925 ...normalizeParams(params),13926 includes13927 });13928}13929function _startsWith(prefix, params) {13930 return new $ZodCheckStartsWith({13931 check: "string_format",13932 format: "starts_with",13933 ...normalizeParams(params),13934 prefix13935 });13936}13937function _endsWith(suffix, params) {13938 return new $ZodCheckEndsWith({13939 check: "string_format",13940 format: "ends_with",13941 ...normalizeParams(params),13942 suffix13943 });13944}13945function _overwrite(tx) {13946 return new $ZodCheckOverwrite({13947 check: "overwrite",13948 tx13949 });13950}13951function _normalize(form) {13952 return _overwrite((input) => input.normalize(form));13953}13954function _trim() {13955 return _overwrite((input) => input.trim());13956}13957function _toLowerCase() {13958 return _overwrite((input) => input.toLowerCase());13959}13960function _toUpperCase() {13961 return _overwrite((input) => input.toUpperCase());13962}13963function _array(Class2, element, params) {13964 return new Class2({13965 type: "array",13966 element,13967 // get element() {13968 // return element;13969 // },13970 ...normalizeParams(params)13971 });13972}13973function _custom(Class2, fn, _params) {13974 const norm = normalizeParams(_params);13975 norm.abort ?? (norm.abort = true);13976 const schema = new Class2({13977 type: "custom",13978 check: "custom",13979 fn,13980 ...norm13981 });13982 return schema;13983}13984function _refine(Class2, fn, _params) {13985 const schema = new Class2({13986 type: "custom",13987 check: "custom",13988 fn,13989 ...normalizeParams(_params)13990 });13991 return schema;13992}1399313994// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js13995var JSONSchemaGenerator = class {13996 constructor(params) {13997 this.counter = 0;13998 this.metadataRegistry = params?.metadata ?? globalRegistry;13999 this.target = params?.target ?? "draft-2020-12";14000 this.unrepresentable = params?.unrepresentable ?? "throw";14001 this.override = params?.override ?? (() => {14002 });14003 this.io = params?.io ?? "output";14004 this.seen = /* @__PURE__ */ new Map();14005 }14006 process(schema, _params = { path: [], schemaPath: [] }) {14007 var _a;14008 const def = schema._zod.def;14009 const formatMap = {14010 guid: "uuid",14011 url: "uri",14012 datetime: "date-time",14013 json_string: "json-string",14014 regex: ""14015 // do not set14016 };14017 const seen = this.seen.get(schema);14018 if (seen) {14019 seen.count++;14020 const isCycle = _params.schemaPath.includes(schema);14021 if (isCycle) {14022 seen.cycle = _params.path;14023 }14024 return seen.schema;14025 }14026 const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };14027 this.seen.set(schema, result);14028 const overrideSchema = schema._zod.toJSONSchema?.();14029 if (overrideSchema) {14030 result.schema = overrideSchema;14031 } else {14032 const params = {14033 ..._params,14034 schemaPath: [..._params.schemaPath, schema],14035 path: _params.path14036 };14037 const parent = schema._zod.parent;14038 if (parent) {14039 result.ref = parent;14040 this.process(parent, params);14041 this.seen.get(parent).isParent = true;14042 } else {14043 const _json = result.schema;14044 switch (def.type) {14045 case "string": {14046 const json = _json;14047 json.type = "string";14048 const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;14049 if (typeof minimum === "number")14050 json.minLength = minimum;14051 if (typeof maximum === "number")14052 json.maxLength = maximum;14053 if (format) {14054 json.format = formatMap[format] ?? format;14055 if (json.format === "")14056 delete json.format;14057 }14058 if (contentEncoding)14059 json.contentEncoding = contentEncoding;14060 if (patterns && patterns.size > 0) {14061 const regexes = [...patterns];14062 if (regexes.length === 1)14063 json.pattern = regexes[0].source;14064 else if (regexes.length > 1) {14065 result.schema.allOf = [14066 ...regexes.map((regex) => ({14067 ...this.target === "draft-7" ? { type: "string" } : {},14068 pattern: regex.source14069 }))14070 ];14071 }14072 }14073 break;14074 }14075 case "number": {14076 const json = _json;14077 const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;14078 if (typeof format === "string" && format.includes("int"))14079 json.type = "integer";14080 else14081 json.type = "number";14082 if (typeof exclusiveMinimum === "number")14083 json.exclusiveMinimum = exclusiveMinimum;14084 if (typeof minimum === "number") {14085 json.minimum = minimum;14086 if (typeof exclusiveMinimum === "number") {14087 if (exclusiveMinimum >= minimum)14088 delete json.minimum;14089 else14090 delete json.exclusiveMinimum;14091 }14092 }14093 if (typeof exclusiveMaximum === "number")14094 json.exclusiveMaximum = exclusiveMaximum;14095 if (typeof maximum === "number") {14096 json.maximum = maximum;14097 if (typeof exclusiveMaximum === "number") {14098 if (exclusiveMaximum <= maximum)14099 delete json.maximum;14100 else14101 delete json.exclusiveMaximum;14102 }14103 }14104 if (typeof multipleOf === "number")14105 json.multipleOf = multipleOf;14106 break;14107 }14108 case "boolean": {14109 const json = _json;14110 json.type = "boolean";14111 break;14112 }14113 case "bigint": {14114 if (this.unrepresentable === "throw") {14115 throw new Error("BigInt cannot be represented in JSON Schema");14116 }14117 break;14118 }14119 case "symbol": {14120 if (this.unrepresentable === "throw") {14121 throw new Error("Symbols cannot be represented in JSON Schema");14122 }14123 break;14124 }14125 case "null": {14126 _json.type = "null";14127 break;14128 }14129 case "any": {14130 break;14131 }14132 case "unknown": {14133 break;14134 }14135 case "undefined": {14136 if (this.unrepresentable === "throw") {14137 throw new Error("Undefined cannot be represented in JSON Schema");14138 }14139 break;14140 }14141 case "void": {14142 if (this.unrepresentable === "throw") {14143 throw new Error("Void cannot be represented in JSON Schema");14144 }14145 break;14146 }14147 case "never": {14148 _json.not = {};14149 break;14150 }14151 case "date": {14152 if (this.unrepresentable === "throw") {14153 throw new Error("Date cannot be represented in JSON Schema");14154 }14155 break;14156 }14157 case "array": {14158 const json = _json;14159 const { minimum, maximum } = schema._zod.bag;14160 if (typeof minimum === "number")14161 json.minItems = minimum;14162 if (typeof maximum === "number")14163 json.maxItems = maximum;14164 json.type = "array";14165 json.items = this.process(def.element, { ...params, path: [...params.path, "items"] });14166 break;14167 }14168 case "object": {14169 const json = _json;14170 json.type = "object";14171 json.properties = {};14172 const shape = def.shape;14173 for (const key in shape) {14174 json.properties[key] = this.process(shape[key], {14175 ...params,14176 path: [...params.path, "properties", key]14177 });14178 }14179 const allKeys = new Set(Object.keys(shape));14180 const requiredKeys = new Set([...allKeys].filter((key) => {14181 const v = def.shape[key]._zod;14182 if (this.io === "input") {14183 return v.optin === void 0;14184 } else {14185 return v.optout === void 0;14186 }14187 }));14188 if (requiredKeys.size > 0) {14189 json.required = Array.from(requiredKeys);14190 }14191 if (def.catchall?._zod.def.type === "never") {14192 json.additionalProperties = false;14193 } else if (!def.catchall) {14194 if (this.io === "output")14195 json.additionalProperties = false;14196 } else if (def.catchall) {14197 json.additionalProperties = this.process(def.catchall, {14198 ...params,14199 path: [...params.path, "additionalProperties"]14200 });14201 }14202 break;14203 }14204 case "union": {14205 const json = _json;14206 json.anyOf = def.options.map((x, i) => this.process(x, {14207 ...params,14208 path: [...params.path, "anyOf", i]14209 }));14210 break;14211 }14212 case "intersection": {14213 const json = _json;14214 const a = this.process(def.left, {14215 ...params,14216 path: [...params.path, "allOf", 0]14217 });14218 const b = this.process(def.right, {14219 ...params,14220 path: [...params.path, "allOf", 1]14221 });14222 const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;14223 const allOf = [14224 ...isSimpleIntersection(a) ? a.allOf : [a],14225 ...isSimpleIntersection(b) ? b.allOf : [b]14226 ];14227 json.allOf = allOf;14228 break;14229 }14230 case "tuple": {14231 const json = _json;14232 json.type = "array";14233 const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] }));14234 if (this.target === "draft-2020-12") {14235 json.prefixItems = prefixItems;14236 } else {14237 json.items = prefixItems;14238 }14239 if (def.rest) {14240 const rest = this.process(def.rest, {14241 ...params,14242 path: [...params.path, "items"]14243 });14244 if (this.target === "draft-2020-12") {14245 json.items = rest;14246 } else {14247 json.additionalItems = rest;14248 }14249 }14250 if (def.rest) {14251 json.items = this.process(def.rest, {14252 ...params,14253 path: [...params.path, "items"]14254 });14255 }14256 const { minimum, maximum } = schema._zod.bag;14257 if (typeof minimum === "number")14258 json.minItems = minimum;14259 if (typeof maximum === "number")14260 json.maxItems = maximum;14261 break;14262 }14263 case "record": {14264 const json = _json;14265 json.type = "object";14266 json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] });14267 json.additionalProperties = this.process(def.valueType, {14268 ...params,14269 path: [...params.path, "additionalProperties"]14270 });14271 break;14272 }14273 case "map": {14274 if (this.unrepresentable === "throw") {14275 throw new Error("Map cannot be represented in JSON Schema");14276 }14277 break;14278 }14279 case "set": {14280 if (this.unrepresentable === "throw") {14281 throw new Error("Set cannot be represented in JSON Schema");14282 }14283 break;14284 }14285 case "enum": {14286 const json = _json;14287 const values = getEnumValues(def.entries);14288 if (values.every((v) => typeof v === "number"))14289 json.type = "number";14290 if (values.every((v) => typeof v === "string"))14291 json.type = "string";14292 json.enum = values;14293 break;14294 }14295 case "literal": {14296 const json = _json;14297 const vals = [];14298 for (const val of def.values) {14299 if (val === void 0) {14300 if (this.unrepresentable === "throw") {14301 throw new Error("Literal `undefined` cannot be represented in JSON Schema");14302 } else {14303 }14304 } else if (typeof val === "bigint") {14305 if (this.unrepresentable === "throw") {14306 throw new Error("BigInt literals cannot be represented in JSON Schema");14307 } else {14308 vals.push(Number(val));14309 }14310 } else {14311 vals.push(val);14312 }14313 }14314 if (vals.length === 0) {14315 } else if (vals.length === 1) {14316 const val = vals[0];14317 json.type = val === null ? "null" : typeof val;14318 json.const = val;14319 } else {14320 if (vals.every((v) => typeof v === "number"))14321 json.type = "number";14322 if (vals.every((v) => typeof v === "string"))14323 json.type = "string";14324 if (vals.every((v) => typeof v === "boolean"))14325 json.type = "string";14326 if (vals.every((v) => v === null))14327 json.type = "null";14328 json.enum = vals;14329 }14330 break;14331 }14332 case "file": {14333 const json = _json;14334 const file = {14335 type: "string",14336 format: "binary",14337 contentEncoding: "binary"14338 };14339 const { minimum, maximum, mime } = schema._zod.bag;14340 if (minimum !== void 0)14341 file.minLength = minimum;14342 if (maximum !== void 0)14343 file.maxLength = maximum;14344 if (mime) {14345 if (mime.length === 1) {14346 file.contentMediaType = mime[0];14347 Object.assign(json, file);14348 } else {14349 json.anyOf = mime.map((m) => {14350 const mFile = { ...file, contentMediaType: m };14351 return mFile;14352 });14353 }14354 } else {14355 Object.assign(json, file);14356 }14357 break;14358 }14359 case "transform": {14360 if (this.unrepresentable === "throw") {14361 throw new Error("Transforms cannot be represented in JSON Schema");14362 }14363 break;14364 }14365 case "nullable": {14366 const inner = this.process(def.innerType, params);14367 _json.anyOf = [inner, { type: "null" }];14368 break;14369 }14370 case "nonoptional": {14371 this.process(def.innerType, params);14372 result.ref = def.innerType;14373 break;14374 }14375 case "success": {14376 const json = _json;14377 json.type = "boolean";14378 break;14379 }14380 case "default": {14381 this.process(def.innerType, params);14382 result.ref = def.innerType;14383 _json.default = JSON.parse(JSON.stringify(def.defaultValue));14384 break;14385 }14386 case "prefault": {14387 this.process(def.innerType, params);14388 result.ref = def.innerType;14389 if (this.io === "input")14390 _json._prefault = JSON.parse(JSON.stringify(def.defaultValue));14391 break;14392 }14393 case "catch": {14394 this.process(def.innerType, params);14395 result.ref = def.innerType;14396 let catchValue;14397 try {14398 catchValue = def.catchValue(void 0);14399 } catch {14400 throw new Error("Dynamic catch values are not supported in JSON Schema");14401 }14402 _json.default = catchValue;14403 break;14404 }14405 case "nan": {14406 if (this.unrepresentable === "throw") {14407 throw new Error("NaN cannot be represented in JSON Schema");14408 }14409 break;14410 }14411 case "template_literal": {14412 const json = _json;14413 const pattern = schema._zod.pattern;14414 if (!pattern)14415 throw new Error("Pattern not found in template literal");14416 json.type = "string";14417 json.pattern = pattern.source;14418 break;14419 }14420 case "pipe": {14421 const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;14422 this.process(innerType, params);14423 result.ref = innerType;14424 break;14425 }14426 case "readonly": {14427 this.process(def.innerType, params);14428 result.ref = def.innerType;14429 _json.readOnly = true;14430 break;14431 }14432 // passthrough types14433 case "promise": {14434 this.process(def.innerType, params);14435 result.ref = def.innerType;14436 break;14437 }14438 case "optional": {14439 this.process(def.innerType, params);14440 result.ref = def.innerType;14441 break;14442 }14443 case "lazy": {14444 const innerType = schema._zod.innerType;14445 this.process(innerType, params);14446 result.ref = innerType;14447 break;14448 }14449 case "custom": {14450 if (this.unrepresentable === "throw") {14451 throw new Error("Custom types cannot be represented in JSON Schema");14452 }14453 break;14454 }14455 default: {14456 def;14457 }14458 }14459 }14460 }14461 const meta = this.metadataRegistry.get(schema);14462 if (meta)14463 Object.assign(result.schema, meta);14464 if (this.io === "input" && isTransforming(schema)) {14465 delete result.schema.examples;14466 delete result.schema.default;14467 }14468 if (this.io === "input" && result.schema._prefault)14469 (_a = result.schema).default ?? (_a.default = result.schema._prefault);14470 delete result.schema._prefault;14471 const _result = this.seen.get(schema);14472 return _result.schema;14473 }14474 emit(schema, _params) {14475 const params = {14476 cycles: _params?.cycles ?? "ref",14477 reused: _params?.reused ?? "inline",14478 // unrepresentable: _params?.unrepresentable ?? "throw",14479 // uri: _params?.uri ?? ((id) => `${id}`),14480 external: _params?.external ?? void 014481 };14482 const root = this.seen.get(schema);14483 if (!root)14484 throw new Error("Unprocessed schema. This is a bug in Zod.");14485 const makeURI = (entry) => {14486 const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";14487 if (params.external) {14488 const externalId = params.external.registry.get(entry[0])?.id;14489 const uriGenerator = params.external.uri ?? ((id2) => id2);14490 if (externalId) {14491 return { ref: uriGenerator(externalId) };14492 }14493 const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;14494 entry[1].defId = id;14495 return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };14496 }14497 if (entry[1] === root) {14498 return { ref: "#" };14499 }14500 const uriPrefix = `#`;14501 const defUriPrefix = `${uriPrefix}/${defsSegment}/`;14502 const defId = entry[1].schema.id ?? `__schema${this.counter++}`;14503 return { defId, ref: defUriPrefix + defId };14504 };14505 const extractToDef = (entry) => {14506 if (entry[1].schema.$ref) {14507 return;14508 }14509 const seen = entry[1];14510 const { ref, defId } = makeURI(entry);14511 seen.def = { ...seen.schema };14512 if (defId)14513 seen.defId = defId;14514 const schema2 = seen.schema;14515 for (const key in schema2) {14516 delete schema2[key];14517 }14518 schema2.$ref = ref;14519 };14520 if (params.cycles === "throw") {14521 for (const entry of this.seen.entries()) {14522 const seen = entry[1];14523 if (seen.cycle) {14524 throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>1452514526Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);14527 }14528 }14529 }14530 for (const entry of this.seen.entries()) {14531 const seen = entry[1];14532 if (schema === entry[0]) {14533 extractToDef(entry);14534 continue;14535 }14536 if (params.external) {14537 const ext = params.external.registry.get(entry[0])?.id;14538 if (schema !== entry[0] && ext) {14539 extractToDef(entry);14540 continue;14541 }14542 }14543 const id = this.metadataRegistry.get(entry[0])?.id;14544 if (id) {14545 extractToDef(entry);14546 continue;14547 }14548 if (seen.cycle) {14549 extractToDef(entry);14550 continue;14551 }14552 if (seen.count > 1) {14553 if (params.reused === "ref") {14554 extractToDef(entry);14555 continue;14556 }14557 }14558 }14559 const flattenRef = (zodSchema, params2) => {14560 const seen = this.seen.get(zodSchema);14561 const schema2 = seen.def ?? seen.schema;14562 const _cached = { ...schema2 };14563 if (seen.ref === null) {14564 return;14565 }14566 const ref = seen.ref;14567 seen.ref = null;14568 if (ref) {14569 flattenRef(ref, params2);14570 const refSchema = this.seen.get(ref).schema;14571 if (refSchema.$ref && params2.target === "draft-7") {14572 schema2.allOf = schema2.allOf ?? [];14573 schema2.allOf.push(refSchema);14574 } else {14575 Object.assign(schema2, refSchema);14576 Object.assign(schema2, _cached);14577 }14578 }14579 if (!seen.isParent)14580 this.override({14581 zodSchema,14582 jsonSchema: schema2,14583 path: seen.path ?? []14584 });14585 };14586 for (const entry of [...this.seen.entries()].reverse()) {14587 flattenRef(entry[0], { target: this.target });14588 }14589 const result = {};14590 if (this.target === "draft-2020-12") {14591 result.$schema = "https://json-schema.org/draft/2020-12/schema";14592 } else if (this.target === "draft-7") {14593 result.$schema = "http://json-schema.org/draft-07/schema#";14594 } else {14595 console.warn(`Invalid target: ${this.target}`);14596 }14597 if (params.external?.uri) {14598 const id = params.external.registry.get(schema)?.id;14599 if (!id)14600 throw new Error("Schema is missing an `id` property");14601 result.$id = params.external.uri(id);14602 }14603 Object.assign(result, root.def);14604 const defs = params.external?.defs ?? {};14605 for (const entry of this.seen.entries()) {14606 const seen = entry[1];14607 if (seen.def && seen.defId) {14608 defs[seen.defId] = seen.def;14609 }14610 }14611 if (params.external) {14612 } else {14613 if (Object.keys(defs).length > 0) {14614 if (this.target === "draft-2020-12") {14615 result.$defs = defs;14616 } else {14617 result.definitions = defs;14618 }14619 }14620 }14621 try {14622 return JSON.parse(JSON.stringify(result));14623 } catch (_err) {14624 throw new Error("Error converting schema to JSON.");14625 }14626 }14627};14628function toJSONSchema(input, _params) {14629 if (input instanceof $ZodRegistry) {14630 const gen2 = new JSONSchemaGenerator(_params);14631 const defs = {};14632 for (const entry of input._idmap.entries()) {14633 const [_, schema] = entry;14634 gen2.process(schema);14635 }14636 const schemas = {};14637 const external = {14638 registry: input,14639 uri: _params?.uri,14640 defs14641 };14642 for (const entry of input._idmap.entries()) {14643 const [key, schema] = entry;14644 schemas[key] = gen2.emit(schema, {14645 ..._params,14646 external14647 });14648 }14649 if (Object.keys(defs).length > 0) {14650 const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions";14651 schemas.__shared = {14652 [defsSegment]: defs14653 };14654 }14655 return { schemas };14656 }14657 const gen = new JSONSchemaGenerator(_params);14658 gen.process(input);14659 return gen.emit(input, _params);14660}14661function isTransforming(_schema, _ctx) {14662 const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };14663 if (ctx.seen.has(_schema))14664 return false;14665 ctx.seen.add(_schema);14666 const schema = _schema;14667 const def = schema._zod.def;14668 switch (def.type) {14669 case "string":14670 case "number":14671 case "bigint":14672 case "boolean":14673 case "date":14674 case "symbol":14675 case "undefined":14676 case "null":14677 case "any":14678 case "unknown":14679 case "never":14680 case "void":14681 case "literal":14682 case "enum":14683 case "nan":14684 case "file":14685 case "template_literal":14686 return false;14687 case "array": {14688 return isTransforming(def.element, ctx);14689 }14690 case "object": {14691 for (const key in def.shape) {14692 if (isTransforming(def.shape[key], ctx))14693 return true;14694 }14695 return false;14696 }14697 case "union": {14698 for (const option of def.options) {14699 if (isTransforming(option, ctx))14700 return true;14701 }14702 return false;14703 }14704 case "intersection": {14705 return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);14706 }14707 case "tuple": {14708 for (const item of def.items) {14709 if (isTransforming(item, ctx))14710 return true;14711 }14712 if (def.rest && isTransforming(def.rest, ctx))14713 return true;14714 return false;14715 }14716 case "record": {14717 return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);14718 }14719 case "map": {14720 return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);14721 }14722 case "set": {14723 return isTransforming(def.valueType, ctx);14724 }14725 // inner types14726 case "promise":14727 case "optional":14728 case "nonoptional":14729 case "nullable":14730 case "readonly":14731 return isTransforming(def.innerType, ctx);14732 case "lazy":14733 return isTransforming(def.getter(), ctx);14734 case "default": {14735 return isTransforming(def.innerType, ctx);14736 }14737 case "prefault": {14738 return isTransforming(def.innerType, ctx);14739 }14740 case "custom": {14741 return false;14742 }14743 case "transform": {14744 return true;14745 }14746 case "pipe": {14747 return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);14748 }14749 case "success": {14750 return false;14751 }14752 case "catch": {14753 return false;14754 }14755 default:14756 def;14757 }14758 throw new Error(`Unknown schema type: ${def.type}`);14759}1476014761// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/mini/schemas.js14762var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {14763 if (!inst._zod)14764 throw new Error("Uninitialized schema in ZodMiniType.");14765 $ZodType.init(inst, def);14766 inst.def = def;14767 inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });14768 inst.safeParse = (data, params) => safeParse(inst, data, params);14769 inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });14770 inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);14771 inst.check = (...checks) => {14772 return inst.clone(14773 {14774 ...def,14775 checks: [14776 ...def.checks ?? [],14777 ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)14778 ]14779 }14780 // { parent: true }14781 );14782 };14783 inst.clone = (_def, params) => clone(inst, _def, params);14784 inst.brand = () => inst;14785 inst.register = (reg, meta) => {14786 reg.add(inst, meta);14787 return inst;14788 };14789});14790var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => {14791 $ZodObject.init(inst, def);14792 ZodMiniType.init(inst, def);14793 util_exports.defineLazy(inst, "shape", () => def.shape);14794});14795function object(shape, params) {14796 const def = {14797 type: "object",14798 get shape() {14799 util_exports.assignProp(this, "shape", { ...shape });14800 return this.shape;14801 },14802 ...util_exports.normalizeParams(params)14803 };14804 return new ZodMiniObject(def);14805}1480614807// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js14808function isZ4Schema(s) {14809 const schema = s;14810 return !!schema._zod;14811}14812function objectFromShape(shape) {14813 const values = Object.values(shape);14814 if (values.length === 0)14815 return object({});14816 const allV4 = values.every(isZ4Schema);14817 const allV3 = values.every((s) => !isZ4Schema(s));14818 if (allV4)14819 return object(shape);14820 if (allV3)14821 return objectType(shape);14822 throw new Error("Mixed Zod versions detected in object shape.");14823}14824function safeParse2(schema, data) {14825 if (isZ4Schema(schema)) {14826 const result2 = safeParse(schema, data);14827 return result2;14828 }14829 const v3Schema = schema;14830 const result = v3Schema.safeParse(data);14831 return result;14832}14833async function safeParseAsync2(schema, data) {14834 if (isZ4Schema(schema)) {14835 const result2 = await safeParseAsync(schema, data);14836 return result2;14837 }14838 const v3Schema = schema;14839 const result = await v3Schema.safeParseAsync(data);14840 return result;14841}14842function getObjectShape(schema) {14843 if (!schema)14844 return void 0;14845 let rawShape;14846 if (isZ4Schema(schema)) {14847 const v4Schema = schema;14848 rawShape = v4Schema._zod?.def?.shape;14849 } else {14850 const v3Schema = schema;14851 rawShape = v3Schema.shape;14852 }14853 if (!rawShape)14854 return void 0;14855 if (typeof rawShape === "function") {14856 try {14857 return rawShape();14858 } catch {14859 return void 0;14860 }14861 }14862 return rawShape;14863}14864function normalizeObjectSchema(schema) {14865 if (!schema)14866 return void 0;14867 if (typeof schema === "object") {14868 const asV3 = schema;14869 const asV4 = schema;14870 if (!asV3._def && !asV4._zod) {14871 const values = Object.values(schema);14872 if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) {14873 return objectFromShape(schema);14874 }14875 }14876 }14877 if (isZ4Schema(schema)) {14878 const v4Schema = schema;14879 const def = v4Schema._zod?.def;14880 if (def && (def.type === "object" || def.shape !== void 0)) {14881 return schema;14882 }14883 } else {14884 const v3Schema = schema;14885 if (v3Schema.shape !== void 0) {14886 return schema;14887 }14888 }14889 return void 0;14890}14891function getDotPath(path) {14892 if (path.length === 0) {14893 return "object root";14894 }14895 return path.reduce((acc, seg, index) => {14896 if (index === 0) {14897 return String(seg);14898 }14899 if (typeof seg === "number") {14900 return `${acc}[${seg}]`;14901 }14902 return `${acc}.${seg}`;14903 }, "");14904}14905function getParseErrorMessage(error2) {14906 if (error2 && typeof error2 === "object") {14907 if ("issues" in error2 && Array.isArray(error2.issues) && error2.issues.length > 0) {14908 return error2.issues.map((i) => {14909 if (!i.path?.length) {14910 return i.message;14911 }14912 return `${i.message} at ${getDotPath(i.path)}`;14913 }).join("\n");14914 }14915 if ("message" in error2 && typeof error2.message === "string") {14916 return error2.message;14917 }14918 try {14919 return JSON.stringify(error2);14920 } catch {14921 return String(error2);14922 }14923 }14924 return String(error2);14925}14926function getSchemaDescription(schema) {14927 return schema.description;14928}14929function isSchemaOptional(schema) {14930 if (isZ4Schema(schema)) {14931 const v4Schema = schema;14932 return v4Schema._zod?.def?.type === "optional";14933 }14934 const v3Schema = schema;14935 if (typeof schema.isOptional === "function") {14936 return schema.isOptional();14937 }14938 return v3Schema._def?.typeName === "ZodOptional";14939}14940function getLiteralValue(schema) {14941 if (isZ4Schema(schema)) {14942 const v4Schema = schema;14943 const def2 = v4Schema._zod?.def;14944 if (def2) {14945 if (def2.value !== void 0)14946 return def2.value;14947 if (Array.isArray(def2.values) && def2.values.length > 0) {14948 return def2.values[0];14949 }14950 }14951 }14952 const v3Schema = schema;14953 const def = v3Schema._def;14954 if (def) {14955 if (def.value !== void 0)14956 return def.value;14957 if (Array.isArray(def.values) && def.values.length > 0) {14958 return def.values[0];14959 }14960 }14961 const directValue = schema.value;14962 if (directValue !== void 0)14963 return directValue;14964 return void 0;14965}1496614967// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js14968var iso_exports2 = {};14969__export(iso_exports2, {14970 ZodISODate: () => ZodISODate,14971 ZodISODateTime: () => ZodISODateTime,14972 ZodISODuration: () => ZodISODuration,14973 ZodISOTime: () => ZodISOTime,14974 date: () => date2,14975 datetime: () => datetime2,14976 duration: () => duration2,14977 time: () => time214978});14979var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {14980 $ZodISODateTime.init(inst, def);14981 ZodStringFormat.init(inst, def);14982});14983function datetime2(params) {14984 return _isoDateTime(ZodISODateTime, params);14985}14986var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {14987 $ZodISODate.init(inst, def);14988 ZodStringFormat.init(inst, def);14989});14990function date2(params) {14991 return _isoDate(ZodISODate, params);14992}14993var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {14994 $ZodISOTime.init(inst, def);14995 ZodStringFormat.init(inst, def);14996});14997function time2(params) {14998 return _isoTime(ZodISOTime, params);14999}15000var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {15001 $ZodISODuration.init(inst, def);15002 ZodStringFormat.init(inst, def);15003});15004function duration2(params) {15005 return _isoDuration(ZodISODuration, params);15006}1500715008// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js15009var initializer2 = (inst, issues) => {15010 $ZodError.init(inst, issues);15011 inst.name = "ZodError";15012 Object.defineProperties(inst, {15013 format: {15014 value: (mapper) => formatError(inst, mapper)15015 // enumerable: false,15016 },15017 flatten: {15018 value: (mapper) => flattenError(inst, mapper)15019 // enumerable: false,15020 },15021 addIssue: {15022 value: (issue2) => inst.issues.push(issue2)15023 // enumerable: false,15024 },15025 addIssues: {15026 value: (issues2) => inst.issues.push(...issues2)15027 // enumerable: false,15028 },15029 isEmpty: {15030 get() {15031 return inst.issues.length === 0;15032 }15033 // enumerable: false,15034 }15035 });15036};15037var ZodError2 = $constructor("ZodError", initializer2);15038var ZodRealError = $constructor("ZodError", initializer2, {15039 Parent: Error15040});1504115042// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js15043var parse2 = /* @__PURE__ */ _parse(ZodRealError);15044var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);15045var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);15046var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError);1504715048// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js15049var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {15050 $ZodType.init(inst, def);15051 inst.def = def;15052 Object.defineProperty(inst, "_def", { value: def });15053 inst.check = (...checks) => {15054 return inst.clone(15055 {15056 ...def,15057 checks: [15058 ...def.checks ?? [],15059 ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)15060 ]15061 }15062 // { parent: true }15063 );15064 };15065 inst.clone = (def2, params) => clone(inst, def2, params);15066 inst.brand = () => inst;15067 inst.register = (reg, meta) => {15068 reg.add(inst, meta);15069 return inst;15070 };15071 inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse });15072 inst.safeParse = (data, params) => safeParse3(inst, data, params);15073 inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });15074 inst.safeParseAsync = async (data, params) => safeParseAsync3(inst, data, params);15075 inst.spa = inst.safeParseAsync;15076 inst.refine = (check2, params) => inst.check(refine(check2, params));15077 inst.superRefine = (refinement) => inst.check(superRefine(refinement));15078 inst.overwrite = (fn) => inst.check(_overwrite(fn));15079 inst.optional = () => optional(inst);15080 inst.nullable = () => nullable(inst);15081 inst.nullish = () => optional(nullable(inst));15082 inst.nonoptional = (params) => nonoptional(inst, params);15083 inst.array = () => array(inst);15084 inst.or = (arg) => union([inst, arg]);15085 inst.and = (arg) => intersection(inst, arg);15086 inst.transform = (tx) => pipe(inst, transform(tx));15087 inst.default = (def2) => _default(inst, def2);15088 inst.prefault = (def2) => prefault(inst, def2);15089 inst.catch = (params) => _catch(inst, params);15090 inst.pipe = (target) => pipe(inst, target);15091 inst.readonly = () => readonly(inst);15092 inst.describe = (description) => {15093 const cl = inst.clone();15094 globalRegistry.add(cl, { description });15095 return cl;15096 };15097 Object.defineProperty(inst, "description", {15098 get() {15099 return globalRegistry.get(inst)?.description;15100 },15101 configurable: true15102 });15103 inst.meta = (...args) => {15104 if (args.length === 0) {15105 return globalRegistry.get(inst);15106 }15107 const cl = inst.clone();15108 globalRegistry.add(cl, args[0]);15109 return cl;15110 };15111 inst.isOptional = () => inst.safeParse(void 0).success;15112 inst.isNullable = () => inst.safeParse(null).success;15113 return inst;15114});15115var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {15116 $ZodString.init(inst, def);15117 ZodType2.init(inst, def);15118 const bag = inst._zod.bag;15119 inst.format = bag.format ?? null;15120 inst.minLength = bag.minimum ?? null;15121 inst.maxLength = bag.maximum ?? null;15122 inst.regex = (...args) => inst.check(_regex(...args));15123 inst.includes = (...args) => inst.check(_includes(...args));15124 inst.startsWith = (...args) => inst.check(_startsWith(...args));15125 inst.endsWith = (...args) => inst.check(_endsWith(...args));15126 inst.min = (...args) => inst.check(_minLength(...args));15127 inst.max = (...args) => inst.check(_maxLength(...args));15128 inst.length = (...args) => inst.check(_length(...args));15129 inst.nonempty = (...args) => inst.check(_minLength(1, ...args));15130 inst.lowercase = (params) => inst.check(_lowercase(params));15131 inst.uppercase = (params) => inst.check(_uppercase(params));15132 inst.trim = () => inst.check(_trim());15133 inst.normalize = (...args) => inst.check(_normalize(...args));15134 inst.toLowerCase = () => inst.check(_toLowerCase());15135 inst.toUpperCase = () => inst.check(_toUpperCase());15136});15137var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {15138 $ZodString.init(inst, def);15139 _ZodString.init(inst, def);15140 inst.email = (params) => inst.check(_email(ZodEmail, params));15141 inst.url = (params) => inst.check(_url(ZodURL, params));15142 inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));15143 inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));15144 inst.guid = (params) => inst.check(_guid(ZodGUID, params));15145 inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));15146 inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));15147 inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));15148 inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));15149 inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));15150 inst.guid = (params) => inst.check(_guid(ZodGUID, params));15151 inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));15152 inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));15153 inst.ulid = (params) => inst.check(_ulid(ZodULID, params));15154 inst.base64 = (params) => inst.check(_base64(ZodBase64, params));15155 inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));15156 inst.xid = (params) => inst.check(_xid(ZodXID, params));15157 inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));15158 inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));15159 inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));15160 inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));15161 inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));15162 inst.e164 = (params) => inst.check(_e164(ZodE164, params));15163 inst.datetime = (params) => inst.check(datetime2(params));15164 inst.date = (params) => inst.check(date2(params));15165 inst.time = (params) => inst.check(time2(params));15166 inst.duration = (params) => inst.check(duration2(params));15167});15168function string2(params) {15169 return _string(ZodString2, params);15170}15171var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {15172 $ZodStringFormat.init(inst, def);15173 _ZodString.init(inst, def);15174});15175var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {15176 $ZodEmail.init(inst, def);15177 ZodStringFormat.init(inst, def);15178});15179var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {15180 $ZodGUID.init(inst, def);15181 ZodStringFormat.init(inst, def);15182});15183var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {15184 $ZodUUID.init(inst, def);15185 ZodStringFormat.init(inst, def);15186});15187var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {15188 $ZodURL.init(inst, def);15189 ZodStringFormat.init(inst, def);15190});15191var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {15192 $ZodEmoji.init(inst, def);15193 ZodStringFormat.init(inst, def);15194});15195var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {15196 $ZodNanoID.init(inst, def);15197 ZodStringFormat.init(inst, def);15198});15199var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {15200 $ZodCUID.init(inst, def);15201 ZodStringFormat.init(inst, def);15202});15203var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {15204 $ZodCUID2.init(inst, def);15205 ZodStringFormat.init(inst, def);15206});15207var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {15208 $ZodULID.init(inst, def);15209 ZodStringFormat.init(inst, def);15210});15211var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {15212 $ZodXID.init(inst, def);15213 ZodStringFormat.init(inst, def);15214});15215var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {15216 $ZodKSUID.init(inst, def);15217 ZodStringFormat.init(inst, def);15218});15219var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {15220 $ZodIPv4.init(inst, def);15221 ZodStringFormat.init(inst, def);15222});15223var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {15224 $ZodIPv6.init(inst, def);15225 ZodStringFormat.init(inst, def);15226});15227var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {15228 $ZodCIDRv4.init(inst, def);15229 ZodStringFormat.init(inst, def);15230});15231var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {15232 $ZodCIDRv6.init(inst, def);15233 ZodStringFormat.init(inst, def);15234});15235var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {15236 $ZodBase64.init(inst, def);15237 ZodStringFormat.init(inst, def);15238});15239var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {15240 $ZodBase64URL.init(inst, def);15241 ZodStringFormat.init(inst, def);15242});15243var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {15244 $ZodE164.init(inst, def);15245 ZodStringFormat.init(inst, def);15246});15247var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {15248 $ZodJWT.init(inst, def);15249 ZodStringFormat.init(inst, def);15250});15251var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {15252 $ZodNumber.init(inst, def);15253 ZodType2.init(inst, def);15254 inst.gt = (value, params) => inst.check(_gt(value, params));15255 inst.gte = (value, params) => inst.check(_gte(value, params));15256 inst.min = (value, params) => inst.check(_gte(value, params));15257 inst.lt = (value, params) => inst.check(_lt(value, params));15258 inst.lte = (value, params) => inst.check(_lte(value, params));15259 inst.max = (value, params) => inst.check(_lte(value, params));15260 inst.int = (params) => inst.check(int(params));15261 inst.safe = (params) => inst.check(int(params));15262 inst.positive = (params) => inst.check(_gt(0, params));15263 inst.nonnegative = (params) => inst.check(_gte(0, params));15264 inst.negative = (params) => inst.check(_lt(0, params));15265 inst.nonpositive = (params) => inst.check(_lte(0, params));15266 inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));15267 inst.step = (value, params) => inst.check(_multipleOf(value, params));15268 inst.finite = () => inst;15269 const bag = inst._zod.bag;15270 inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;15271 inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;15272 inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);15273 inst.isFinite = true;15274 inst.format = bag.format ?? null;15275});15276function number2(params) {15277 return _number(ZodNumber2, params);15278}15279var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {15280 $ZodNumberFormat.init(inst, def);15281 ZodNumber2.init(inst, def);15282});15283function int(params) {15284 return _int(ZodNumberFormat, params);15285}15286var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {15287 $ZodBoolean.init(inst, def);15288 ZodType2.init(inst, def);15289});15290function boolean2(params) {15291 return _boolean(ZodBoolean2, params);15292}15293var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {15294 $ZodNull.init(inst, def);15295 ZodType2.init(inst, def);15296});15297function _null3(params) {15298 return _null2(ZodNull2, params);15299}15300var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {15301 $ZodUnknown.init(inst, def);15302 ZodType2.init(inst, def);15303});15304function unknown() {15305 return _unknown(ZodUnknown2);15306}15307var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {15308 $ZodNever.init(inst, def);15309 ZodType2.init(inst, def);15310});15311function never(params) {15312 return _never(ZodNever2, params);15313}15314var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {15315 $ZodArray.init(inst, def);15316 ZodType2.init(inst, def);15317 inst.element = def.element;15318 inst.min = (minLength, params) => inst.check(_minLength(minLength, params));15319 inst.nonempty = (params) => inst.check(_minLength(1, params));15320 inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));15321 inst.length = (len, params) => inst.check(_length(len, params));15322 inst.unwrap = () => inst.element;15323});15324function array(element, params) {15325 return _array(ZodArray2, element, params);15326}15327var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {15328 $ZodObject.init(inst, def);15329 ZodType2.init(inst, def);15330 util_exports.defineLazy(inst, "shape", () => def.shape);15331 inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));15332 inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });15333 inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });15334 inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });15335 inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });15336 inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 });15337 inst.extend = (incoming) => {15338 return util_exports.extend(inst, incoming);15339 };15340 inst.merge = (other) => util_exports.merge(inst, other);15341 inst.pick = (mask) => util_exports.pick(inst, mask);15342 inst.omit = (mask) => util_exports.omit(inst, mask);15343 inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]);15344 inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]);15345});15346function object2(shape, params) {15347 const def = {15348 type: "object",15349 get shape() {15350 util_exports.assignProp(this, "shape", { ...shape });15351 return this.shape;15352 },15353 ...util_exports.normalizeParams(params)15354 };15355 return new ZodObject2(def);15356}15357function looseObject(shape, params) {15358 return new ZodObject2({15359 type: "object",15360 get shape() {15361 util_exports.assignProp(this, "shape", { ...shape });15362 return this.shape;15363 },15364 catchall: unknown(),15365 ...util_exports.normalizeParams(params)15366 });15367}15368var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {15369 $ZodUnion.init(inst, def);15370 ZodType2.init(inst, def);15371 inst.options = def.options;15372});15373function union(options, params) {15374 return new ZodUnion2({15375 type: "union",15376 options,15377 ...util_exports.normalizeParams(params)15378 });15379}15380var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {15381 ZodUnion2.init(inst, def);15382 $ZodDiscriminatedUnion.init(inst, def);15383});15384function discriminatedUnion(discriminator, options, params) {15385 return new ZodDiscriminatedUnion2({15386 type: "union",15387 options,15388 discriminator,15389 ...util_exports.normalizeParams(params)15390 });15391}15392var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {15393 $ZodIntersection.init(inst, def);15394 ZodType2.init(inst, def);15395});15396function intersection(left, right) {15397 return new ZodIntersection2({15398 type: "intersection",15399 left,15400 right15401 });15402}15403var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {15404 $ZodRecord.init(inst, def);15405 ZodType2.init(inst, def);15406 inst.keyType = def.keyType;15407 inst.valueType = def.valueType;15408});15409function record(keyType, valueType, params) {15410 return new ZodRecord2({15411 type: "record",15412 keyType,15413 valueType,15414 ...util_exports.normalizeParams(params)15415 });15416}15417var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {15418 $ZodEnum.init(inst, def);15419 ZodType2.init(inst, def);15420 inst.enum = def.entries;15421 inst.options = Object.values(def.entries);15422 const keys = new Set(Object.keys(def.entries));15423 inst.extract = (values, params) => {15424 const newEntries = {};15425 for (const value of values) {15426 if (keys.has(value)) {15427 newEntries[value] = def.entries[value];15428 } else15429 throw new Error(`Key ${value} not found in enum`);15430 }15431 return new ZodEnum2({15432 ...def,15433 checks: [],15434 ...util_exports.normalizeParams(params),15435 entries: newEntries15436 });15437 };15438 inst.exclude = (values, params) => {15439 const newEntries = { ...def.entries };15440 for (const value of values) {15441 if (keys.has(value)) {15442 delete newEntries[value];15443 } else15444 throw new Error(`Key ${value} not found in enum`);15445 }15446 return new ZodEnum2({15447 ...def,15448 checks: [],15449 ...util_exports.normalizeParams(params),15450 entries: newEntries15451 });15452 };15453});15454function _enum(values, params) {15455 const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;15456 return new ZodEnum2({15457 type: "enum",15458 entries,15459 ...util_exports.normalizeParams(params)15460 });15461}15462var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {15463 $ZodLiteral.init(inst, def);15464 ZodType2.init(inst, def);15465 inst.values = new Set(def.values);15466 Object.defineProperty(inst, "value", {15467 get() {15468 if (def.values.length > 1) {15469 throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");15470 }15471 return def.values[0];15472 }15473 });15474});15475function literal(value, params) {15476 return new ZodLiteral2({15477 type: "literal",15478 values: Array.isArray(value) ? value : [value],15479 ...util_exports.normalizeParams(params)15480 });15481}15482var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {15483 $ZodTransform.init(inst, def);15484 ZodType2.init(inst, def);15485 inst._zod.parse = (payload, _ctx) => {15486 payload.addIssue = (issue2) => {15487 if (typeof issue2 === "string") {15488 payload.issues.push(util_exports.issue(issue2, payload.value, def));15489 } else {15490 const _issue = issue2;15491 if (_issue.fatal)15492 _issue.continue = false;15493 _issue.code ?? (_issue.code = "custom");15494 _issue.input ?? (_issue.input = payload.value);15495 _issue.inst ?? (_issue.inst = inst);15496 _issue.continue ?? (_issue.continue = true);15497 payload.issues.push(util_exports.issue(_issue));15498 }15499 };15500 const output = def.transform(payload.value, payload);15501 if (output instanceof Promise) {15502 return output.then((output2) => {15503 payload.value = output2;15504 return payload;15505 });15506 }15507 payload.value = output;15508 return payload;15509 };15510});15511function transform(fn) {15512 return new ZodTransform({15513 type: "transform",15514 transform: fn15515 });15516}15517var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {15518 $ZodOptional.init(inst, def);15519 ZodType2.init(inst, def);15520 inst.unwrap = () => inst._zod.def.innerType;15521});15522function optional(innerType) {15523 return new ZodOptional2({15524 type: "optional",15525 innerType15526 });15527}15528var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {15529 $ZodNullable.init(inst, def);15530 ZodType2.init(inst, def);15531 inst.unwrap = () => inst._zod.def.innerType;15532});15533function nullable(innerType) {15534 return new ZodNullable2({15535 type: "nullable",15536 innerType15537 });15538}15539var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {15540 $ZodDefault.init(inst, def);15541 ZodType2.init(inst, def);15542 inst.unwrap = () => inst._zod.def.innerType;15543 inst.removeDefault = inst.unwrap;15544});15545function _default(innerType, defaultValue) {15546 return new ZodDefault2({15547 type: "default",15548 innerType,15549 get defaultValue() {15550 return typeof defaultValue === "function" ? defaultValue() : defaultValue;15551 }15552 });15553}15554var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {15555 $ZodPrefault.init(inst, def);15556 ZodType2.init(inst, def);15557 inst.unwrap = () => inst._zod.def.innerType;15558});15559function prefault(innerType, defaultValue) {15560 return new ZodPrefault({15561 type: "prefault",15562 innerType,15563 get defaultValue() {15564 return typeof defaultValue === "function" ? defaultValue() : defaultValue;15565 }15566 });15567}15568var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {15569 $ZodNonOptional.init(inst, def);15570 ZodType2.init(inst, def);15571 inst.unwrap = () => inst._zod.def.innerType;15572});15573function nonoptional(innerType, params) {15574 return new ZodNonOptional({15575 type: "nonoptional",15576 innerType,15577 ...util_exports.normalizeParams(params)15578 });15579}15580var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {15581 $ZodCatch.init(inst, def);15582 ZodType2.init(inst, def);15583 inst.unwrap = () => inst._zod.def.innerType;15584 inst.removeCatch = inst.unwrap;15585});15586function _catch(innerType, catchValue) {15587 return new ZodCatch2({15588 type: "catch",15589 innerType,15590 catchValue: typeof catchValue === "function" ? catchValue : () => catchValue15591 });15592}15593var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {15594 $ZodPipe.init(inst, def);15595 ZodType2.init(inst, def);15596 inst.in = def.in;15597 inst.out = def.out;15598});15599function pipe(in_, out) {15600 return new ZodPipe({15601 type: "pipe",15602 in: in_,15603 out15604 // ...util.normalizeParams(params),15605 });15606}15607var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {15608 $ZodReadonly.init(inst, def);15609 ZodType2.init(inst, def);15610});15611function readonly(innerType) {15612 return new ZodReadonly2({15613 type: "readonly",15614 innerType15615 });15616}15617var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {15618 $ZodCustom.init(inst, def);15619 ZodType2.init(inst, def);15620});15621function check(fn) {15622 const ch = new $ZodCheck({15623 check: "custom"15624 // ...util.normalizeParams(params),15625 });15626 ch._zod.check = fn;15627 return ch;15628}15629function custom2(fn, _params) {15630 return _custom(ZodCustom, fn ?? (() => true), _params);15631}15632function refine(fn, _params = {}) {15633 return _refine(ZodCustom, fn, _params);15634}15635function superRefine(fn) {15636 const ch = check((payload) => {15637 payload.addIssue = (issue2) => {15638 if (typeof issue2 === "string") {15639 payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def));15640 } else {15641 const _issue = issue2;15642 if (_issue.fatal)15643 _issue.continue = false;15644 _issue.code ?? (_issue.code = "custom");15645 _issue.input ?? (_issue.input = payload.value);15646 _issue.inst ?? (_issue.inst = ch);15647 _issue.continue ?? (_issue.continue = !ch._zod.def.abort);15648 payload.issues.push(util_exports.issue(_issue));15649 }15650 };15651 return fn(payload.value, payload);15652 });15653 return ch;15654}15655function preprocess(fn, schema) {15656 return pipe(transform(fn), schema);15657}1565815659// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/external.js15660config(en_default2());1566115662// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js15663var LATEST_PROTOCOL_VERSION = "2025-11-25";15664var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];15665var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";15666var JSONRPC_VERSION = "2.0";15667var AssertObjectSchema = custom2((v) => v !== null && (typeof v === "object" || typeof v === "function"));15668var ProgressTokenSchema = union([string2(), number2().int()]);15669var CursorSchema = string2();15670var TaskCreationParamsSchema = looseObject({15671 /**15672 * Requested duration in milliseconds to retain task from creation.15673 */15674 ttl: number2().optional(),15675 /**15676 * Time in milliseconds to wait between task status requests.15677 */15678 pollInterval: number2().optional()15679});15680var TaskMetadataSchema = object2({15681 ttl: number2().optional()15682});15683var RelatedTaskMetadataSchema = object2({15684 taskId: string2()15685});15686var RequestMetaSchema = looseObject({15687 /**15688 * 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.15689 */15690 progressToken: ProgressTokenSchema.optional(),15691 /**15692 * If specified, this request is related to the provided task.15693 */15694 [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()15695});15696var BaseRequestParamsSchema = object2({15697 /**15698 * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.15699 */15700 _meta: RequestMetaSchema.optional()15701});15702var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({15703 /**15704 * If specified, the caller is requesting task-augmented execution for this request.15705 * The request will return a CreateTaskResult immediately, and the actual result can be15706 * retrieved later via tasks/result.15707 *15708 * Task augmentation is subject to capability negotiation - receivers MUST declare support15709 * for task augmentation of specific request types in their capabilities.15710 */15711 task: TaskMetadataSchema.optional()15712});15713var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;15714var RequestSchema = object2({15715 method: string2(),15716 params: BaseRequestParamsSchema.loose().optional()15717});15718var NotificationsParamsSchema = object2({15719 /**15720 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)15721 * for notes on _meta usage.15722 */15723 _meta: RequestMetaSchema.optional()15724});15725var NotificationSchema = object2({15726 method: string2(),15727 params: NotificationsParamsSchema.loose().optional()15728});15729var ResultSchema = looseObject({15730 /**15731 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)15732 * for notes on _meta usage.15733 */15734 _meta: RequestMetaSchema.optional()15735});15736var RequestIdSchema = union([string2(), number2().int()]);15737var JSONRPCRequestSchema = object2({15738 jsonrpc: literal(JSONRPC_VERSION),15739 id: RequestIdSchema,15740 ...RequestSchema.shape15741}).strict();15742var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;15743var JSONRPCNotificationSchema = object2({15744 jsonrpc: literal(JSONRPC_VERSION),15745 ...NotificationSchema.shape15746}).strict();15747var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;15748var JSONRPCResultResponseSchema = object2({15749 jsonrpc: literal(JSONRPC_VERSION),15750 id: RequestIdSchema,15751 result: ResultSchema15752}).strict();15753var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;15754var ErrorCode;15755(function(ErrorCode2) {15756 ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";15757 ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";15758 ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";15759 ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";15760 ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";15761 ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";15762 ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";15763 ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";15764})(ErrorCode || (ErrorCode = {}));15765var JSONRPCErrorResponseSchema = object2({15766 jsonrpc: literal(JSONRPC_VERSION),15767 id: RequestIdSchema.optional(),15768 error: object2({15769 /**15770 * The error type that occurred.15771 */15772 code: number2().int(),15773 /**15774 * A short description of the error. The message SHOULD be limited to a concise single sentence.15775 */15776 message: string2(),15777 /**15778 * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).15779 */15780 data: unknown().optional()15781 })15782}).strict();15783var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;15784var JSONRPCMessageSchema = union([15785 JSONRPCRequestSchema,15786 JSONRPCNotificationSchema,15787 JSONRPCResultResponseSchema,15788 JSONRPCErrorResponseSchema15789]);15790var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);15791var EmptyResultSchema = ResultSchema.strict();15792var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({15793 /**15794 * The ID of the request to cancel.15795 *15796 * This MUST correspond to the ID of a request previously issued in the same direction.15797 */15798 requestId: RequestIdSchema.optional(),15799 /**15800 * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.15801 */15802 reason: string2().optional()15803});15804var CancelledNotificationSchema = NotificationSchema.extend({15805 method: literal("notifications/cancelled"),15806 params: CancelledNotificationParamsSchema15807});15808var IconSchema = object2({15809 /**15810 * URL or data URI for the icon.15811 */15812 src: string2(),15813 /**15814 * Optional MIME type for the icon.15815 */15816 mimeType: string2().optional(),15817 /**15818 * Optional array of strings that specify sizes at which the icon can be used.15819 * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.15820 *15821 * If not provided, the client should assume that the icon can be used at any size.15822 */15823 sizes: array(string2()).optional(),15824 /**15825 * Optional specifier for the theme this icon is designed for. `light` indicates15826 * the icon is designed to be used with a light background, and `dark` indicates15827 * the icon is designed to be used with a dark background.15828 *15829 * If not provided, the client should assume the icon can be used with any theme.15830 */15831 theme: _enum(["light", "dark"]).optional()15832});15833var IconsSchema = object2({15834 /**15835 * Optional set of sized icons that the client can display in a user interface.15836 *15837 * Clients that support rendering icons MUST support at least the following MIME types:15838 * - `image/png` - PNG images (safe, universal compatibility)15839 * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)15840 *15841 * Clients that support rendering icons SHOULD also support:15842 * - `image/svg+xml` - SVG images (scalable but requires security precautions)15843 * - `image/webp` - WebP images (modern, efficient format)15844 */15845 icons: array(IconSchema).optional()15846});15847var BaseMetadataSchema = object2({15848 /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */15849 name: string2(),15850 /**15851 * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,15852 * even by those unfamiliar with domain-specific terminology.15853 *15854 * If not provided, the name should be used for display (except for Tool,15855 * where `annotations.title` should be given precedence over using `name`,15856 * if present).15857 */15858 title: string2().optional()15859});15860var ImplementationSchema = BaseMetadataSchema.extend({15861 ...BaseMetadataSchema.shape,15862 ...IconsSchema.shape,15863 version: string2(),15864 /**15865 * An optional URL of the website for this implementation.15866 */15867 websiteUrl: string2().optional(),15868 /**15869 * An optional human-readable description of what this implementation does.15870 *15871 * This can be used by clients or servers to provide context about their purpose15872 * and capabilities. For example, a server might describe the types of resources15873 * or tools it provides, while a client might describe its intended use case.15874 */15875 description: string2().optional()15876});15877var FormElicitationCapabilitySchema = intersection(object2({15878 applyDefaults: boolean2().optional()15879}), record(string2(), unknown()));15880var ElicitationCapabilitySchema = preprocess((value) => {15881 if (value && typeof value === "object" && !Array.isArray(value)) {15882 if (Object.keys(value).length === 0) {15883 return { form: {} };15884 }15885 }15886 return value;15887}, intersection(object2({15888 form: FormElicitationCapabilitySchema.optional(),15889 url: AssertObjectSchema.optional()15890}), record(string2(), unknown()).optional()));15891var ClientTasksCapabilitySchema = looseObject({15892 /**15893 * Present if the client supports listing tasks.15894 */15895 list: AssertObjectSchema.optional(),15896 /**15897 * Present if the client supports cancelling tasks.15898 */15899 cancel: AssertObjectSchema.optional(),15900 /**15901 * Capabilities for task creation on specific request types.15902 */15903 requests: looseObject({15904 /**15905 * Task support for sampling requests.15906 */15907 sampling: looseObject({15908 createMessage: AssertObjectSchema.optional()15909 }).optional(),15910 /**15911 * Task support for elicitation requests.15912 */15913 elicitation: looseObject({15914 create: AssertObjectSchema.optional()15915 }).optional()15916 }).optional()15917});15918var ServerTasksCapabilitySchema = looseObject({15919 /**15920 * Present if the server supports listing tasks.15921 */15922 list: AssertObjectSchema.optional(),15923 /**15924 * Present if the server supports cancelling tasks.15925 */15926 cancel: AssertObjectSchema.optional(),15927 /**15928 * Capabilities for task creation on specific request types.15929 */15930 requests: looseObject({15931 /**15932 * Task support for tool requests.15933 */15934 tools: looseObject({15935 call: AssertObjectSchema.optional()15936 }).optional()15937 }).optional()15938});15939var ClientCapabilitiesSchema = object2({15940 /**15941 * Experimental, non-standard capabilities that the client supports.15942 */15943 experimental: record(string2(), AssertObjectSchema).optional(),15944 /**15945 * Present if the client supports sampling from an LLM.15946 */15947 sampling: object2({15948 /**15949 * Present if the client supports context inclusion via includeContext parameter.15950 * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).15951 */15952 context: AssertObjectSchema.optional(),15953 /**15954 * Present if the client supports tool use via tools and toolChoice parameters.15955 */15956 tools: AssertObjectSchema.optional()15957 }).optional(),15958 /**15959 * Present if the client supports eliciting user input.15960 */15961 elicitation: ElicitationCapabilitySchema.optional(),15962 /**15963 * Present if the client supports listing roots.15964 */15965 roots: object2({15966 /**15967 * Whether the client supports issuing notifications for changes to the roots list.15968 */15969 listChanged: boolean2().optional()15970 }).optional(),15971 /**15972 * Present if the client supports task creation.15973 */15974 tasks: ClientTasksCapabilitySchema.optional(),15975 /**15976 * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).15977 */15978 extensions: record(string2(), AssertObjectSchema).optional()15979});15980var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({15981 /**15982 * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.15983 */15984 protocolVersion: string2(),15985 capabilities: ClientCapabilitiesSchema,15986 clientInfo: ImplementationSchema15987});15988var InitializeRequestSchema = RequestSchema.extend({15989 method: literal("initialize"),15990 params: InitializeRequestParamsSchema15991});15992var ServerCapabilitiesSchema = object2({15993 /**15994 * Experimental, non-standard capabilities that the server supports.15995 */15996 experimental: record(string2(), AssertObjectSchema).optional(),15997 /**15998 * Present if the server supports sending log messages to the client.15999 */16000 logging: AssertObjectSchema.optional(),16001 /**16002 * Present if the server supports sending completions to the client.16003 */16004 completions: AssertObjectSchema.optional(),16005 /**16006 * Present if the server offers any prompt templates.16007 */16008 prompts: object2({16009 /**16010 * Whether this server supports issuing notifications for changes to the prompt list.16011 */16012 listChanged: boolean2().optional()16013 }).optional(),16014 /**16015 * Present if the server offers any resources to read.16016 */16017 resources: object2({16018 /**16019 * Whether this server supports clients subscribing to resource updates.16020 */16021 subscribe: boolean2().optional(),16022 /**16023 * Whether this server supports issuing notifications for changes to the resource list.16024 */16025 listChanged: boolean2().optional()16026 }).optional(),16027 /**16028 * Present if the server offers any tools to call.16029 */16030 tools: object2({16031 /**16032 * Whether this server supports issuing notifications for changes to the tool list.16033 */16034 listChanged: boolean2().optional()16035 }).optional(),16036 /**16037 * Present if the server supports task creation.16038 */16039 tasks: ServerTasksCapabilitySchema.optional(),16040 /**16041 * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).16042 */16043 extensions: record(string2(), AssertObjectSchema).optional()16044});16045var InitializeResultSchema = ResultSchema.extend({16046 /**16047 * 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.16048 */16049 protocolVersion: string2(),16050 capabilities: ServerCapabilitiesSchema,16051 serverInfo: ImplementationSchema,16052 /**16053 * Instructions describing how to use the server and its features.16054 *16055 * 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.16056 */16057 instructions: string2().optional()16058});16059var InitializedNotificationSchema = NotificationSchema.extend({16060 method: literal("notifications/initialized"),16061 params: NotificationsParamsSchema.optional()16062});16063var PingRequestSchema = RequestSchema.extend({16064 method: literal("ping"),16065 params: BaseRequestParamsSchema.optional()16066});16067var ProgressSchema = object2({16068 /**16069 * The progress thus far. This should increase every time progress is made, even if the total is unknown.16070 */16071 progress: number2(),16072 /**16073 * Total number of items to process (or total progress required), if known.16074 */16075 total: optional(number2()),16076 /**16077 * An optional message describing the current progress.16078 */16079 message: optional(string2())16080});16081var ProgressNotificationParamsSchema = object2({16082 ...NotificationsParamsSchema.shape,16083 ...ProgressSchema.shape,16084 /**16085 * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.16086 */16087 progressToken: ProgressTokenSchema16088});16089var ProgressNotificationSchema = NotificationSchema.extend({16090 method: literal("notifications/progress"),16091 params: ProgressNotificationParamsSchema16092});16093var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({16094 /**16095 * An opaque token representing the current pagination position.16096 * If provided, the server should return results starting after this cursor.16097 */16098 cursor: CursorSchema.optional()16099});16100var PaginatedRequestSchema = RequestSchema.extend({16101 params: PaginatedRequestParamsSchema.optional()16102});16103var PaginatedResultSchema = ResultSchema.extend({16104 /**16105 * An opaque token representing the pagination position after the last returned result.16106 * If present, there may be more results available.16107 */16108 nextCursor: CursorSchema.optional()16109});16110var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);16111var TaskSchema = object2({16112 taskId: string2(),16113 status: TaskStatusSchema,16114 /**16115 * Time in milliseconds to keep task results available after completion.16116 * If null, the task has unlimited lifetime until manually cleaned up.16117 */16118 ttl: union([number2(), _null3()]),16119 /**16120 * ISO 8601 timestamp when the task was created.16121 */16122 createdAt: string2(),16123 /**16124 * ISO 8601 timestamp when the task was last updated.16125 */16126 lastUpdatedAt: string2(),16127 pollInterval: optional(number2()),16128 /**16129 * Optional diagnostic message for failed tasks or other status information.16130 */16131 statusMessage: optional(string2())16132});16133var CreateTaskResultSchema = ResultSchema.extend({16134 task: TaskSchema16135});16136var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);16137var TaskStatusNotificationSchema = NotificationSchema.extend({16138 method: literal("notifications/tasks/status"),16139 params: TaskStatusNotificationParamsSchema16140});16141var GetTaskRequestSchema = RequestSchema.extend({16142 method: literal("tasks/get"),16143 params: BaseRequestParamsSchema.extend({16144 taskId: string2()16145 })16146});16147var GetTaskResultSchema = ResultSchema.merge(TaskSchema);16148var GetTaskPayloadRequestSchema = RequestSchema.extend({16149 method: literal("tasks/result"),16150 params: BaseRequestParamsSchema.extend({16151 taskId: string2()16152 })16153});16154var GetTaskPayloadResultSchema = ResultSchema.loose();16155var ListTasksRequestSchema = PaginatedRequestSchema.extend({16156 method: literal("tasks/list")16157});16158var ListTasksResultSchema = PaginatedResultSchema.extend({16159 tasks: array(TaskSchema)16160});16161var CancelTaskRequestSchema = RequestSchema.extend({16162 method: literal("tasks/cancel"),16163 params: BaseRequestParamsSchema.extend({16164 taskId: string2()16165 })16166});16167var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);16168var ResourceContentsSchema = object2({16169 /**16170 * The URI of this resource.16171 */16172 uri: string2(),16173 /**16174 * The MIME type of this resource, if known.16175 */16176 mimeType: optional(string2()),16177 /**16178 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16179 * for notes on _meta usage.16180 */16181 _meta: record(string2(), unknown()).optional()16182});16183var TextResourceContentsSchema = ResourceContentsSchema.extend({16184 /**16185 * The text of the item. This must only be set if the item can actually be represented as text (not binary data).16186 */16187 text: string2()16188});16189var Base64Schema = string2().refine((val) => {16190 try {16191 atob(val);16192 return true;16193 } catch {16194 return false;16195 }16196}, { message: "Invalid Base64 string" });16197var BlobResourceContentsSchema = ResourceContentsSchema.extend({16198 /**16199 * A base64-encoded string representing the binary data of the item.16200 */16201 blob: Base64Schema16202});16203var RoleSchema = _enum(["user", "assistant"]);16204var AnnotationsSchema = object2({16205 /**16206 * Intended audience(s) for the resource.16207 */16208 audience: array(RoleSchema).optional(),16209 /**16210 * Importance hint for the resource, from 0 (least) to 1 (most).16211 */16212 priority: number2().min(0).max(1).optional(),16213 /**16214 * ISO 8601 timestamp for the most recent modification.16215 */16216 lastModified: iso_exports2.datetime({ offset: true }).optional()16217});16218var ResourceSchema = object2({16219 ...BaseMetadataSchema.shape,16220 ...IconsSchema.shape,16221 /**16222 * The URI of this resource.16223 */16224 uri: string2(),16225 /**16226 * A description of what this resource represents.16227 *16228 * 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.16229 */16230 description: optional(string2()),16231 /**16232 * The MIME type of this resource, if known.16233 */16234 mimeType: optional(string2()),16235 /**16236 * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.16237 *16238 * This can be used by Hosts to display file sizes and estimate context window usage.16239 */16240 size: optional(number2()),16241 /**16242 * Optional annotations for the client.16243 */16244 annotations: AnnotationsSchema.optional(),16245 /**16246 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16247 * for notes on _meta usage.16248 */16249 _meta: optional(looseObject({}))16250});16251var ResourceTemplateSchema = object2({16252 ...BaseMetadataSchema.shape,16253 ...IconsSchema.shape,16254 /**16255 * A URI template (according to RFC 6570) that can be used to construct resource URIs.16256 */16257 uriTemplate: string2(),16258 /**16259 * A description of what this template is for.16260 *16261 * 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.16262 */16263 description: optional(string2()),16264 /**16265 * 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.16266 */16267 mimeType: optional(string2()),16268 /**16269 * Optional annotations for the client.16270 */16271 annotations: AnnotationsSchema.optional(),16272 /**16273 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16274 * for notes on _meta usage.16275 */16276 _meta: optional(looseObject({}))16277});16278var ListResourcesRequestSchema = PaginatedRequestSchema.extend({16279 method: literal("resources/list")16280});16281var ListResourcesResultSchema = PaginatedResultSchema.extend({16282 resources: array(ResourceSchema)16283});16284var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({16285 method: literal("resources/templates/list")16286});16287var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({16288 resourceTemplates: array(ResourceTemplateSchema)16289});16290var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({16291 /**16292 * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.16293 *16294 * @format uri16295 */16296 uri: string2()16297});16298var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;16299var ReadResourceRequestSchema = RequestSchema.extend({16300 method: literal("resources/read"),16301 params: ReadResourceRequestParamsSchema16302});16303var ReadResourceResultSchema = ResultSchema.extend({16304 contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))16305});16306var ResourceListChangedNotificationSchema = NotificationSchema.extend({16307 method: literal("notifications/resources/list_changed"),16308 params: NotificationsParamsSchema.optional()16309});16310var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;16311var SubscribeRequestSchema = RequestSchema.extend({16312 method: literal("resources/subscribe"),16313 params: SubscribeRequestParamsSchema16314});16315var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;16316var UnsubscribeRequestSchema = RequestSchema.extend({16317 method: literal("resources/unsubscribe"),16318 params: UnsubscribeRequestParamsSchema16319});16320var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({16321 /**16322 * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.16323 */16324 uri: string2()16325});16326var ResourceUpdatedNotificationSchema = NotificationSchema.extend({16327 method: literal("notifications/resources/updated"),16328 params: ResourceUpdatedNotificationParamsSchema16329});16330var PromptArgumentSchema = object2({16331 /**16332 * The name of the argument.16333 */16334 name: string2(),16335 /**16336 * A human-readable description of the argument.16337 */16338 description: optional(string2()),16339 /**16340 * Whether this argument must be provided.16341 */16342 required: optional(boolean2())16343});16344var PromptSchema = object2({16345 ...BaseMetadataSchema.shape,16346 ...IconsSchema.shape,16347 /**16348 * An optional description of what this prompt provides16349 */16350 description: optional(string2()),16351 /**16352 * A list of arguments to use for templating the prompt.16353 */16354 arguments: optional(array(PromptArgumentSchema)),16355 /**16356 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16357 * for notes on _meta usage.16358 */16359 _meta: optional(looseObject({}))16360});16361var ListPromptsRequestSchema = PaginatedRequestSchema.extend({16362 method: literal("prompts/list")16363});16364var ListPromptsResultSchema = PaginatedResultSchema.extend({16365 prompts: array(PromptSchema)16366});16367var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({16368 /**16369 * The name of the prompt or prompt template.16370 */16371 name: string2(),16372 /**16373 * Arguments to use for templating the prompt.16374 */16375 arguments: record(string2(), string2()).optional()16376});16377var GetPromptRequestSchema = RequestSchema.extend({16378 method: literal("prompts/get"),16379 params: GetPromptRequestParamsSchema16380});16381var TextContentSchema = object2({16382 type: literal("text"),16383 /**16384 * The text content of the message.16385 */16386 text: string2(),16387 /**16388 * Optional annotations for the client.16389 */16390 annotations: AnnotationsSchema.optional(),16391 /**16392 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16393 * for notes on _meta usage.16394 */16395 _meta: record(string2(), unknown()).optional()16396});16397var ImageContentSchema = object2({16398 type: literal("image"),16399 /**16400 * The base64-encoded image data.16401 */16402 data: Base64Schema,16403 /**16404 * The MIME type of the image. Different providers may support different image types.16405 */16406 mimeType: string2(),16407 /**16408 * Optional annotations for the client.16409 */16410 annotations: AnnotationsSchema.optional(),16411 /**16412 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16413 * for notes on _meta usage.16414 */16415 _meta: record(string2(), unknown()).optional()16416});16417var AudioContentSchema = object2({16418 type: literal("audio"),16419 /**16420 * The base64-encoded audio data.16421 */16422 data: Base64Schema,16423 /**16424 * The MIME type of the audio. Different providers may support different audio types.16425 */16426 mimeType: string2(),16427 /**16428 * Optional annotations for the client.16429 */16430 annotations: AnnotationsSchema.optional(),16431 /**16432 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16433 * for notes on _meta usage.16434 */16435 _meta: record(string2(), unknown()).optional()16436});16437var ToolUseContentSchema = object2({16438 type: literal("tool_use"),16439 /**16440 * The name of the tool to invoke.16441 * Must match a tool name from the request's tools array.16442 */16443 name: string2(),16444 /**16445 * Unique identifier for this tool call.16446 * Used to correlate with ToolResultContent in subsequent messages.16447 */16448 id: string2(),16449 /**16450 * Arguments to pass to the tool.16451 * Must conform to the tool's inputSchema.16452 */16453 input: record(string2(), unknown()),16454 /**16455 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16456 * for notes on _meta usage.16457 */16458 _meta: record(string2(), unknown()).optional()16459});16460var EmbeddedResourceSchema = object2({16461 type: literal("resource"),16462 resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),16463 /**16464 * Optional annotations for the client.16465 */16466 annotations: AnnotationsSchema.optional(),16467 /**16468 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16469 * for notes on _meta usage.16470 */16471 _meta: record(string2(), unknown()).optional()16472});16473var ResourceLinkSchema = ResourceSchema.extend({16474 type: literal("resource_link")16475});16476var ContentBlockSchema = union([16477 TextContentSchema,16478 ImageContentSchema,16479 AudioContentSchema,16480 ResourceLinkSchema,16481 EmbeddedResourceSchema16482]);16483var PromptMessageSchema = object2({16484 role: RoleSchema,16485 content: ContentBlockSchema16486});16487var GetPromptResultSchema = ResultSchema.extend({16488 /**16489 * An optional description for the prompt.16490 */16491 description: string2().optional(),16492 messages: array(PromptMessageSchema)16493});16494var PromptListChangedNotificationSchema = NotificationSchema.extend({16495 method: literal("notifications/prompts/list_changed"),16496 params: NotificationsParamsSchema.optional()16497});16498var ToolAnnotationsSchema = object2({16499 /**16500 * A human-readable title for the tool.16501 */16502 title: string2().optional(),16503 /**16504 * If true, the tool does not modify its environment.16505 *16506 * Default: false16507 */16508 readOnlyHint: boolean2().optional(),16509 /**16510 * If true, the tool may perform destructive updates to its environment.16511 * If false, the tool performs only additive updates.16512 *16513 * (This property is meaningful only when `readOnlyHint == false`)16514 *16515 * Default: true16516 */16517 destructiveHint: boolean2().optional(),16518 /**16519 * If true, calling the tool repeatedly with the same arguments16520 * will have no additional effect on the its environment.16521 *16522 * (This property is meaningful only when `readOnlyHint == false`)16523 *16524 * Default: false16525 */16526 idempotentHint: boolean2().optional(),16527 /**16528 * If true, this tool may interact with an "open world" of external16529 * entities. If false, the tool's domain of interaction is closed.16530 * For example, the world of a web search tool is open, whereas that16531 * of a memory tool is not.16532 *16533 * Default: true16534 */16535 openWorldHint: boolean2().optional()16536});16537var ToolExecutionSchema = object2({16538 /**16539 * Indicates the tool's preference for task-augmented execution.16540 * - "required": Clients MUST invoke the tool as a task16541 * - "optional": Clients MAY invoke the tool as a task or normal request16542 * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task16543 *16544 * If not present, defaults to "forbidden".16545 */16546 taskSupport: _enum(["required", "optional", "forbidden"]).optional()16547});16548var ToolSchema = object2({16549 ...BaseMetadataSchema.shape,16550 ...IconsSchema.shape,16551 /**16552 * A human-readable description of the tool.16553 */16554 description: string2().optional(),16555 /**16556 * A JSON Schema 2020-12 object defining the expected parameters for the tool.16557 * Must have type: 'object' at the root level per MCP spec.16558 */16559 inputSchema: object2({16560 type: literal("object"),16561 properties: record(string2(), AssertObjectSchema).optional(),16562 required: array(string2()).optional()16563 }).catchall(unknown()),16564 /**16565 * An optional JSON Schema 2020-12 object defining the structure of the tool's output16566 * returned in the structuredContent field of a CallToolResult.16567 * Must have type: 'object' at the root level per MCP spec.16568 */16569 outputSchema: object2({16570 type: literal("object"),16571 properties: record(string2(), AssertObjectSchema).optional(),16572 required: array(string2()).optional()16573 }).catchall(unknown()).optional(),16574 /**16575 * Optional additional tool information.16576 */16577 annotations: ToolAnnotationsSchema.optional(),16578 /**16579 * Execution-related properties for this tool.16580 */16581 execution: ToolExecutionSchema.optional(),16582 /**16583 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16584 * for notes on _meta usage.16585 */16586 _meta: record(string2(), unknown()).optional()16587});16588var ListToolsRequestSchema = PaginatedRequestSchema.extend({16589 method: literal("tools/list")16590});16591var ListToolsResultSchema = PaginatedResultSchema.extend({16592 tools: array(ToolSchema)16593});16594var CallToolResultSchema = ResultSchema.extend({16595 /**16596 * A list of content objects that represent the result of the tool call.16597 *16598 * If the Tool does not define an outputSchema, this field MUST be present in the result.16599 * For backwards compatibility, this field is always present, but it may be empty.16600 */16601 content: array(ContentBlockSchema).default([]),16602 /**16603 * An object containing structured tool output.16604 *16605 * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.16606 */16607 structuredContent: record(string2(), unknown()).optional(),16608 /**16609 * Whether the tool call ended in an error.16610 *16611 * If not set, this is assumed to be false (the call was successful).16612 *16613 * Any errors that originate from the tool SHOULD be reported inside the result16614 * object, with `isError` set to true, _not_ as an MCP protocol-level error16615 * response. Otherwise, the LLM would not be able to see that an error occurred16616 * and self-correct.16617 *16618 * However, any errors in _finding_ the tool, an error indicating that the16619 * server does not support tool calls, or any other exceptional conditions,16620 * should be reported as an MCP error response.16621 */16622 isError: boolean2().optional()16623});16624var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({16625 toolResult: unknown()16626}));16627var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({16628 /**16629 * The name of the tool to call.16630 */16631 name: string2(),16632 /**16633 * Arguments to pass to the tool.16634 */16635 arguments: record(string2(), unknown()).optional()16636});16637var CallToolRequestSchema = RequestSchema.extend({16638 method: literal("tools/call"),16639 params: CallToolRequestParamsSchema16640});16641var ToolListChangedNotificationSchema = NotificationSchema.extend({16642 method: literal("notifications/tools/list_changed"),16643 params: NotificationsParamsSchema.optional()16644});16645var ListChangedOptionsBaseSchema = object2({16646 /**16647 * If true, the list will be refreshed automatically when a list changed notification is received.16648 * The callback will be called with the updated list.16649 *16650 * If false, the callback will be called with null items, allowing manual refresh.16651 *16652 * @default true16653 */16654 autoRefresh: boolean2().default(true),16655 /**16656 * Debounce time in milliseconds for list changed notification processing.16657 *16658 * Multiple notifications received within this timeframe will only trigger one refresh.16659 * Set to 0 to disable debouncing.16660 *16661 * @default 30016662 */16663 debounceMs: number2().int().nonnegative().default(300)16664});16665var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);16666var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({16667 /**16668 * 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.16669 */16670 level: LoggingLevelSchema16671});16672var SetLevelRequestSchema = RequestSchema.extend({16673 method: literal("logging/setLevel"),16674 params: SetLevelRequestParamsSchema16675});16676var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({16677 /**16678 * The severity of this log message.16679 */16680 level: LoggingLevelSchema,16681 /**16682 * An optional name of the logger issuing this message.16683 */16684 logger: string2().optional(),16685 /**16686 * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.16687 */16688 data: unknown()16689});16690var LoggingMessageNotificationSchema = NotificationSchema.extend({16691 method: literal("notifications/message"),16692 params: LoggingMessageNotificationParamsSchema16693});16694var ModelHintSchema = object2({16695 /**16696 * A hint for a model name.16697 */16698 name: string2().optional()16699});16700var ModelPreferencesSchema = object2({16701 /**16702 * Optional hints to use for model selection.16703 */16704 hints: array(ModelHintSchema).optional(),16705 /**16706 * How much to prioritize cost when selecting a model.16707 */16708 costPriority: number2().min(0).max(1).optional(),16709 /**16710 * How much to prioritize sampling speed (latency) when selecting a model.16711 */16712 speedPriority: number2().min(0).max(1).optional(),16713 /**16714 * How much to prioritize intelligence and capabilities when selecting a model.16715 */16716 intelligencePriority: number2().min(0).max(1).optional()16717});16718var ToolChoiceSchema = object2({16719 /**16720 * Controls when tools are used:16721 * - "auto": Model decides whether to use tools (default)16722 * - "required": Model MUST use at least one tool before completing16723 * - "none": Model MUST NOT use any tools16724 */16725 mode: _enum(["auto", "required", "none"]).optional()16726});16727var ToolResultContentSchema = object2({16728 type: literal("tool_result"),16729 toolUseId: string2().describe("The unique identifier for the corresponding tool call."),16730 content: array(ContentBlockSchema).default([]),16731 structuredContent: object2({}).loose().optional(),16732 isError: boolean2().optional(),16733 /**16734 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16735 * for notes on _meta usage.16736 */16737 _meta: record(string2(), unknown()).optional()16738});16739var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);16740var SamplingMessageContentBlockSchema = discriminatedUnion("type", [16741 TextContentSchema,16742 ImageContentSchema,16743 AudioContentSchema,16744 ToolUseContentSchema,16745 ToolResultContentSchema16746]);16747var SamplingMessageSchema = object2({16748 role: RoleSchema,16749 content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),16750 /**16751 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)16752 * for notes on _meta usage.16753 */16754 _meta: record(string2(), unknown()).optional()16755});16756var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({16757 messages: array(SamplingMessageSchema),16758 /**16759 * The server's preferences for which model to select. The client MAY modify or omit this request.16760 */16761 modelPreferences: ModelPreferencesSchema.optional(),16762 /**16763 * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.16764 */16765 systemPrompt: string2().optional(),16766 /**16767 * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.16768 * The client MAY ignore this request.16769 *16770 * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client16771 * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.16772 */16773 includeContext: _enum(["none", "thisServer", "allServers"]).optional(),16774 temperature: number2().optional(),16775 /**16776 * The requested maximum number of tokens to sample (to prevent runaway completions).16777 *16778 * The client MAY choose to sample fewer tokens than the requested maximum.16779 */16780 maxTokens: number2().int(),16781 stopSequences: array(string2()).optional(),16782 /**16783 * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.16784 */16785 metadata: AssertObjectSchema.optional(),16786 /**16787 * Tools that the model may use during generation.16788 * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.16789 */16790 tools: array(ToolSchema).optional(),16791 /**16792 * Controls how the model uses tools.16793 * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.16794 * Default is `{ mode: "auto" }`.16795 */16796 toolChoice: ToolChoiceSchema.optional()16797});16798var CreateMessageRequestSchema = RequestSchema.extend({16799 method: literal("sampling/createMessage"),16800 params: CreateMessageRequestParamsSchema16801});16802var CreateMessageResultSchema = ResultSchema.extend({16803 /**16804 * The name of the model that generated the message.16805 */16806 model: string2(),16807 /**16808 * The reason why sampling stopped, if known.16809 *16810 * Standard values:16811 * - "endTurn": Natural end of the assistant's turn16812 * - "stopSequence": A stop sequence was encountered16813 * - "maxTokens": Maximum token limit was reached16814 *16815 * This field is an open string to allow for provider-specific stop reasons.16816 */16817 stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())),16818 role: RoleSchema,16819 /**16820 * Response content. Single content block (text, image, or audio).16821 */16822 content: SamplingContentSchema16823});16824var CreateMessageResultWithToolsSchema = ResultSchema.extend({16825 /**16826 * The name of the model that generated the message.16827 */16828 model: string2(),16829 /**16830 * The reason why sampling stopped, if known.16831 *16832 * Standard values:16833 * - "endTurn": Natural end of the assistant's turn16834 * - "stopSequence": A stop sequence was encountered16835 * - "maxTokens": Maximum token limit was reached16836 * - "toolUse": The model wants to use one or more tools16837 *16838 * This field is an open string to allow for provider-specific stop reasons.16839 */16840 stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),16841 role: RoleSchema,16842 /**16843 * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".16844 */16845 content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])16846});16847var BooleanSchemaSchema = object2({16848 type: literal("boolean"),16849 title: string2().optional(),16850 description: string2().optional(),16851 default: boolean2().optional()16852});16853var StringSchemaSchema = object2({16854 type: literal("string"),16855 title: string2().optional(),16856 description: string2().optional(),16857 minLength: number2().optional(),16858 maxLength: number2().optional(),16859 format: _enum(["email", "uri", "date", "date-time"]).optional(),16860 default: string2().optional()16861});16862var NumberSchemaSchema = object2({16863 type: _enum(["number", "integer"]),16864 title: string2().optional(),16865 description: string2().optional(),16866 minimum: number2().optional(),16867 maximum: number2().optional(),16868 default: number2().optional()16869});16870var UntitledSingleSelectEnumSchemaSchema = object2({16871 type: literal("string"),16872 title: string2().optional(),16873 description: string2().optional(),16874 enum: array(string2()),16875 default: string2().optional()16876});16877var TitledSingleSelectEnumSchemaSchema = object2({16878 type: literal("string"),16879 title: string2().optional(),16880 description: string2().optional(),16881 oneOf: array(object2({16882 const: string2(),16883 title: string2()16884 })),16885 default: string2().optional()16886});16887var LegacyTitledEnumSchemaSchema = object2({16888 type: literal("string"),16889 title: string2().optional(),16890 description: string2().optional(),16891 enum: array(string2()),16892 enumNames: array(string2()).optional(),16893 default: string2().optional()16894});16895var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);16896var UntitledMultiSelectEnumSchemaSchema = object2({16897 type: literal("array"),16898 title: string2().optional(),16899 description: string2().optional(),16900 minItems: number2().optional(),16901 maxItems: number2().optional(),16902 items: object2({16903 type: literal("string"),16904 enum: array(string2())16905 }),16906 default: array(string2()).optional()16907});16908var TitledMultiSelectEnumSchemaSchema = object2({16909 type: literal("array"),16910 title: string2().optional(),16911 description: string2().optional(),16912 minItems: number2().optional(),16913 maxItems: number2().optional(),16914 items: object2({16915 anyOf: array(object2({16916 const: string2(),16917 title: string2()16918 }))16919 }),16920 default: array(string2()).optional()16921});16922var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);16923var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);16924var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);16925var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({16926 /**16927 * The elicitation mode.16928 *16929 * Optional for backward compatibility. Clients MUST treat missing mode as "form".16930 */16931 mode: literal("form").optional(),16932 /**16933 * The message to present to the user describing what information is being requested.16934 */16935 message: string2(),16936 /**16937 * A restricted subset of JSON Schema.16938 * Only top-level properties are allowed, without nesting.16939 */16940 requestedSchema: object2({16941 type: literal("object"),16942 properties: record(string2(), PrimitiveSchemaDefinitionSchema),16943 required: array(string2()).optional()16944 })16945});16946var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({16947 /**16948 * The elicitation mode.16949 */16950 mode: literal("url"),16951 /**16952 * The message to present to the user explaining why the interaction is needed.16953 */16954 message: string2(),16955 /**16956 * The ID of the elicitation, which must be unique within the context of the server.16957 * The client MUST treat this ID as an opaque value.16958 */16959 elicitationId: string2(),16960 /**16961 * The URL that the user should navigate to.16962 */16963 url: string2().url()16964});16965var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);16966var ElicitRequestSchema = RequestSchema.extend({16967 method: literal("elicitation/create"),16968 params: ElicitRequestParamsSchema16969});16970var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({16971 /**16972 * The ID of the elicitation that completed.16973 */16974 elicitationId: string2()16975});16976var ElicitationCompleteNotificationSchema = NotificationSchema.extend({16977 method: literal("notifications/elicitation/complete"),16978 params: ElicitationCompleteNotificationParamsSchema16979});16980var ElicitResultSchema = ResultSchema.extend({16981 /**16982 * The user action in response to the elicitation.16983 * - "accept": User submitted the form/confirmed the action16984 * - "decline": User explicitly decline the action16985 * - "cancel": User dismissed without making an explicit choice16986 */16987 action: _enum(["accept", "decline", "cancel"]),16988 /**16989 * The submitted form data, only present when action is "accept".16990 * Contains values matching the requested schema.16991 * Per MCP spec, content is "typically omitted" for decline/cancel actions.16992 * We normalize null to undefined for leniency while maintaining type compatibility.16993 */16994 content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())16995});16996var ResourceTemplateReferenceSchema = object2({16997 type: literal("ref/resource"),16998 /**16999 * The URI or URI template of the resource.17000 */17001 uri: string2()17002});17003var PromptReferenceSchema = object2({17004 type: literal("ref/prompt"),17005 /**17006 * The name of the prompt or prompt template17007 */17008 name: string2()17009});17010var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({17011 ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),17012 /**17013 * The argument's information17014 */17015 argument: object2({17016 /**17017 * The name of the argument17018 */17019 name: string2(),17020 /**17021 * The value of the argument to use for completion matching.17022 */17023 value: string2()17024 }),17025 context: object2({17026 /**17027 * Previously-resolved variables in a URI template or prompt.17028 */17029 arguments: record(string2(), string2()).optional()17030 }).optional()17031});17032var CompleteRequestSchema = RequestSchema.extend({17033 method: literal("completion/complete"),17034 params: CompleteRequestParamsSchema17035});17036function assertCompleteRequestPrompt(request) {17037 if (request.params.ref.type !== "ref/prompt") {17038 throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);17039 }17040}17041function assertCompleteRequestResourceTemplate(request) {17042 if (request.params.ref.type !== "ref/resource") {17043 throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);17044 }17045}17046var CompleteResultSchema = ResultSchema.extend({17047 completion: looseObject({17048 /**17049 * An array of completion values. Must not exceed 100 items.17050 */17051 values: array(string2()).max(100),17052 /**17053 * The total number of completion options available. This can exceed the number of values actually sent in the response.17054 */17055 total: optional(number2().int()),17056 /**17057 * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.17058 */17059 hasMore: optional(boolean2())17060 })17061});17062var RootSchema = object2({17063 /**17064 * The URI identifying the root. This *must* start with file:// for now.17065 */17066 uri: string2().startsWith("file://"),17067 /**17068 * An optional name for the root.17069 */17070 name: string2().optional(),17071 /**17072 * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)17073 * for notes on _meta usage.17074 */17075 _meta: record(string2(), unknown()).optional()17076});17077var ListRootsRequestSchema = RequestSchema.extend({17078 method: literal("roots/list"),17079 params: BaseRequestParamsSchema.optional()17080});17081var ListRootsResultSchema = ResultSchema.extend({17082 roots: array(RootSchema)17083});17084var RootsListChangedNotificationSchema = NotificationSchema.extend({17085 method: literal("notifications/roots/list_changed"),17086 params: NotificationsParamsSchema.optional()17087});17088var ClientRequestSchema = union([17089 PingRequestSchema,17090 InitializeRequestSchema,17091 CompleteRequestSchema,17092 SetLevelRequestSchema,17093 GetPromptRequestSchema,17094 ListPromptsRequestSchema,17095 ListResourcesRequestSchema,17096 ListResourceTemplatesRequestSchema,17097 ReadResourceRequestSchema,17098 SubscribeRequestSchema,17099 UnsubscribeRequestSchema,17100 CallToolRequestSchema,17101 ListToolsRequestSchema,17102 GetTaskRequestSchema,17103 GetTaskPayloadRequestSchema,17104 ListTasksRequestSchema,17105 CancelTaskRequestSchema17106]);17107var ClientNotificationSchema = union([17108 CancelledNotificationSchema,17109 ProgressNotificationSchema,17110 InitializedNotificationSchema,17111 RootsListChangedNotificationSchema,17112 TaskStatusNotificationSchema17113]);17114var ClientResultSchema = union([17115 EmptyResultSchema,17116 CreateMessageResultSchema,17117 CreateMessageResultWithToolsSchema,17118 ElicitResultSchema,17119 ListRootsResultSchema,17120 GetTaskResultSchema,17121 ListTasksResultSchema,17122 CreateTaskResultSchema17123]);17124var ServerRequestSchema = union([17125 PingRequestSchema,17126 CreateMessageRequestSchema,17127 ElicitRequestSchema,17128 ListRootsRequestSchema,17129 GetTaskRequestSchema,17130 GetTaskPayloadRequestSchema,17131 ListTasksRequestSchema,17132 CancelTaskRequestSchema17133]);17134var ServerNotificationSchema = union([17135 CancelledNotificationSchema,17136 ProgressNotificationSchema,17137 LoggingMessageNotificationSchema,17138 ResourceUpdatedNotificationSchema,17139 ResourceListChangedNotificationSchema,17140 ToolListChangedNotificationSchema,17141 PromptListChangedNotificationSchema,17142 TaskStatusNotificationSchema,17143 ElicitationCompleteNotificationSchema17144]);17145var ServerResultSchema = union([17146 EmptyResultSchema,17147 InitializeResultSchema,17148 CompleteResultSchema,17149 GetPromptResultSchema,17150 ListPromptsResultSchema,17151 ListResourcesResultSchema,17152 ListResourceTemplatesResultSchema,17153 ReadResourceResultSchema,17154 CallToolResultSchema,17155 ListToolsResultSchema,17156 GetTaskResultSchema,17157 ListTasksResultSchema,17158 CreateTaskResultSchema17159]);17160var McpError = class _McpError extends Error {17161 constructor(code, message, data) {17162 super(`MCP error ${code}: ${message}`);17163 this.code = code;17164 this.data = data;17165 this.name = "McpError";17166 }17167 /**17168 * Factory method to create the appropriate error type based on the error code and data17169 */17170 static fromError(code, message, data) {17171 if (code === ErrorCode.UrlElicitationRequired && data) {17172 const errorData = data;17173 if (errorData.elicitations) {17174 return new UrlElicitationRequiredError(errorData.elicitations, message);17175 }17176 }17177 return new _McpError(code, message, data);17178 }17179};17180var UrlElicitationRequiredError = class extends McpError {17181 constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {17182 super(ErrorCode.UrlElicitationRequired, message, {17183 elicitations17184 });17185 }17186 get elicitations() {17187 return this.data?.elicitations ?? [];17188 }17189};1719017191// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js17192function isTerminal(status) {17193 return status === "completed" || status === "failed" || status === "cancelled";17194}1719517196// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js17197var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");17198var defaultOptions = {17199 name: void 0,17200 $refStrategy: "root",17201 basePath: ["#"],17202 effectStrategy: "input",17203 pipeStrategy: "all",17204 dateStrategy: "format:date-time",17205 mapStrategy: "entries",17206 removeAdditionalStrategy: "passthrough",17207 allowedAdditionalProperties: true,17208 rejectedAdditionalProperties: false,17209 definitionPath: "definitions",17210 target: "jsonSchema7",17211 strictUnions: false,17212 definitions: {},17213 errorMessages: false,17214 markdownDescription: false,17215 patternStrategy: "escape",17216 applyRegexFlags: false,17217 emailStrategy: "format:email",17218 base64Strategy: "contentEncoding:base64",17219 nameStrategy: "ref",17220 openAiAnyTypeName: "OpenAiAnyType"17221};17222var getDefaultOptions = (options) => typeof options === "string" ? {17223 ...defaultOptions,17224 name: options17225} : {17226 ...defaultOptions,17227 ...options17228};1722917230// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Refs.js17231var getRefs = (options) => {17232 const _options = getDefaultOptions(options);17233 const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;17234 return {17235 ..._options,17236 flags: { hasReferencedOpenAiAnyType: false },17237 currentPath,17238 propertyPath: void 0,17239 seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [17240 def._def,17241 {17242 def: def._def,17243 path: [..._options.basePath, _options.definitionPath, name],17244 // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.17245 jsonSchema: void 017246 }17247 ]))17248 };17249};1725017251// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/errorMessages.js17252function addErrorMessage(res, key, errorMessage, refs) {17253 if (!refs?.errorMessages)17254 return;17255 if (errorMessage) {17256 res.errorMessage = {17257 ...res.errorMessage,17258 [key]: errorMessage17259 };17260 }17261}17262function setResponseValueAndErrors(res, key, value, errorMessage, refs) {17263 res[key] = value;17264 addErrorMessage(res, key, errorMessage, refs);17265}1726617267// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js17268var getRelativePath = (pathA, pathB) => {17269 let i = 0;17270 for (; i < pathA.length && i < pathB.length; i++) {17271 if (pathA[i] !== pathB[i])17272 break;17273 }17274 return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");17275};1727617277// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/any.js17278function parseAnyDef(refs) {17279 if (refs.target !== "openAi") {17280 return {};17281 }17282 const anyDefinitionPath = [17283 ...refs.basePath,17284 refs.definitionPath,17285 refs.openAiAnyTypeName17286 ];17287 refs.flags.hasReferencedOpenAiAnyType = true;17288 return {17289 $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")17290 };17291}1729217293// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/array.js17294function parseArrayDef(def, refs) {17295 const res = {17296 type: "array"17297 };17298 if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {17299 res.items = parseDef(def.type._def, {17300 ...refs,17301 currentPath: [...refs.currentPath, "items"]17302 });17303 }17304 if (def.minLength) {17305 setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);17306 }17307 if (def.maxLength) {17308 setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);17309 }17310 if (def.exactLength) {17311 setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);17312 setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);17313 }17314 return res;17315}1731617317// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js17318function parseBigintDef(def, refs) {17319 const res = {17320 type: "integer",17321 format: "int64"17322 };17323 if (!def.checks)17324 return res;17325 for (const check2 of def.checks) {17326 switch (check2.kind) {17327 case "min":17328 if (refs.target === "jsonSchema7") {17329 if (check2.inclusive) {17330 setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);17331 } else {17332 setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);17333 }17334 } else {17335 if (!check2.inclusive) {17336 res.exclusiveMinimum = true;17337 }17338 setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);17339 }17340 break;17341 case "max":17342 if (refs.target === "jsonSchema7") {17343 if (check2.inclusive) {17344 setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);17345 } else {17346 setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);17347 }17348 } else {17349 if (!check2.inclusive) {17350 res.exclusiveMaximum = true;17351 }17352 setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);17353 }17354 break;17355 case "multipleOf":17356 setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);17357 break;17358 }17359 }17360 return res;17361}1736217363// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js17364function parseBooleanDef() {17365 return {17366 type: "boolean"17367 };17368}1736917370// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js17371function parseBrandedDef(_def, refs) {17372 return parseDef(_def.type._def, refs);17373}1737417375// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js17376var parseCatchDef = (def, refs) => {17377 return parseDef(def.innerType._def, refs);17378};1737917380// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/date.js17381function parseDateDef(def, refs, overrideDateStrategy) {17382 const strategy = overrideDateStrategy ?? refs.dateStrategy;17383 if (Array.isArray(strategy)) {17384 return {17385 anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))17386 };17387 }17388 switch (strategy) {17389 case "string":17390 case "format:date-time":17391 return {17392 type: "string",17393 format: "date-time"17394 };17395 case "format:date":17396 return {17397 type: "string",17398 format: "date"17399 };17400 case "integer":17401 return integerDateParser(def, refs);17402 }17403}17404var integerDateParser = (def, refs) => {17405 const res = {17406 type: "integer",17407 format: "unix-time"17408 };17409 if (refs.target === "openApi3") {17410 return res;17411 }17412 for (const check2 of def.checks) {17413 switch (check2.kind) {17414 case "min":17415 setResponseValueAndErrors(17416 res,17417 "minimum",17418 check2.value,17419 // This is in milliseconds17420 check2.message,17421 refs17422 );17423 break;17424 case "max":17425 setResponseValueAndErrors(17426 res,17427 "maximum",17428 check2.value,17429 // This is in milliseconds17430 check2.message,17431 refs17432 );17433 break;17434 }17435 }17436 return res;17437};1743817439// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/default.js17440function parseDefaultDef(_def, refs) {17441 return {17442 ...parseDef(_def.innerType._def, refs),17443 default: _def.defaultValue()17444 };17445}1744617447// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js17448function parseEffectsDef(_def, refs) {17449 return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);17450}1745117452// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js17453function parseEnumDef(def) {17454 return {17455 type: "string",17456 enum: Array.from(def.values)17457 };17458}1745917460// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js17461var isJsonSchema7AllOfType = (type) => {17462 if ("type" in type && type.type === "string")17463 return false;17464 return "allOf" in type;17465};17466function parseIntersectionDef(def, refs) {17467 const allOf = [17468 parseDef(def.left._def, {17469 ...refs,17470 currentPath: [...refs.currentPath, "allOf", "0"]17471 }),17472 parseDef(def.right._def, {17473 ...refs,17474 currentPath: [...refs.currentPath, "allOf", "1"]17475 })17476 ].filter((x) => !!x);17477 let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;17478 const mergedAllOf = [];17479 allOf.forEach((schema) => {17480 if (isJsonSchema7AllOfType(schema)) {17481 mergedAllOf.push(...schema.allOf);17482 if (schema.unevaluatedProperties === void 0) {17483 unevaluatedProperties = void 0;17484 }17485 } else {17486 let nestedSchema = schema;17487 if ("additionalProperties" in schema && schema.additionalProperties === false) {17488 const { additionalProperties, ...rest } = schema;17489 nestedSchema = rest;17490 } else {17491 unevaluatedProperties = void 0;17492 }17493 mergedAllOf.push(nestedSchema);17494 }17495 });17496 return mergedAllOf.length ? {17497 allOf: mergedAllOf,17498 ...unevaluatedProperties17499 } : void 0;17500}1750117502// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js17503function parseLiteralDef(def, refs) {17504 const parsedType2 = typeof def.value;17505 if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") {17506 return {17507 type: Array.isArray(def.value) ? "array" : "object"17508 };17509 }17510 if (refs.target === "openApi3") {17511 return {17512 type: parsedType2 === "bigint" ? "integer" : parsedType2,17513 enum: [def.value]17514 };17515 }17516 return {17517 type: parsedType2 === "bigint" ? "integer" : parsedType2,17518 const: def.value17519 };17520}1752117522// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js17523var emojiRegex2 = void 0;17524var zodPatterns = {17525 /**17526 * `c` was changed to `[cC]` to replicate /i flag17527 */17528 cuid: /^[cC][^\s-]{8,}$/,17529 cuid2: /^[0-9a-z]+$/,17530 ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,17531 /**17532 * `a-z` was added to replicate /i flag17533 */17534 email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,17535 /**17536 * Constructed a valid Unicode RegExp17537 *17538 * Lazily instantiate since this type of regex isn't supported17539 * in all envs (e.g. React Native).17540 *17541 * See:17542 * https://github.com/colinhacks/zod/issues/243317543 * Fix in Zod:17544 * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b17545 */17546 emoji: () => {17547 if (emojiRegex2 === void 0) {17548 emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");17549 }17550 return emojiRegex2;17551 },17552 /**17553 * Unused17554 */17555 uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,17556 /**17557 * Unused17558 */17559 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])$/,17560 ipv4Cidr: /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,17561 /**17562 * Unused17563 */17564 ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,17565 ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,17566 base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,17567 base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,17568 nanoid: /^[a-zA-Z0-9_-]{21}$/,17569 jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/17570};17571function parseStringDef(def, refs) {17572 const res = {17573 type: "string"17574 };17575 if (def.checks) {17576 for (const check2 of def.checks) {17577 switch (check2.kind) {17578 case "min":17579 setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);17580 break;17581 case "max":17582 setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);17583 break;17584 case "email":17585 switch (refs.emailStrategy) {17586 case "format:email":17587 addFormat(res, "email", check2.message, refs);17588 break;17589 case "format:idn-email":17590 addFormat(res, "idn-email", check2.message, refs);17591 break;17592 case "pattern:zod":17593 addPattern(res, zodPatterns.email, check2.message, refs);17594 break;17595 }17596 break;17597 case "url":17598 addFormat(res, "uri", check2.message, refs);17599 break;17600 case "uuid":17601 addFormat(res, "uuid", check2.message, refs);17602 break;17603 case "regex":17604 addPattern(res, check2.regex, check2.message, refs);17605 break;17606 case "cuid":17607 addPattern(res, zodPatterns.cuid, check2.message, refs);17608 break;17609 case "cuid2":17610 addPattern(res, zodPatterns.cuid2, check2.message, refs);17611 break;17612 case "startsWith":17613 addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs);17614 break;17615 case "endsWith":17616 addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs);17617 break;17618 case "datetime":17619 addFormat(res, "date-time", check2.message, refs);17620 break;17621 case "date":17622 addFormat(res, "date", check2.message, refs);17623 break;17624 case "time":17625 addFormat(res, "time", check2.message, refs);17626 break;17627 case "duration":17628 addFormat(res, "duration", check2.message, refs);17629 break;17630 case "length":17631 setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);17632 setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);17633 break;17634 case "includes": {17635 addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs);17636 break;17637 }17638 case "ip": {17639 if (check2.version !== "v6") {17640 addFormat(res, "ipv4", check2.message, refs);17641 }17642 if (check2.version !== "v4") {17643 addFormat(res, "ipv6", check2.message, refs);17644 }17645 break;17646 }17647 case "base64url":17648 addPattern(res, zodPatterns.base64url, check2.message, refs);17649 break;17650 case "jwt":17651 addPattern(res, zodPatterns.jwt, check2.message, refs);17652 break;17653 case "cidr": {17654 if (check2.version !== "v6") {17655 addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs);17656 }17657 if (check2.version !== "v4") {17658 addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs);17659 }17660 break;17661 }17662 case "emoji":17663 addPattern(res, zodPatterns.emoji(), check2.message, refs);17664 break;17665 case "ulid": {17666 addPattern(res, zodPatterns.ulid, check2.message, refs);17667 break;17668 }17669 case "base64": {17670 switch (refs.base64Strategy) {17671 case "format:binary": {17672 addFormat(res, "binary", check2.message, refs);17673 break;17674 }17675 case "contentEncoding:base64": {17676 setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs);17677 break;17678 }17679 case "pattern:zod": {17680 addPattern(res, zodPatterns.base64, check2.message, refs);17681 break;17682 }17683 }17684 break;17685 }17686 case "nanoid": {17687 addPattern(res, zodPatterns.nanoid, check2.message, refs);17688 }17689 case "toLowerCase":17690 case "toUpperCase":17691 case "trim":17692 break;17693 default:17694 /* @__PURE__ */ ((_) => {17695 })(check2);17696 }17697 }17698 }17699 return res;17700}17701function escapeLiteralCheckValue(literal2, refs) {17702 return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2;17703}17704var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");17705function escapeNonAlphaNumeric(source) {17706 let result = "";17707 for (let i = 0; i < source.length; i++) {17708 if (!ALPHA_NUMERIC.has(source[i])) {17709 result += "\\";17710 }17711 result += source[i];17712 }17713 return result;17714}17715function addFormat(schema, value, message, refs) {17716 if (schema.format || schema.anyOf?.some((x) => x.format)) {17717 if (!schema.anyOf) {17718 schema.anyOf = [];17719 }17720 if (schema.format) {17721 schema.anyOf.push({17722 format: schema.format,17723 ...schema.errorMessage && refs.errorMessages && {17724 errorMessage: { format: schema.errorMessage.format }17725 }17726 });17727 delete schema.format;17728 if (schema.errorMessage) {17729 delete schema.errorMessage.format;17730 if (Object.keys(schema.errorMessage).length === 0) {17731 delete schema.errorMessage;17732 }17733 }17734 }17735 schema.anyOf.push({17736 format: value,17737 ...message && refs.errorMessages && { errorMessage: { format: message } }17738 });17739 } else {17740 setResponseValueAndErrors(schema, "format", value, message, refs);17741 }17742}17743function addPattern(schema, regex, message, refs) {17744 if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {17745 if (!schema.allOf) {17746 schema.allOf = [];17747 }17748 if (schema.pattern) {17749 schema.allOf.push({17750 pattern: schema.pattern,17751 ...schema.errorMessage && refs.errorMessages && {17752 errorMessage: { pattern: schema.errorMessage.pattern }17753 }17754 });17755 delete schema.pattern;17756 if (schema.errorMessage) {17757 delete schema.errorMessage.pattern;17758 if (Object.keys(schema.errorMessage).length === 0) {17759 delete schema.errorMessage;17760 }17761 }17762 }17763 schema.allOf.push({17764 pattern: stringifyRegExpWithFlags(regex, refs),17765 ...message && refs.errorMessages && { errorMessage: { pattern: message } }17766 });17767 } else {17768 setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);17769 }17770}17771function stringifyRegExpWithFlags(regex, refs) {17772 if (!refs.applyRegexFlags || !regex.flags) {17773 return regex.source;17774 }17775 const flags = {17776 i: regex.flags.includes("i"),17777 m: regex.flags.includes("m"),17778 s: regex.flags.includes("s")17779 // `.` matches newlines17780 };17781 const source = flags.i ? regex.source.toLowerCase() : regex.source;17782 let pattern = "";17783 let isEscaped = false;17784 let inCharGroup = false;17785 let inCharRange = false;17786 for (let i = 0; i < source.length; i++) {17787 if (isEscaped) {17788 pattern += source[i];17789 isEscaped = false;17790 continue;17791 }17792 if (flags.i) {17793 if (inCharGroup) {17794 if (source[i].match(/[a-z]/)) {17795 if (inCharRange) {17796 pattern += source[i];17797 pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();17798 inCharRange = false;17799 } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {17800 pattern += source[i];17801 inCharRange = true;17802 } else {17803 pattern += `${source[i]}${source[i].toUpperCase()}`;17804 }17805 continue;17806 }17807 } else if (source[i].match(/[a-z]/)) {17808 pattern += `[${source[i]}${source[i].toUpperCase()}]`;17809 continue;17810 }17811 }17812 if (flags.m) {17813 if (source[i] === "^") {17814 pattern += `(^|(?<=[\r17815]))`;17816 continue;17817 } else if (source[i] === "$") {17818 pattern += `($|(?=[\r17819]))`;17820 continue;17821 }17822 }17823 if (flags.s && source[i] === ".") {17824 pattern += inCharGroup ? `${source[i]}\r17825` : `[${source[i]}\r17826]`;17827 continue;17828 }17829 pattern += source[i];17830 if (source[i] === "\\") {17831 isEscaped = true;17832 } else if (inCharGroup && source[i] === "]") {17833 inCharGroup = false;17834 } else if (!inCharGroup && source[i] === "[") {17835 inCharGroup = true;17836 }17837 }17838 try {17839 new RegExp(pattern);17840 } catch {17841 console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);17842 return regex.source;17843 }17844 return pattern;17845}1784617847// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js17848function parseRecordDef(def, refs) {17849 if (refs.target === "openAi") {17850 console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");17851 }17852 if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {17853 return {17854 type: "object",17855 required: def.keyType._def.values,17856 properties: def.keyType._def.values.reduce((acc, key) => ({17857 ...acc,17858 [key]: parseDef(def.valueType._def, {17859 ...refs,17860 currentPath: [...refs.currentPath, "properties", key]17861 }) ?? parseAnyDef(refs)17862 }), {}),17863 additionalProperties: refs.rejectedAdditionalProperties17864 };17865 }17866 const schema = {17867 type: "object",17868 additionalProperties: parseDef(def.valueType._def, {17869 ...refs,17870 currentPath: [...refs.currentPath, "additionalProperties"]17871 }) ?? refs.allowedAdditionalProperties17872 };17873 if (refs.target === "openApi3") {17874 return schema;17875 }17876 if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {17877 const { type, ...keyType } = parseStringDef(def.keyType._def, refs);17878 return {17879 ...schema,17880 propertyNames: keyType17881 };17882 } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {17883 return {17884 ...schema,17885 propertyNames: {17886 enum: def.keyType._def.values17887 }17888 };17889 } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {17890 const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);17891 return {17892 ...schema,17893 propertyNames: keyType17894 };17895 }17896 return schema;17897}1789817899// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/map.js17900function parseMapDef(def, refs) {17901 if (refs.mapStrategy === "record") {17902 return parseRecordDef(def, refs);17903 }17904 const keys = parseDef(def.keyType._def, {17905 ...refs,17906 currentPath: [...refs.currentPath, "items", "items", "0"]17907 }) || parseAnyDef(refs);17908 const values = parseDef(def.valueType._def, {17909 ...refs,17910 currentPath: [...refs.currentPath, "items", "items", "1"]17911 }) || parseAnyDef(refs);17912 return {17913 type: "array",17914 maxItems: 125,17915 items: {17916 type: "array",17917 items: [keys, values],17918 minItems: 2,17919 maxItems: 217920 }17921 };17922}1792317924// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js17925function parseNativeEnumDef(def) {17926 const object3 = def.values;17927 const actualKeys = Object.keys(def.values).filter((key) => {17928 return typeof object3[object3[key]] !== "number";17929 });17930 const actualValues = actualKeys.map((key) => object3[key]);17931 const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));17932 return {17933 type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],17934 enum: actualValues17935 };17936}1793717938// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/never.js17939function parseNeverDef(refs) {17940 return refs.target === "openAi" ? void 0 : {17941 not: parseAnyDef({17942 ...refs,17943 currentPath: [...refs.currentPath, "not"]17944 })17945 };17946}1794717948// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/null.js17949function parseNullDef(refs) {17950 return refs.target === "openApi3" ? {17951 enum: ["null"],17952 nullable: true17953 } : {17954 type: "null"17955 };17956}1795717958// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/union.js17959var primitiveMappings = {17960 ZodString: "string",17961 ZodNumber: "number",17962 ZodBigInt: "integer",17963 ZodBoolean: "boolean",17964 ZodNull: "null"17965};17966function parseUnionDef(def, refs) {17967 if (refs.target === "openApi3")17968 return asAnyOf(def, refs);17969 const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;17970 if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {17971 const types = options.reduce((types2, x) => {17972 const type = primitiveMappings[x._def.typeName];17973 return type && !types2.includes(type) ? [...types2, type] : types2;17974 }, []);17975 return {17976 type: types.length > 1 ? types : types[0]17977 };17978 } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {17979 const types = options.reduce((acc, x) => {17980 const type = typeof x._def.value;17981 switch (type) {17982 case "string":17983 case "number":17984 case "boolean":17985 return [...acc, type];17986 case "bigint":17987 return [...acc, "integer"];17988 case "object":17989 if (x._def.value === null)17990 return [...acc, "null"];17991 case "symbol":17992 case "undefined":17993 case "function":17994 default:17995 return acc;17996 }17997 }, []);17998 if (types.length === options.length) {17999 const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);18000 return {18001 type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],18002 enum: options.reduce((acc, x) => {18003 return acc.includes(x._def.value) ? acc : [...acc, x._def.value];18004 }, [])18005 };18006 }18007 } else if (options.every((x) => x._def.typeName === "ZodEnum")) {18008 return {18009 type: "string",18010 enum: options.reduce((acc, x) => [18011 ...acc,18012 ...x._def.values.filter((x2) => !acc.includes(x2))18013 ], [])18014 };18015 }18016 return asAnyOf(def, refs);18017}18018var asAnyOf = (def, refs) => {18019 const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {18020 ...refs,18021 currentPath: [...refs.currentPath, "anyOf", `${i}`]18022 })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));18023 return anyOf.length ? { anyOf } : void 0;18024};1802518026// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js18027function parseNullableDef(def, refs) {18028 if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {18029 if (refs.target === "openApi3") {18030 return {18031 type: primitiveMappings[def.innerType._def.typeName],18032 nullable: true18033 };18034 }18035 return {18036 type: [18037 primitiveMappings[def.innerType._def.typeName],18038 "null"18039 ]18040 };18041 }18042 if (refs.target === "openApi3") {18043 const base2 = parseDef(def.innerType._def, {18044 ...refs,18045 currentPath: [...refs.currentPath]18046 });18047 if (base2 && "$ref" in base2)18048 return { allOf: [base2], nullable: true };18049 return base2 && { ...base2, nullable: true };18050 }18051 const base = parseDef(def.innerType._def, {18052 ...refs,18053 currentPath: [...refs.currentPath, "anyOf", "0"]18054 });18055 return base && { anyOf: [base, { type: "null" }] };18056}1805718058// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/number.js18059function parseNumberDef(def, refs) {18060 const res = {18061 type: "number"18062 };18063 if (!def.checks)18064 return res;18065 for (const check2 of def.checks) {18066 switch (check2.kind) {18067 case "int":18068 res.type = "integer";18069 addErrorMessage(res, "type", check2.message, refs);18070 break;18071 case "min":18072 if (refs.target === "jsonSchema7") {18073 if (check2.inclusive) {18074 setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);18075 } else {18076 setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);18077 }18078 } else {18079 if (!check2.inclusive) {18080 res.exclusiveMinimum = true;18081 }18082 setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);18083 }18084 break;18085 case "max":18086 if (refs.target === "jsonSchema7") {18087 if (check2.inclusive) {18088 setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);18089 } else {18090 setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);18091 }18092 } else {18093 if (!check2.inclusive) {18094 res.exclusiveMaximum = true;18095 }18096 setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);18097 }18098 break;18099 case "multipleOf":18100 setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);18101 break;18102 }18103 }18104 return res;18105}1810618107// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/object.js18108function parseObjectDef(def, refs) {18109 const forceOptionalIntoNullable = refs.target === "openAi";18110 const result = {18111 type: "object",18112 properties: {}18113 };18114 const required2 = [];18115 const shape = def.shape();18116 for (const propName in shape) {18117 let propDef = shape[propName];18118 if (propDef === void 0 || propDef._def === void 0) {18119 continue;18120 }18121 let propOptional = safeIsOptional(propDef);18122 if (propOptional && forceOptionalIntoNullable) {18123 if (propDef._def.typeName === "ZodOptional") {18124 propDef = propDef._def.innerType;18125 }18126 if (!propDef.isNullable()) {18127 propDef = propDef.nullable();18128 }18129 propOptional = false;18130 }18131 const parsedDef = parseDef(propDef._def, {18132 ...refs,18133 currentPath: [...refs.currentPath, "properties", propName],18134 propertyPath: [...refs.currentPath, "properties", propName]18135 });18136 if (parsedDef === void 0) {18137 continue;18138 }18139 result.properties[propName] = parsedDef;18140 if (!propOptional) {18141 required2.push(propName);18142 }18143 }18144 if (required2.length) {18145 result.required = required2;18146 }18147 const additionalProperties = decideAdditionalProperties(def, refs);18148 if (additionalProperties !== void 0) {18149 result.additionalProperties = additionalProperties;18150 }18151 return result;18152}18153function decideAdditionalProperties(def, refs) {18154 if (def.catchall._def.typeName !== "ZodNever") {18155 return parseDef(def.catchall._def, {18156 ...refs,18157 currentPath: [...refs.currentPath, "additionalProperties"]18158 });18159 }18160 switch (def.unknownKeys) {18161 case "passthrough":18162 return refs.allowedAdditionalProperties;18163 case "strict":18164 return refs.rejectedAdditionalProperties;18165 case "strip":18166 return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;18167 }18168}18169function safeIsOptional(schema) {18170 try {18171 return schema.isOptional();18172 } catch {18173 return true;18174 }18175}1817618177// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js18178var parseOptionalDef = (def, refs) => {18179 if (refs.currentPath.toString() === refs.propertyPath?.toString()) {18180 return parseDef(def.innerType._def, refs);18181 }18182 const innerSchema = parseDef(def.innerType._def, {18183 ...refs,18184 currentPath: [...refs.currentPath, "anyOf", "1"]18185 });18186 return innerSchema ? {18187 anyOf: [18188 {18189 not: parseAnyDef(refs)18190 },18191 innerSchema18192 ]18193 } : parseAnyDef(refs);18194};1819518196// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js18197var parsePipelineDef = (def, refs) => {18198 if (refs.pipeStrategy === "input") {18199 return parseDef(def.in._def, refs);18200 } else if (refs.pipeStrategy === "output") {18201 return parseDef(def.out._def, refs);18202 }18203 const a = parseDef(def.in._def, {18204 ...refs,18205 currentPath: [...refs.currentPath, "allOf", "0"]18206 });18207 const b = parseDef(def.out._def, {18208 ...refs,18209 currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]18210 });18211 return {18212 allOf: [a, b].filter((x) => x !== void 0)18213 };18214};1821518216// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js18217function parsePromiseDef(def, refs) {18218 return parseDef(def.type._def, refs);18219}1822018221// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/set.js18222function parseSetDef(def, refs) {18223 const items = parseDef(def.valueType._def, {18224 ...refs,18225 currentPath: [...refs.currentPath, "items"]18226 });18227 const schema = {18228 type: "array",18229 uniqueItems: true,18230 items18231 };18232 if (def.minSize) {18233 setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);18234 }18235 if (def.maxSize) {18236 setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);18237 }18238 return schema;18239}1824018241// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js18242function parseTupleDef(def, refs) {18243 if (def.rest) {18244 return {18245 type: "array",18246 minItems: def.items.length,18247 items: def.items.map((x, i) => parseDef(x._def, {18248 ...refs,18249 currentPath: [...refs.currentPath, "items", `${i}`]18250 })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),18251 additionalItems: parseDef(def.rest._def, {18252 ...refs,18253 currentPath: [...refs.currentPath, "additionalItems"]18254 })18255 };18256 } else {18257 return {18258 type: "array",18259 minItems: def.items.length,18260 maxItems: def.items.length,18261 items: def.items.map((x, i) => parseDef(x._def, {18262 ...refs,18263 currentPath: [...refs.currentPath, "items", `${i}`]18264 })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])18265 };18266 }18267}1826818269// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js18270function parseUndefinedDef(refs) {18271 return {18272 not: parseAnyDef(refs)18273 };18274}1827518276// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js18277function parseUnknownDef(refs) {18278 return parseAnyDef(refs);18279}1828018281// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js18282var parseReadonlyDef = (def, refs) => {18283 return parseDef(def.innerType._def, refs);18284};1828518286// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js18287var selectParser = (def, typeName, refs) => {18288 switch (typeName) {18289 case ZodFirstPartyTypeKind.ZodString:18290 return parseStringDef(def, refs);18291 case ZodFirstPartyTypeKind.ZodNumber:18292 return parseNumberDef(def, refs);18293 case ZodFirstPartyTypeKind.ZodObject:18294 return parseObjectDef(def, refs);18295 case ZodFirstPartyTypeKind.ZodBigInt:18296 return parseBigintDef(def, refs);18297 case ZodFirstPartyTypeKind.ZodBoolean:18298 return parseBooleanDef();18299 case ZodFirstPartyTypeKind.ZodDate:18300 return parseDateDef(def, refs);18301 case ZodFirstPartyTypeKind.ZodUndefined:18302 return parseUndefinedDef(refs);18303 case ZodFirstPartyTypeKind.ZodNull:18304 return parseNullDef(refs);18305 case ZodFirstPartyTypeKind.ZodArray:18306 return parseArrayDef(def, refs);18307 case ZodFirstPartyTypeKind.ZodUnion:18308 case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:18309 return parseUnionDef(def, refs);18310 case ZodFirstPartyTypeKind.ZodIntersection:18311 return parseIntersectionDef(def, refs);18312 case ZodFirstPartyTypeKind.ZodTuple:18313 return parseTupleDef(def, refs);18314 case ZodFirstPartyTypeKind.ZodRecord:18315 return parseRecordDef(def, refs);18316 case ZodFirstPartyTypeKind.ZodLiteral:18317 return parseLiteralDef(def, refs);18318 case ZodFirstPartyTypeKind.ZodEnum:18319 return parseEnumDef(def);18320 case ZodFirstPartyTypeKind.ZodNativeEnum:18321 return parseNativeEnumDef(def);18322 case ZodFirstPartyTypeKind.ZodNullable:18323 return parseNullableDef(def, refs);18324 case ZodFirstPartyTypeKind.ZodOptional:18325 return parseOptionalDef(def, refs);18326 case ZodFirstPartyTypeKind.ZodMap:18327 return parseMapDef(def, refs);18328 case ZodFirstPartyTypeKind.ZodSet:18329 return parseSetDef(def, refs);18330 case ZodFirstPartyTypeKind.ZodLazy:18331 return () => def.getter()._def;18332 case ZodFirstPartyTypeKind.ZodPromise:18333 return parsePromiseDef(def, refs);18334 case ZodFirstPartyTypeKind.ZodNaN:18335 case ZodFirstPartyTypeKind.ZodNever:18336 return parseNeverDef(refs);18337 case ZodFirstPartyTypeKind.ZodEffects:18338 return parseEffectsDef(def, refs);18339 case ZodFirstPartyTypeKind.ZodAny:18340 return parseAnyDef(refs);18341 case ZodFirstPartyTypeKind.ZodUnknown:18342 return parseUnknownDef(refs);18343 case ZodFirstPartyTypeKind.ZodDefault:18344 return parseDefaultDef(def, refs);18345 case ZodFirstPartyTypeKind.ZodBranded:18346 return parseBrandedDef(def, refs);18347 case ZodFirstPartyTypeKind.ZodReadonly:18348 return parseReadonlyDef(def, refs);18349 case ZodFirstPartyTypeKind.ZodCatch:18350 return parseCatchDef(def, refs);18351 case ZodFirstPartyTypeKind.ZodPipeline:18352 return parsePipelineDef(def, refs);18353 case ZodFirstPartyTypeKind.ZodFunction:18354 case ZodFirstPartyTypeKind.ZodVoid:18355 case ZodFirstPartyTypeKind.ZodSymbol:18356 return void 0;18357 default:18358 return /* @__PURE__ */ ((_) => void 0)(typeName);18359 }18360};1836118362// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parseDef.js18363function parseDef(def, refs, forceResolution = false) {18364 const seenItem = refs.seen.get(def);18365 if (refs.override) {18366 const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);18367 if (overrideResult !== ignoreOverride) {18368 return overrideResult;18369 }18370 }18371 if (seenItem && !forceResolution) {18372 const seenSchema = get$ref(seenItem, refs);18373 if (seenSchema !== void 0) {18374 return seenSchema;18375 }18376 }18377 const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };18378 refs.seen.set(def, newItem);18379 const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);18380 const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;18381 if (jsonSchema) {18382 addMeta(def, refs, jsonSchema);18383 }18384 if (refs.postProcess) {18385 const postProcessResult = refs.postProcess(jsonSchema, def, refs);18386 newItem.jsonSchema = jsonSchema;18387 return postProcessResult;18388 }18389 newItem.jsonSchema = jsonSchema;18390 return jsonSchema;18391}18392var get$ref = (item, refs) => {18393 switch (refs.$refStrategy) {18394 case "root":18395 return { $ref: item.path.join("/") };18396 case "relative":18397 return { $ref: getRelativePath(refs.currentPath, item.path) };18398 case "none":18399 case "seen": {18400 if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {18401 console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);18402 return parseAnyDef(refs);18403 }18404 return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;18405 }18406 }18407};18408var addMeta = (def, refs, jsonSchema) => {18409 if (def.description) {18410 jsonSchema.description = def.description;18411 if (refs.markdownDescription) {18412 jsonSchema.markdownDescription = def.description;18413 }18414 }18415 return jsonSchema;18416};1841718418// ../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js18419var zodToJsonSchema = (schema, options) => {18420 const refs = getRefs(options);18421 let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({18422 ...acc,18423 [name2]: parseDef(schema2._def, {18424 ...refs,18425 currentPath: [...refs.basePath, refs.definitionPath, name2]18426 }, true) ?? parseAnyDef(refs)18427 }), {}) : void 0;18428 const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;18429 const main2 = parseDef(schema._def, name === void 0 ? refs : {18430 ...refs,18431 currentPath: [...refs.basePath, refs.definitionPath, name]18432 }, false) ?? parseAnyDef(refs);18433 const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;18434 if (title !== void 0) {18435 main2.title = title;18436 }18437 if (refs.flags.hasReferencedOpenAiAnyType) {18438 if (!definitions) {18439 definitions = {};18440 }18441 if (!definitions[refs.openAiAnyTypeName]) {18442 definitions[refs.openAiAnyTypeName] = {18443 // Skipping "object" as no properties can be defined and additionalProperties must be "false"18444 type: ["string", "number", "integer", "boolean", "array", "null"],18445 items: {18446 $ref: refs.$refStrategy === "relative" ? "1" : [18447 ...refs.basePath,18448 refs.definitionPath,18449 refs.openAiAnyTypeName18450 ].join("/")18451 }18452 };18453 }18454 }18455 const combined = name === void 0 ? definitions ? {18456 ...main2,18457 [refs.definitionPath]: definitions18458 } : main2 : {18459 $ref: [18460 ...refs.$refStrategy === "relative" ? [] : refs.basePath,18461 refs.definitionPath,18462 name18463 ].join("/"),18464 [refs.definitionPath]: {18465 ...definitions,18466 [name]: main218467 }18468 };18469 if (refs.target === "jsonSchema7") {18470 combined.$schema = "http://json-schema.org/draft-07/schema#";18471 } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {18472 combined.$schema = "https://json-schema.org/draft/2019-09/schema#";18473 }18474 if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {18475 console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");18476 }18477 return combined;18478};1847918480// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js18481function mapMiniTarget(t) {18482 if (!t)18483 return "draft-7";18484 if (t === "jsonSchema7" || t === "draft-7")18485 return "draft-7";18486 if (t === "jsonSchema2019-09" || t === "draft-2020-12")18487 return "draft-2020-12";18488 return "draft-7";18489}18490function toJsonSchemaCompat(schema, opts) {18491 if (isZ4Schema(schema)) {18492 return toJSONSchema(schema, {18493 target: mapMiniTarget(opts?.target),18494 io: opts?.pipeStrategy ?? "input"18495 });18496 }18497 return zodToJsonSchema(schema, {18498 strictUnions: opts?.strictUnions ?? true,18499 pipeStrategy: opts?.pipeStrategy ?? "input"18500 });18501}18502function getMethodLiteral(schema) {18503 const shape = getObjectShape(schema);18504 const methodSchema = shape?.method;18505 if (!methodSchema) {18506 throw new Error("Schema is missing a method literal");18507 }18508 const value = getLiteralValue(methodSchema);18509 if (typeof value !== "string") {18510 throw new Error("Schema method literal must be a string");18511 }18512 return value;18513}18514function parseWithCompat(schema, data) {18515 const result = safeParse2(schema, data);18516 if (!result.success) {18517 throw result.error;18518 }18519 return result.data;18520}1852118522// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js18523var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;18524var Protocol = class {18525 constructor(_options) {18526 this._options = _options;18527 this._requestMessageId = 0;18528 this._requestHandlers = /* @__PURE__ */ new Map();18529 this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();18530 this._notificationHandlers = /* @__PURE__ */ new Map();18531 this._responseHandlers = /* @__PURE__ */ new Map();18532 this._progressHandlers = /* @__PURE__ */ new Map();18533 this._timeoutInfo = /* @__PURE__ */ new Map();18534 this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();18535 this._taskProgressTokens = /* @__PURE__ */ new Map();18536 this._requestResolvers = /* @__PURE__ */ new Map();18537 this.setNotificationHandler(CancelledNotificationSchema, (notification) => {18538 this._oncancel(notification);18539 });18540 this.setNotificationHandler(ProgressNotificationSchema, (notification) => {18541 this._onprogress(notification);18542 });18543 this.setRequestHandler(18544 PingRequestSchema,18545 // Automatic pong by default.18546 (_request) => ({})18547 );18548 this._taskStore = _options?.taskStore;18549 this._taskMessageQueue = _options?.taskMessageQueue;18550 if (this._taskStore) {18551 this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {18552 const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);18553 if (!task) {18554 throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");18555 }18556 return {18557 ...task18558 };18559 });18560 this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {18561 const handleTaskResult = async () => {18562 const taskId = request.params.taskId;18563 if (this._taskMessageQueue) {18564 let queuedMessage;18565 while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {18566 if (queuedMessage.type === "response" || queuedMessage.type === "error") {18567 const message = queuedMessage.message;18568 const requestId = message.id;18569 const resolver = this._requestResolvers.get(requestId);18570 if (resolver) {18571 this._requestResolvers.delete(requestId);18572 if (queuedMessage.type === "response") {18573 resolver(message);18574 } else {18575 const errorMessage = message;18576 const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);18577 resolver(error2);18578 }18579 } else {18580 const messageType = queuedMessage.type === "response" ? "Response" : "Error";18581 this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));18582 }18583 continue;18584 }18585 await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });18586 }18587 }18588 const task = await this._taskStore.getTask(taskId, extra.sessionId);18589 if (!task) {18590 throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);18591 }18592 if (!isTerminal(task.status)) {18593 await this._waitForTaskUpdate(taskId, extra.signal);18594 return await handleTaskResult();18595 }18596 if (isTerminal(task.status)) {18597 const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);18598 this._clearTaskQueue(taskId);18599 return {18600 ...result,18601 _meta: {18602 ...result._meta,18603 [RELATED_TASK_META_KEY]: {18604 taskId18605 }18606 }18607 };18608 }18609 return await handleTaskResult();18610 };18611 return await handleTaskResult();18612 });18613 this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {18614 try {18615 const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);18616 return {18617 tasks,18618 nextCursor,18619 _meta: {}18620 };18621 } catch (error2) {18622 throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);18623 }18624 });18625 this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {18626 try {18627 const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);18628 if (!task) {18629 throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);18630 }18631 if (isTerminal(task.status)) {18632 throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);18633 }18634 await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);18635 this._clearTaskQueue(request.params.taskId);18636 const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);18637 if (!cancelledTask) {18638 throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);18639 }18640 return {18641 _meta: {},18642 ...cancelledTask18643 };18644 } catch (error2) {18645 if (error2 instanceof McpError) {18646 throw error2;18647 }18648 throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`);18649 }18650 });18651 }18652 }18653 async _oncancel(notification) {18654 if (!notification.params.requestId) {18655 return;18656 }18657 const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);18658 controller?.abort(notification.params.reason);18659 }18660 _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {18661 this._timeoutInfo.set(messageId, {18662 timeoutId: setTimeout(onTimeout, timeout),18663 startTime: Date.now(),18664 timeout,18665 maxTotalTimeout,18666 resetTimeoutOnProgress,18667 onTimeout18668 });18669 }18670 _resetTimeout(messageId) {18671 const info = this._timeoutInfo.get(messageId);18672 if (!info)18673 return false;18674 const totalElapsed = Date.now() - info.startTime;18675 if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {18676 this._timeoutInfo.delete(messageId);18677 throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {18678 maxTotalTimeout: info.maxTotalTimeout,18679 totalElapsed18680 });18681 }18682 clearTimeout(info.timeoutId);18683 info.timeoutId = setTimeout(info.onTimeout, info.timeout);18684 return true;18685 }18686 _cleanupTimeout(messageId) {18687 const info = this._timeoutInfo.get(messageId);18688 if (info) {18689 clearTimeout(info.timeoutId);18690 this._timeoutInfo.delete(messageId);18691 }18692 }18693 /**18694 * Attaches to the given transport, starts it, and starts listening for messages.18695 *18696 * 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.18697 */18698 async connect(transport) {18699 if (this._transport) {18700 throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");18701 }18702 this._transport = transport;18703 const _onclose = this.transport?.onclose;18704 this._transport.onclose = () => {18705 _onclose?.();18706 this._onclose();18707 };18708 const _onerror = this.transport?.onerror;18709 this._transport.onerror = (error2) => {18710 _onerror?.(error2);18711 this._onerror(error2);18712 };18713 const _onmessage = this._transport?.onmessage;18714 this._transport.onmessage = (message, extra) => {18715 _onmessage?.(message, extra);18716 if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {18717 this._onresponse(message);18718 } else if (isJSONRPCRequest(message)) {18719 this._onrequest(message, extra);18720 } else if (isJSONRPCNotification(message)) {18721 this._onnotification(message);18722 } else {18723 this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));18724 }18725 };18726 await this._transport.start();18727 }18728 _onclose() {18729 const responseHandlers = this._responseHandlers;18730 this._responseHandlers = /* @__PURE__ */ new Map();18731 this._progressHandlers.clear();18732 this._taskProgressTokens.clear();18733 this._pendingDebouncedNotifications.clear();18734 for (const info of this._timeoutInfo.values()) {18735 clearTimeout(info.timeoutId);18736 }18737 this._timeoutInfo.clear();18738 for (const controller of this._requestHandlerAbortControllers.values()) {18739 controller.abort();18740 }18741 this._requestHandlerAbortControllers.clear();18742 const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");18743 this._transport = void 0;18744 this.onclose?.();18745 for (const handler of responseHandlers.values()) {18746 handler(error2);18747 }18748 }18749 _onerror(error2) {18750 this.onerror?.(error2);18751 }18752 _onnotification(notification) {18753 const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;18754 if (handler === void 0) {18755 return;18756 }18757 Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));18758 }18759 _onrequest(request, extra) {18760 const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;18761 const capturedTransport = this._transport;18762 const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;18763 if (handler === void 0) {18764 const errorResponse = {18765 jsonrpc: "2.0",18766 id: request.id,18767 error: {18768 code: ErrorCode.MethodNotFound,18769 message: "Method not found"18770 }18771 };18772 if (relatedTaskId && this._taskMessageQueue) {18773 this._enqueueTaskMessage(relatedTaskId, {18774 type: "error",18775 message: errorResponse,18776 timestamp: Date.now()18777 }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));18778 } else {18779 capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));18780 }18781 return;18782 }18783 const abortController = new AbortController();18784 this._requestHandlerAbortControllers.set(request.id, abortController);18785 const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;18786 const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;18787 const fullExtra = {18788 signal: abortController.signal,18789 sessionId: capturedTransport?.sessionId,18790 _meta: request.params?._meta,18791 sendNotification: async (notification) => {18792 if (abortController.signal.aborted)18793 return;18794 const notificationOptions = { relatedRequestId: request.id };18795 if (relatedTaskId) {18796 notificationOptions.relatedTask = { taskId: relatedTaskId };18797 }18798 await this.notification(notification, notificationOptions);18799 },18800 sendRequest: async (r, resultSchema, options) => {18801 if (abortController.signal.aborted) {18802 throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");18803 }18804 const requestOptions = { ...options, relatedRequestId: request.id };18805 if (relatedTaskId && !requestOptions.relatedTask) {18806 requestOptions.relatedTask = { taskId: relatedTaskId };18807 }18808 const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;18809 if (effectiveTaskId && taskStore) {18810 await taskStore.updateTaskStatus(effectiveTaskId, "input_required");18811 }18812 return await this.request(r, resultSchema, requestOptions);18813 },18814 authInfo: extra?.authInfo,18815 requestId: request.id,18816 requestInfo: extra?.requestInfo,18817 taskId: relatedTaskId,18818 taskStore,18819 taskRequestedTtl: taskCreationParams?.ttl,18820 closeSSEStream: extra?.closeSSEStream,18821 closeStandaloneSSEStream: extra?.closeStandaloneSSEStream18822 };18823 Promise.resolve().then(() => {18824 if (taskCreationParams) {18825 this.assertTaskHandlerCapability(request.method);18826 }18827 }).then(() => handler(request, fullExtra)).then(async (result) => {18828 if (abortController.signal.aborted) {18829 return;18830 }18831 const response = {18832 result,18833 jsonrpc: "2.0",18834 id: request.id18835 };18836 if (relatedTaskId && this._taskMessageQueue) {18837 await this._enqueueTaskMessage(relatedTaskId, {18838 type: "response",18839 message: response,18840 timestamp: Date.now()18841 }, capturedTransport?.sessionId);18842 } else {18843 await capturedTransport?.send(response);18844 }18845 }, async (error2) => {18846 if (abortController.signal.aborted) {18847 return;18848 }18849 const errorResponse = {18850 jsonrpc: "2.0",18851 id: request.id,18852 error: {18853 code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,18854 message: error2.message ?? "Internal error",18855 ...error2["data"] !== void 0 && { data: error2["data"] }18856 }18857 };18858 if (relatedTaskId && this._taskMessageQueue) {18859 await this._enqueueTaskMessage(relatedTaskId, {18860 type: "error",18861 message: errorResponse,18862 timestamp: Date.now()18863 }, capturedTransport?.sessionId);18864 } else {18865 await capturedTransport?.send(errorResponse);18866 }18867 }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {18868 if (this._requestHandlerAbortControllers.get(request.id) === abortController) {18869 this._requestHandlerAbortControllers.delete(request.id);18870 }18871 });18872 }18873 _onprogress(notification) {18874 const { progressToken, ...params } = notification.params;18875 const messageId = Number(progressToken);18876 const handler = this._progressHandlers.get(messageId);18877 if (!handler) {18878 this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));18879 return;18880 }18881 const responseHandler = this._responseHandlers.get(messageId);18882 const timeoutInfo = this._timeoutInfo.get(messageId);18883 if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {18884 try {18885 this._resetTimeout(messageId);18886 } catch (error2) {18887 this._responseHandlers.delete(messageId);18888 this._progressHandlers.delete(messageId);18889 this._cleanupTimeout(messageId);18890 responseHandler(error2);18891 return;18892 }18893 }18894 handler(params);18895 }18896 _onresponse(response) {18897 const messageId = Number(response.id);18898 const resolver = this._requestResolvers.get(messageId);18899 if (resolver) {18900 this._requestResolvers.delete(messageId);18901 if (isJSONRPCResultResponse(response)) {18902 resolver(response);18903 } else {18904 const error2 = new McpError(response.error.code, response.error.message, response.error.data);18905 resolver(error2);18906 }18907 return;18908 }18909 const handler = this._responseHandlers.get(messageId);18910 if (handler === void 0) {18911 this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));18912 return;18913 }18914 this._responseHandlers.delete(messageId);18915 this._cleanupTimeout(messageId);18916 let isTaskResponse = false;18917 if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {18918 const result = response.result;18919 if (result.task && typeof result.task === "object") {18920 const task = result.task;18921 if (typeof task.taskId === "string") {18922 isTaskResponse = true;18923 this._taskProgressTokens.set(task.taskId, messageId);18924 }18925 }18926 }18927 if (!isTaskResponse) {18928 this._progressHandlers.delete(messageId);18929 }18930 if (isJSONRPCResultResponse(response)) {18931 handler(response);18932 } else {18933 const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data);18934 handler(error2);18935 }18936 }18937 get transport() {18938 return this._transport;18939 }18940 /**18941 * Closes the connection.18942 */18943 async close() {18944 await this._transport?.close();18945 }18946 /**18947 * Sends a request and returns an AsyncGenerator that yields response messages.18948 * The generator is guaranteed to end with either a 'result' or 'error' message.18949 *18950 * @example18951 * ```typescript18952 * const stream = protocol.requestStream(request, resultSchema, options);18953 * for await (const message of stream) {18954 * switch (message.type) {18955 * case 'taskCreated':18956 * console.log('Task created:', message.task.taskId);18957 * break;18958 * case 'taskStatus':18959 * console.log('Task status:', message.task.status);18960 * break;18961 * case 'result':18962 * console.log('Final result:', message.result);18963 * break;18964 * case 'error':18965 * console.error('Error:', message.error);18966 * break;18967 * }18968 * }18969 * ```18970 *18971 * @experimental Use `client.experimental.tasks.requestStream()` to access this method.18972 */18973 async *requestStream(request, resultSchema, options) {18974 const { task } = options ?? {};18975 if (!task) {18976 try {18977 const result = await this.request(request, resultSchema, options);18978 yield { type: "result", result };18979 } catch (error2) {18980 yield {18981 type: "error",18982 error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))18983 };18984 }18985 return;18986 }18987 let taskId;18988 try {18989 const createResult = await this.request(request, CreateTaskResultSchema, options);18990 if (createResult.task) {18991 taskId = createResult.task.taskId;18992 yield { type: "taskCreated", task: createResult.task };18993 } else {18994 throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");18995 }18996 while (true) {18997 const task2 = await this.getTask({ taskId }, options);18998 yield { type: "taskStatus", task: task2 };18999 if (isTerminal(task2.status)) {19000 if (task2.status === "completed") {19001 const result = await this.getTaskResult({ taskId }, resultSchema, options);19002 yield { type: "result", result };19003 } else if (task2.status === "failed") {19004 yield {19005 type: "error",19006 error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)19007 };19008 } else if (task2.status === "cancelled") {19009 yield {19010 type: "error",19011 error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)19012 };19013 }19014 return;19015 }19016 if (task2.status === "input_required") {19017 const result = await this.getTaskResult({ taskId }, resultSchema, options);19018 yield { type: "result", result };19019 return;19020 }19021 const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;19022 await new Promise((resolve) => setTimeout(resolve, pollInterval));19023 options?.signal?.throwIfAborted();19024 }19025 } catch (error2) {19026 yield {19027 type: "error",19028 error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))19029 };19030 }19031 }19032 /**19033 * Sends a request and waits for a response.19034 *19035 * Do not use this method to emit notifications! Use notification() instead.19036 */19037 request(request, resultSchema, options) {19038 const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};19039 return new Promise((resolve, reject) => {19040 const earlyReject = (error2) => {19041 reject(error2);19042 };19043 if (!this._transport) {19044 earlyReject(new Error("Not connected"));19045 return;19046 }19047 if (this._options?.enforceStrictCapabilities === true) {19048 try {19049 this.assertCapabilityForMethod(request.method);19050 if (task) {19051 this.assertTaskCapability(request.method);19052 }19053 } catch (e) {19054 earlyReject(e);19055 return;19056 }19057 }19058 options?.signal?.throwIfAborted();19059 const messageId = this._requestMessageId++;19060 const jsonrpcRequest = {19061 ...request,19062 jsonrpc: "2.0",19063 id: messageId19064 };19065 if (options?.onprogress) {19066 this._progressHandlers.set(messageId, options.onprogress);19067 jsonrpcRequest.params = {19068 ...request.params,19069 _meta: {19070 ...request.params?._meta || {},19071 progressToken: messageId19072 }19073 };19074 }19075 if (task) {19076 jsonrpcRequest.params = {19077 ...jsonrpcRequest.params,19078 task19079 };19080 }19081 if (relatedTask) {19082 jsonrpcRequest.params = {19083 ...jsonrpcRequest.params,19084 _meta: {19085 ...jsonrpcRequest.params?._meta || {},19086 [RELATED_TASK_META_KEY]: relatedTask19087 }19088 };19089 }19090 const cancel = (reason) => {19091 this._responseHandlers.delete(messageId);19092 this._progressHandlers.delete(messageId);19093 this._cleanupTimeout(messageId);19094 this._transport?.send({19095 jsonrpc: "2.0",19096 method: "notifications/cancelled",19097 params: {19098 requestId: messageId,19099 reason: String(reason)19100 }19101 }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`)));19102 const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));19103 reject(error2);19104 };19105 this._responseHandlers.set(messageId, (response) => {19106 if (options?.signal?.aborted) {19107 return;19108 }19109 if (response instanceof Error) {19110 return reject(response);19111 }19112 try {19113 const parseResult = safeParse2(resultSchema, response.result);19114 if (!parseResult.success) {19115 reject(parseResult.error);19116 } else {19117 resolve(parseResult.data);19118 }19119 } catch (error2) {19120 reject(error2);19121 }19122 });19123 options?.signal?.addEventListener("abort", () => {19124 cancel(options?.signal?.reason);19125 });19126 const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;19127 const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));19128 this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);19129 const relatedTaskId = relatedTask?.taskId;19130 if (relatedTaskId) {19131 const responseResolver = (response) => {19132 const handler = this._responseHandlers.get(messageId);19133 if (handler) {19134 handler(response);19135 } else {19136 this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));19137 }19138 };19139 this._requestResolvers.set(messageId, responseResolver);19140 this._enqueueTaskMessage(relatedTaskId, {19141 type: "request",19142 message: jsonrpcRequest,19143 timestamp: Date.now()19144 }).catch((error2) => {19145 this._cleanupTimeout(messageId);19146 reject(error2);19147 });19148 } else {19149 this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {19150 this._cleanupTimeout(messageId);19151 reject(error2);19152 });19153 }19154 });19155 }19156 /**19157 * Gets the current status of a task.19158 *19159 * @experimental Use `client.experimental.tasks.getTask()` to access this method.19160 */19161 async getTask(params, options) {19162 return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);19163 }19164 /**19165 * Retrieves the result of a completed task.19166 *19167 * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.19168 */19169 async getTaskResult(params, resultSchema, options) {19170 return this.request({ method: "tasks/result", params }, resultSchema, options);19171 }19172 /**19173 * Lists tasks, optionally starting from a pagination cursor.19174 *19175 * @experimental Use `client.experimental.tasks.listTasks()` to access this method.19176 */19177 async listTasks(params, options) {19178 return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);19179 }19180 /**19181 * Cancels a specific task.19182 *19183 * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.19184 */19185 async cancelTask(params, options) {19186 return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);19187 }19188 /**19189 * Emits a notification, which is a one-way message that does not expect a response.19190 */19191 async notification(notification, options) {19192 if (!this._transport) {19193 throw new Error("Not connected");19194 }19195 this.assertNotificationCapability(notification.method);19196 const relatedTaskId = options?.relatedTask?.taskId;19197 if (relatedTaskId) {19198 const jsonrpcNotification2 = {19199 ...notification,19200 jsonrpc: "2.0",19201 params: {19202 ...notification.params,19203 _meta: {19204 ...notification.params?._meta || {},19205 [RELATED_TASK_META_KEY]: options.relatedTask19206 }19207 }19208 };19209 await this._enqueueTaskMessage(relatedTaskId, {19210 type: "notification",19211 message: jsonrpcNotification2,19212 timestamp: Date.now()19213 });19214 return;19215 }19216 const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];19217 const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;19218 if (canDebounce) {19219 if (this._pendingDebouncedNotifications.has(notification.method)) {19220 return;19221 }19222 this._pendingDebouncedNotifications.add(notification.method);19223 Promise.resolve().then(() => {19224 this._pendingDebouncedNotifications.delete(notification.method);19225 if (!this._transport) {19226 return;19227 }19228 let jsonrpcNotification2 = {19229 ...notification,19230 jsonrpc: "2.0"19231 };19232 if (options?.relatedTask) {19233 jsonrpcNotification2 = {19234 ...jsonrpcNotification2,19235 params: {19236 ...jsonrpcNotification2.params,19237 _meta: {19238 ...jsonrpcNotification2.params?._meta || {},19239 [RELATED_TASK_META_KEY]: options.relatedTask19240 }19241 }19242 };19243 }19244 this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));19245 });19246 return;19247 }19248 let jsonrpcNotification = {19249 ...notification,19250 jsonrpc: "2.0"19251 };19252 if (options?.relatedTask) {19253 jsonrpcNotification = {19254 ...jsonrpcNotification,19255 params: {19256 ...jsonrpcNotification.params,19257 _meta: {19258 ...jsonrpcNotification.params?._meta || {},19259 [RELATED_TASK_META_KEY]: options.relatedTask19260 }19261 }19262 };19263 }19264 await this._transport.send(jsonrpcNotification, options);19265 }19266 /**19267 * Registers a handler to invoke when this protocol object receives a request with the given method.19268 *19269 * Note that this will replace any previous request handler for the same method.19270 */19271 setRequestHandler(requestSchema, handler) {19272 const method = getMethodLiteral(requestSchema);19273 this.assertRequestHandlerCapability(method);19274 this._requestHandlers.set(method, (request, extra) => {19275 const parsed = parseWithCompat(requestSchema, request);19276 return Promise.resolve(handler(parsed, extra));19277 });19278 }19279 /**19280 * Removes the request handler for the given method.19281 */19282 removeRequestHandler(method) {19283 this._requestHandlers.delete(method);19284 }19285 /**19286 * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.19287 */19288 assertCanSetRequestHandler(method) {19289 if (this._requestHandlers.has(method)) {19290 throw new Error(`A request handler for ${method} already exists, which would be overridden`);19291 }19292 }19293 /**19294 * Registers a handler to invoke when this protocol object receives a notification with the given method.19295 *19296 * Note that this will replace any previous notification handler for the same method.19297 */19298 setNotificationHandler(notificationSchema, handler) {19299 const method = getMethodLiteral(notificationSchema);19300 this._notificationHandlers.set(method, (notification) => {19301 const parsed = parseWithCompat(notificationSchema, notification);19302 return Promise.resolve(handler(parsed));19303 });19304 }19305 /**19306 * Removes the notification handler for the given method.19307 */19308 removeNotificationHandler(method) {19309 this._notificationHandlers.delete(method);19310 }19311 /**19312 * Cleans up the progress handler associated with a task.19313 * This should be called when a task reaches a terminal status.19314 */19315 _cleanupTaskProgressHandler(taskId) {19316 const progressToken = this._taskProgressTokens.get(taskId);19317 if (progressToken !== void 0) {19318 this._progressHandlers.delete(progressToken);19319 this._taskProgressTokens.delete(taskId);19320 }19321 }19322 /**19323 * Enqueues a task-related message for side-channel delivery via tasks/result.19324 * @param taskId The task ID to associate the message with19325 * @param message The message to enqueue19326 * @param sessionId Optional session ID for binding the operation to a specific session19327 * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)19328 *19329 * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle19330 * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer19331 * simply propagates the error.19332 */19333 async _enqueueTaskMessage(taskId, message, sessionId) {19334 if (!this._taskStore || !this._taskMessageQueue) {19335 throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");19336 }19337 const maxQueueSize = this._options?.maxTaskQueueSize;19338 await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);19339 }19340 /**19341 * Clears the message queue for a task and rejects any pending request resolvers.19342 * @param taskId The task ID whose queue should be cleared19343 * @param sessionId Optional session ID for binding the operation to a specific session19344 */19345 async _clearTaskQueue(taskId, sessionId) {19346 if (this._taskMessageQueue) {19347 const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);19348 for (const message of messages) {19349 if (message.type === "request" && isJSONRPCRequest(message.message)) {19350 const requestId = message.message.id;19351 const resolver = this._requestResolvers.get(requestId);19352 if (resolver) {19353 resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));19354 this._requestResolvers.delete(requestId);19355 } else {19356 this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));19357 }19358 }19359 }19360 }19361 }19362 /**19363 * Waits for a task update (new messages or status change) with abort signal support.19364 * Uses polling to check for updates at the task's configured poll interval.19365 * @param taskId The task ID to wait for19366 * @param signal Abort signal to cancel the wait19367 * @returns Promise that resolves when an update occurs or rejects if aborted19368 */19369 async _waitForTaskUpdate(taskId, signal) {19370 let interval = this._options?.defaultTaskPollInterval ?? 1e3;19371 try {19372 const task = await this._taskStore?.getTask(taskId);19373 if (task?.pollInterval) {19374 interval = task.pollInterval;19375 }19376 } catch {19377 }19378 return new Promise((resolve, reject) => {19379 if (signal.aborted) {19380 reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));19381 return;19382 }19383 const timeoutId = setTimeout(resolve, interval);19384 signal.addEventListener("abort", () => {19385 clearTimeout(timeoutId);19386 reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));19387 }, { once: true });19388 });19389 }19390 requestTaskStore(request, sessionId) {19391 const taskStore = this._taskStore;19392 if (!taskStore) {19393 throw new Error("No task store configured");19394 }19395 return {19396 createTask: async (taskParams) => {19397 if (!request) {19398 throw new Error("No request provided");19399 }19400 return await taskStore.createTask(taskParams, request.id, {19401 method: request.method,19402 params: request.params19403 }, sessionId);19404 },19405 getTask: async (taskId) => {19406 const task = await taskStore.getTask(taskId, sessionId);19407 if (!task) {19408 throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");19409 }19410 return task;19411 },19412 storeTaskResult: async (taskId, status, result) => {19413 await taskStore.storeTaskResult(taskId, status, result, sessionId);19414 const task = await taskStore.getTask(taskId, sessionId);19415 if (task) {19416 const notification = TaskStatusNotificationSchema.parse({19417 method: "notifications/tasks/status",19418 params: task19419 });19420 await this.notification(notification);19421 if (isTerminal(task.status)) {19422 this._cleanupTaskProgressHandler(taskId);19423 }19424 }19425 },19426 getTaskResult: (taskId) => {19427 return taskStore.getTaskResult(taskId, sessionId);19428 },19429 updateTaskStatus: async (taskId, status, statusMessage) => {19430 const task = await taskStore.getTask(taskId, sessionId);19431 if (!task) {19432 throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);19433 }19434 if (isTerminal(task.status)) {19435 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.`);19436 }19437 await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);19438 const updatedTask = await taskStore.getTask(taskId, sessionId);19439 if (updatedTask) {19440 const notification = TaskStatusNotificationSchema.parse({19441 method: "notifications/tasks/status",19442 params: updatedTask19443 });19444 await this.notification(notification);19445 if (isTerminal(updatedTask.status)) {19446 this._cleanupTaskProgressHandler(taskId);19447 }19448 }19449 },19450 listTasks: (cursor) => {19451 return taskStore.listTasks(cursor, sessionId);19452 }19453 };19454 }19455};19456function isPlainObject2(value) {19457 return value !== null && typeof value === "object" && !Array.isArray(value);19458}19459function mergeCapabilities(base, additional) {19460 const result = { ...base };19461 for (const key in additional) {19462 const k = key;19463 const addValue = additional[k];19464 if (addValue === void 0)19465 continue;19466 const baseValue = result[k];19467 if (isPlainObject2(baseValue) && isPlainObject2(addValue)) {19468 result[k] = { ...baseValue, ...addValue };19469 } else {19470 result[k] = addValue;19471 }19472 }19473 return result;19474}1947519476// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js19477var import_ajv = __toESM(require_ajv(), 1);19478var import_ajv_formats = __toESM(require_dist(), 1);19479function createDefaultAjvInstance() {19480 const ajv = new import_ajv.default({19481 strict: false,19482 validateFormats: true,19483 validateSchema: false,19484 allErrors: true19485 });19486 const addFormats = import_ajv_formats.default;19487 addFormats(ajv);19488 return ajv;19489}19490var AjvJsonSchemaValidator = class {19491 /**19492 * Create an AJV validator19493 *19494 * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.19495 *19496 * @example19497 * ```typescript19498 * // Use default configuration (recommended for most cases)19499 * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';19500 * const validator = new AjvJsonSchemaValidator();19501 *19502 * // Or provide custom AJV instance for advanced configuration19503 * import { Ajv } from 'ajv';19504 * import addFormats from 'ajv-formats';19505 *19506 * const ajv = new Ajv({ validateFormats: true });19507 * addFormats(ajv);19508 * const validator = new AjvJsonSchemaValidator(ajv);19509 * ```19510 */19511 constructor(ajv) {19512 this._ajv = ajv ?? createDefaultAjvInstance();19513 }19514 /**19515 * Create a validator for the given JSON Schema19516 *19517 * The validator is compiled once and can be reused multiple times.19518 * If the schema has an $id, it will be cached by AJV automatically.19519 *19520 * @param schema - Standard JSON Schema object19521 * @returns A validator function that validates input data19522 */19523 getValidator(schema) {19524 const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);19525 return (input) => {19526 const valid = ajvValidator(input);19527 if (valid) {19528 return {19529 valid: true,19530 data: input,19531 errorMessage: void 019532 };19533 } else {19534 return {19535 valid: false,19536 data: void 0,19537 errorMessage: this._ajv.errorsText(ajvValidator.errors)19538 };19539 }19540 };19541 }19542};1954319544// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js19545var ExperimentalServerTasks = class {19546 constructor(_server) {19547 this._server = _server;19548 }19549 /**19550 * Sends a request and returns an AsyncGenerator that yields response messages.19551 * The generator is guaranteed to end with either a 'result' or 'error' message.19552 *19553 * This method provides streaming access to request processing, allowing you to19554 * observe intermediate task status updates for task-augmented requests.19555 *19556 * @param request - The request to send19557 * @param resultSchema - Zod schema for validating the result19558 * @param options - Optional request options (timeout, signal, task creation params, etc.)19559 * @returns AsyncGenerator that yields ResponseMessage objects19560 *19561 * @experimental19562 */19563 requestStream(request, resultSchema, options) {19564 return this._server.requestStream(request, resultSchema, options);19565 }19566 /**19567 * Sends a sampling request and returns an AsyncGenerator that yields response messages.19568 * The generator is guaranteed to end with either a 'result' or 'error' message.19569 *19570 * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages19571 * before the final result.19572 *19573 * @example19574 * ```typescript19575 * const stream = server.experimental.tasks.createMessageStream({19576 * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],19577 * maxTokens: 10019578 * }, {19579 * onprogress: (progress) => {19580 * // Handle streaming tokens via progress notifications19581 * console.log('Progress:', progress.message);19582 * }19583 * });19584 *19585 * for await (const message of stream) {19586 * switch (message.type) {19587 * case 'taskCreated':19588 * console.log('Task created:', message.task.taskId);19589 * break;19590 * case 'taskStatus':19591 * console.log('Task status:', message.task.status);19592 * break;19593 * case 'result':19594 * console.log('Final result:', message.result);19595 * break;19596 * case 'error':19597 * console.error('Error:', message.error);19598 * break;19599 * }19600 * }19601 * ```19602 *19603 * @param params - The sampling request parameters19604 * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)19605 * @returns AsyncGenerator that yields ResponseMessage objects19606 *19607 * @experimental19608 */19609 createMessageStream(params, options) {19610 const clientCapabilities = this._server.getClientCapabilities();19611 if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {19612 throw new Error("Client does not support sampling tools capability.");19613 }19614 if (params.messages.length > 0) {19615 const lastMessage = params.messages[params.messages.length - 1];19616 const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];19617 const hasToolResults = lastContent.some((c) => c.type === "tool_result");19618 const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;19619 const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];19620 const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");19621 if (hasToolResults) {19622 if (lastContent.some((c) => c.type !== "tool_result")) {19623 throw new Error("The last message must contain only tool_result content if any is present");19624 }19625 if (!hasPreviousToolUse) {19626 throw new Error("tool_result blocks are not matching any tool_use from the previous message");19627 }19628 }19629 if (hasPreviousToolUse) {19630 const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));19631 const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));19632 if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {19633 throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");19634 }19635 }19636 }19637 return this.requestStream({19638 method: "sampling/createMessage",19639 params19640 }, CreateMessageResultSchema, options);19641 }19642 /**19643 * Sends an elicitation request and returns an AsyncGenerator that yields response messages.19644 * The generator is guaranteed to end with either a 'result' or 'error' message.19645 *19646 * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'19647 * and 'taskStatus' messages before the final result.19648 *19649 * @example19650 * ```typescript19651 * const stream = server.experimental.tasks.elicitInputStream({19652 * mode: 'url',19653 * message: 'Please authenticate',19654 * elicitationId: 'auth-123',19655 * url: 'https://example.com/auth'19656 * }, {19657 * task: { ttl: 300000 } // Task-augmented for long-running auth flow19658 * });19659 *19660 * for await (const message of stream) {19661 * switch (message.type) {19662 * case 'taskCreated':19663 * console.log('Task created:', message.task.taskId);19664 * break;19665 * case 'taskStatus':19666 * console.log('Task status:', message.task.status);19667 * break;19668 * case 'result':19669 * console.log('User action:', message.result.action);19670 * break;19671 * case 'error':19672 * console.error('Error:', message.error);19673 * break;19674 * }19675 * }19676 * ```19677 *19678 * @param params - The elicitation request parameters19679 * @param options - Optional request options (timeout, signal, task creation params, etc.)19680 * @returns AsyncGenerator that yields ResponseMessage objects19681 *19682 * @experimental19683 */19684 elicitInputStream(params, options) {19685 const clientCapabilities = this._server.getClientCapabilities();19686 const mode = params.mode ?? "form";19687 switch (mode) {19688 case "url": {19689 if (!clientCapabilities?.elicitation?.url) {19690 throw new Error("Client does not support url elicitation.");19691 }19692 break;19693 }19694 case "form": {19695 if (!clientCapabilities?.elicitation?.form) {19696 throw new Error("Client does not support form elicitation.");19697 }19698 break;19699 }19700 }19701 const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params;19702 return this.requestStream({19703 method: "elicitation/create",19704 params: normalizedParams19705 }, ElicitResultSchema, options);19706 }19707 /**19708 * Gets the current status of a task.19709 *19710 * @param taskId - The task identifier19711 * @param options - Optional request options19712 * @returns The task status19713 *19714 * @experimental19715 */19716 async getTask(taskId, options) {19717 return this._server.getTask({ taskId }, options);19718 }19719 /**19720 * Retrieves the result of a completed task.19721 *19722 * @param taskId - The task identifier19723 * @param resultSchema - Zod schema for validating the result19724 * @param options - Optional request options19725 * @returns The task result19726 *19727 * @experimental19728 */19729 async getTaskResult(taskId, resultSchema, options) {19730 return this._server.getTaskResult({ taskId }, resultSchema, options);19731 }19732 /**19733 * Lists tasks with optional pagination.19734 *19735 * @param cursor - Optional pagination cursor19736 * @param options - Optional request options19737 * @returns List of tasks with optional next cursor19738 *19739 * @experimental19740 */19741 async listTasks(cursor, options) {19742 return this._server.listTasks(cursor ? { cursor } : void 0, options);19743 }19744 /**19745 * Cancels a running task.19746 *19747 * @param taskId - The task identifier19748 * @param options - Optional request options19749 *19750 * @experimental19751 */19752 async cancelTask(taskId, options) {19753 return this._server.cancelTask({ taskId }, options);19754 }19755};1975619757// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js19758function assertToolsCallTaskCapability(requests, method, entityName) {19759 if (!requests) {19760 throw new Error(`${entityName} does not support task creation (required for ${method})`);19761 }19762 switch (method) {19763 case "tools/call":19764 if (!requests.tools?.call) {19765 throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);19766 }19767 break;19768 default:19769 break;19770 }19771}19772function assertClientRequestTaskCapability(requests, method, entityName) {19773 if (!requests) {19774 throw new Error(`${entityName} does not support task creation (required for ${method})`);19775 }19776 switch (method) {19777 case "sampling/createMessage":19778 if (!requests.sampling?.createMessage) {19779 throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);19780 }19781 break;19782 case "elicitation/create":19783 if (!requests.elicitation?.create) {19784 throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);19785 }19786 break;19787 default:19788 break;19789 }19790}1979119792// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js19793var Server = class extends Protocol {19794 /**19795 * Initializes this server with the given name and version information.19796 */19797 constructor(_serverInfo, options) {19798 super(options);19799 this._serverInfo = _serverInfo;19800 this._loggingLevels = /* @__PURE__ */ new Map();19801 this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));19802 this.isMessageIgnored = (level, sessionId) => {19803 const currentLevel = this._loggingLevels.get(sessionId);19804 return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;19805 };19806 this._capabilities = options?.capabilities ?? {};19807 this._instructions = options?.instructions;19808 this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();19809 this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));19810 this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());19811 if (this._capabilities.logging) {19812 this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {19813 const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;19814 const { level } = request.params;19815 const parseResult = LoggingLevelSchema.safeParse(level);19816 if (parseResult.success) {19817 this._loggingLevels.set(transportSessionId, parseResult.data);19818 }19819 return {};19820 });19821 }19822 }19823 /**19824 * Access experimental features.19825 *19826 * WARNING: These APIs are experimental and may change without notice.19827 *19828 * @experimental19829 */19830 get experimental() {19831 if (!this._experimental) {19832 this._experimental = {19833 tasks: new ExperimentalServerTasks(this)19834 };19835 }19836 return this._experimental;19837 }19838 /**19839 * Registers new capabilities. This can only be called before connecting to a transport.19840 *19841 * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).19842 */19843 registerCapabilities(capabilities) {19844 if (this.transport) {19845 throw new Error("Cannot register capabilities after connecting to transport");19846 }19847 this._capabilities = mergeCapabilities(this._capabilities, capabilities);19848 }19849 /**19850 * Override request handler registration to enforce server-side validation for tools/call.19851 */19852 setRequestHandler(requestSchema, handler) {19853 const shape = getObjectShape(requestSchema);19854 const methodSchema = shape?.method;19855 if (!methodSchema) {19856 throw new Error("Schema is missing a method literal");19857 }19858 const methodValue = getLiteralValue(methodSchema);19859 if (typeof methodValue !== "string") {19860 throw new Error("Schema method literal must be a string");19861 }19862 const method = methodValue;19863 if (method === "tools/call") {19864 const wrappedHandler = async (request, extra) => {19865 const validatedRequest = safeParse2(CallToolRequestSchema, request);19866 if (!validatedRequest.success) {19867 const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);19868 throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);19869 }19870 const { params } = validatedRequest.data;19871 const result = await Promise.resolve(handler(request, extra));19872 if (params.task) {19873 const taskValidationResult = safeParse2(CreateTaskResultSchema, result);19874 if (!taskValidationResult.success) {19875 const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);19876 throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);19877 }19878 return taskValidationResult.data;19879 }19880 const validationResult = safeParse2(CallToolResultSchema, result);19881 if (!validationResult.success) {19882 const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);19883 throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);19884 }19885 return validationResult.data;19886 };19887 return super.setRequestHandler(requestSchema, wrappedHandler);19888 }19889 return super.setRequestHandler(requestSchema, handler);19890 }19891 assertCapabilityForMethod(method) {19892 switch (method) {19893 case "sampling/createMessage":19894 if (!this._clientCapabilities?.sampling) {19895 throw new Error(`Client does not support sampling (required for ${method})`);19896 }19897 break;19898 case "elicitation/create":19899 if (!this._clientCapabilities?.elicitation) {19900 throw new Error(`Client does not support elicitation (required for ${method})`);19901 }19902 break;19903 case "roots/list":19904 if (!this._clientCapabilities?.roots) {19905 throw new Error(`Client does not support listing roots (required for ${method})`);19906 }19907 break;19908 case "ping":19909 break;19910 }19911 }19912 assertNotificationCapability(method) {19913 switch (method) {19914 case "notifications/message":19915 if (!this._capabilities.logging) {19916 throw new Error(`Server does not support logging (required for ${method})`);19917 }19918 break;19919 case "notifications/resources/updated":19920 case "notifications/resources/list_changed":19921 if (!this._capabilities.resources) {19922 throw new Error(`Server does not support notifying about resources (required for ${method})`);19923 }19924 break;19925 case "notifications/tools/list_changed":19926 if (!this._capabilities.tools) {19927 throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);19928 }19929 break;19930 case "notifications/prompts/list_changed":19931 if (!this._capabilities.prompts) {19932 throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);19933 }19934 break;19935 case "notifications/elicitation/complete":19936 if (!this._clientCapabilities?.elicitation?.url) {19937 throw new Error(`Client does not support URL elicitation (required for ${method})`);19938 }19939 break;19940 case "notifications/cancelled":19941 break;19942 case "notifications/progress":19943 break;19944 }19945 }19946 assertRequestHandlerCapability(method) {19947 if (!this._capabilities) {19948 return;19949 }19950 switch (method) {19951 case "completion/complete":19952 if (!this._capabilities.completions) {19953 throw new Error(`Server does not support completions (required for ${method})`);19954 }19955 break;19956 case "logging/setLevel":19957 if (!this._capabilities.logging) {19958 throw new Error(`Server does not support logging (required for ${method})`);19959 }19960 break;19961 case "prompts/get":19962 case "prompts/list":19963 if (!this._capabilities.prompts) {19964 throw new Error(`Server does not support prompts (required for ${method})`);19965 }19966 break;19967 case "resources/list":19968 case "resources/templates/list":19969 case "resources/read":19970 if (!this._capabilities.resources) {19971 throw new Error(`Server does not support resources (required for ${method})`);19972 }19973 break;19974 case "tools/call":19975 case "tools/list":19976 if (!this._capabilities.tools) {19977 throw new Error(`Server does not support tools (required for ${method})`);19978 }19979 break;19980 case "tasks/get":19981 case "tasks/list":19982 case "tasks/result":19983 case "tasks/cancel":19984 if (!this._capabilities.tasks) {19985 throw new Error(`Server does not support tasks capability (required for ${method})`);19986 }19987 break;19988 case "ping":19989 case "initialize":19990 break;19991 }19992 }19993 assertTaskCapability(method) {19994 assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");19995 }19996 assertTaskHandlerCapability(method) {19997 if (!this._capabilities) {19998 return;19999 }20000 assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");20001 }20002 async _oninitialize(request) {20003 const requestedVersion = request.params.protocolVersion;20004 this._clientCapabilities = request.params.capabilities;20005 this._clientVersion = request.params.clientInfo;20006 const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;20007 return {20008 protocolVersion,20009 capabilities: this.getCapabilities(),20010 serverInfo: this._serverInfo,20011 ...this._instructions && { instructions: this._instructions }20012 };20013 }20014 /**20015 * After initialization has completed, this will be populated with the client's reported capabilities.20016 */20017 getClientCapabilities() {20018 return this._clientCapabilities;20019 }20020 /**20021 * After initialization has completed, this will be populated with information about the client's name and version.20022 */20023 getClientVersion() {20024 return this._clientVersion;20025 }20026 getCapabilities() {20027 return this._capabilities;20028 }20029 async ping() {20030 return this.request({ method: "ping" }, EmptyResultSchema);20031 }20032 // Implementation20033 async createMessage(params, options) {20034 if (params.tools || params.toolChoice) {20035 if (!this._clientCapabilities?.sampling?.tools) {20036 throw new Error("Client does not support sampling tools capability.");20037 }20038 }20039 if (params.messages.length > 0) {20040 const lastMessage = params.messages[params.messages.length - 1];20041 const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];20042 const hasToolResults = lastContent.some((c) => c.type === "tool_result");20043 const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;20044 const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];20045 const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");20046 if (hasToolResults) {20047 if (lastContent.some((c) => c.type !== "tool_result")) {20048 throw new Error("The last message must contain only tool_result content if any is present");20049 }20050 if (!hasPreviousToolUse) {20051 throw new Error("tool_result blocks are not matching any tool_use from the previous message");20052 }20053 }20054 if (hasPreviousToolUse) {20055 const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));20056 const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));20057 if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {20058 throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");20059 }20060 }20061 }20062 if (params.tools) {20063 return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options);20064 }20065 return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);20066 }20067 /**20068 * Creates an elicitation request for the given parameters.20069 * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.20070 * @param params The parameters for the elicitation request.20071 * @param options Optional request options.20072 * @returns The result of the elicitation request.20073 */20074 async elicitInput(params, options) {20075 const mode = params.mode ?? "form";20076 switch (mode) {20077 case "url": {20078 if (!this._clientCapabilities?.elicitation?.url) {20079 throw new Error("Client does not support url elicitation.");20080 }20081 const urlParams = params;20082 return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options);20083 }20084 case "form": {20085 if (!this._clientCapabilities?.elicitation?.form) {20086 throw new Error("Client does not support form elicitation.");20087 }20088 const formParams = params.mode === "form" ? params : { ...params, mode: "form" };20089 const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options);20090 if (result.action === "accept" && result.content && formParams.requestedSchema) {20091 try {20092 const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);20093 const validationResult = validator(result.content);20094 if (!validationResult.valid) {20095 throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);20096 }20097 } catch (error2) {20098 if (error2 instanceof McpError) {20099 throw error2;20100 }20101 throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`);20102 }20103 }20104 return result;20105 }20106 }20107 }20108 /**20109 * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`20110 * notification for the specified elicitation ID.20111 *20112 * @param elicitationId The ID of the elicitation to mark as complete.20113 * @param options Optional notification options. Useful when the completion notification should be related to a prior request.20114 * @returns A function that emits the completion notification when awaited.20115 */20116 createElicitationCompletionNotifier(elicitationId, options) {20117 if (!this._clientCapabilities?.elicitation?.url) {20118 throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");20119 }20120 return () => this.notification({20121 method: "notifications/elicitation/complete",20122 params: {20123 elicitationId20124 }20125 }, options);20126 }20127 async listRoots(params, options) {20128 return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);20129 }20130 /**20131 * Sends a logging message to the client, if connected.20132 * Note: You only need to send the parameters object, not the entire JSON RPC message20133 * @see LoggingMessageNotification20134 * @param params20135 * @param sessionId optional for stateless and backward compatibility20136 */20137 async sendLoggingMessage(params, sessionId) {20138 if (this._capabilities.logging) {20139 if (!this.isMessageIgnored(params.level, sessionId)) {20140 return this.notification({ method: "notifications/message", params });20141 }20142 }20143 }20144 async sendResourceUpdated(params) {20145 return this.notification({20146 method: "notifications/resources/updated",20147 params20148 });20149 }20150 async sendResourceListChanged() {20151 return this.notification({20152 method: "notifications/resources/list_changed"20153 });20154 }20155 async sendToolListChanged() {20156 return this.notification({ method: "notifications/tools/list_changed" });20157 }20158 async sendPromptListChanged() {20159 return this.notification({ method: "notifications/prompts/list_changed" });20160 }20161};2016220163// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js20164var COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");20165function isCompletable(schema) {20166 return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;20167}20168function getCompleter(schema) {20169 const meta = schema[COMPLETABLE_SYMBOL];20170 return meta?.complete;20171}20172var McpZodTypeKind;20173(function(McpZodTypeKind2) {20174 McpZodTypeKind2["Completable"] = "McpCompletable";20175})(McpZodTypeKind || (McpZodTypeKind = {}));2017620177// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js20178var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;20179function validateToolName(name) {20180 const warnings = [];20181 if (name.length === 0) {20182 return {20183 isValid: false,20184 warnings: ["Tool name cannot be empty"]20185 };20186 }20187 if (name.length > 128) {20188 return {20189 isValid: false,20190 warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]20191 };20192 }20193 if (name.includes(" ")) {20194 warnings.push("Tool name contains spaces, which may cause parsing issues");20195 }20196 if (name.includes(",")) {20197 warnings.push("Tool name contains commas, which may cause parsing issues");20198 }20199 if (name.startsWith("-") || name.endsWith("-")) {20200 warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");20201 }20202 if (name.startsWith(".") || name.endsWith(".")) {20203 warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");20204 }20205 if (!TOOL_NAME_REGEX.test(name)) {20206 const invalidChars = name.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);20207 warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");20208 return {20209 isValid: false,20210 warnings20211 };20212 }20213 return {20214 isValid: true,20215 warnings20216 };20217}20218function issueToolNameWarning(name, warnings) {20219 if (warnings.length > 0) {20220 console.warn(`Tool name validation warning for "${name}":`);20221 for (const warning of warnings) {20222 console.warn(` - ${warning}`);20223 }20224 console.warn("Tool registration will proceed, but this may cause compatibility issues.");20225 console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");20226 console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");20227 }20228}20229function validateAndWarnToolName(name) {20230 const result = validateToolName(name);20231 issueToolNameWarning(name, result.warnings);20232 return result.isValid;20233}2023420235// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js20236var ExperimentalMcpServerTasks = class {20237 constructor(_mcpServer) {20238 this._mcpServer = _mcpServer;20239 }20240 registerToolTask(name, config2, handler) {20241 const execution = { taskSupport: "required", ...config2.execution };20242 if (execution.taskSupport === "forbidden") {20243 throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);20244 }20245 const mcpServerInternal = this._mcpServer;20246 return mcpServerInternal._createRegisteredTool(name, config2.title, config2.description, config2.inputSchema, config2.outputSchema, config2.annotations, execution, config2._meta, handler);20247 }20248};2024920250// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js20251var McpServer = class {20252 constructor(serverInfo, options) {20253 this._registeredResources = {};20254 this._registeredResourceTemplates = {};20255 this._registeredTools = {};20256 this._registeredPrompts = {};20257 this._toolHandlersInitialized = false;20258 this._completionHandlerInitialized = false;20259 this._resourceHandlersInitialized = false;20260 this._promptHandlersInitialized = false;20261 this.server = new Server(serverInfo, options);20262 }20263 /**20264 * Access experimental features.20265 *20266 * WARNING: These APIs are experimental and may change without notice.20267 *20268 * @experimental20269 */20270 get experimental() {20271 if (!this._experimental) {20272 this._experimental = {20273 tasks: new ExperimentalMcpServerTasks(this)20274 };20275 }20276 return this._experimental;20277 }20278 /**20279 * Attaches to the given transport, starts it, and starts listening for messages.20280 *20281 * The `server` 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.20282 */20283 async connect(transport) {20284 return await this.server.connect(transport);20285 }20286 /**20287 * Closes the connection.20288 */20289 async close() {20290 await this.server.close();20291 }20292 setToolRequestHandlers() {20293 if (this._toolHandlersInitialized) {20294 return;20295 }20296 this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));20297 this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));20298 this.server.registerCapabilities({20299 tools: {20300 listChanged: true20301 }20302 });20303 this.server.setRequestHandler(ListToolsRequestSchema, () => ({20304 tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {20305 const toolDefinition = {20306 name,20307 title: tool.title,20308 description: tool.description,20309 inputSchema: (() => {20310 const obj = normalizeObjectSchema(tool.inputSchema);20311 return obj ? toJsonSchemaCompat(obj, {20312 strictUnions: true,20313 pipeStrategy: "input"20314 }) : EMPTY_OBJECT_JSON_SCHEMA;20315 })(),20316 annotations: tool.annotations,20317 execution: tool.execution,20318 _meta: tool._meta20319 };20320 if (tool.outputSchema) {20321 const obj = normalizeObjectSchema(tool.outputSchema);20322 if (obj) {20323 toolDefinition.outputSchema = toJsonSchemaCompat(obj, {20324 strictUnions: true,20325 pipeStrategy: "output"20326 });20327 }20328 }20329 return toolDefinition;20330 })20331 }));20332 this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {20333 try {20334 const tool = this._registeredTools[request.params.name];20335 if (!tool) {20336 throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);20337 }20338 if (!tool.enabled) {20339 throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);20340 }20341 const isTaskRequest = !!request.params.task;20342 const taskSupport = tool.execution?.taskSupport;20343 const isTaskHandler = "createTask" in tool.handler;20344 if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {20345 throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);20346 }20347 if (taskSupport === "required" && !isTaskRequest) {20348 throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);20349 }20350 if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) {20351 return await this.handleAutomaticTaskPolling(tool, request, extra);20352 }20353 const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);20354 const result = await this.executeToolHandler(tool, args, extra);20355 if (isTaskRequest) {20356 return result;20357 }20358 await this.validateToolOutput(tool, result, request.params.name);20359 return result;20360 } catch (error2) {20361 if (error2 instanceof McpError) {20362 if (error2.code === ErrorCode.UrlElicitationRequired) {20363 throw error2;20364 }20365 }20366 return this.createToolError(error2 instanceof Error ? error2.message : String(error2));20367 }20368 });20369 this._toolHandlersInitialized = true;20370 }20371 /**20372 * Creates a tool error result.20373 *20374 * @param errorMessage - The error message.20375 * @returns The tool error result.20376 */20377 createToolError(errorMessage) {20378 return {20379 content: [20380 {20381 type: "text",20382 text: errorMessage20383 }20384 ],20385 isError: true20386 };20387 }20388 /**20389 * Validates tool input arguments against the tool's input schema.20390 */20391 async validateToolInput(tool, args, toolName) {20392 if (!tool.inputSchema) {20393 return void 0;20394 }20395 const inputObj = normalizeObjectSchema(tool.inputSchema);20396 const schemaToParse = inputObj ?? tool.inputSchema;20397 const parseResult = await safeParseAsync2(schemaToParse, args);20398 if (!parseResult.success) {20399 const error2 = "error" in parseResult ? parseResult.error : "Unknown error";20400 const errorMessage = getParseErrorMessage(error2);20401 throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);20402 }20403 return parseResult.data;20404 }20405 /**20406 * Validates tool output against the tool's output schema.20407 */20408 async validateToolOutput(tool, result, toolName) {20409 if (!tool.outputSchema) {20410 return;20411 }20412 if (!("content" in result)) {20413 return;20414 }20415 if (result.isError) {20416 return;20417 }20418 if (!result.structuredContent) {20419 throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);20420 }20421 const outputObj = normalizeObjectSchema(tool.outputSchema);20422 const parseResult = await safeParseAsync2(outputObj, result.structuredContent);20423 if (!parseResult.success) {20424 const error2 = "error" in parseResult ? parseResult.error : "Unknown error";20425 const errorMessage = getParseErrorMessage(error2);20426 throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);20427 }20428 }20429 /**20430 * Executes a tool handler (either regular or task-based).20431 */20432 async executeToolHandler(tool, args, extra) {20433 const handler = tool.handler;20434 const isTaskHandler = "createTask" in handler;20435 if (isTaskHandler) {20436 if (!extra.taskStore) {20437 throw new Error("No task store provided.");20438 }20439 const taskExtra = { ...extra, taskStore: extra.taskStore };20440 if (tool.inputSchema) {20441 const typedHandler = handler;20442 return await Promise.resolve(typedHandler.createTask(args, taskExtra));20443 } else {20444 const typedHandler = handler;20445 return await Promise.resolve(typedHandler.createTask(taskExtra));20446 }20447 }20448 if (tool.inputSchema) {20449 const typedHandler = handler;20450 return await Promise.resolve(typedHandler(args, extra));20451 } else {20452 const typedHandler = handler;20453 return await Promise.resolve(typedHandler(extra));20454 }20455 }20456 /**20457 * Handles automatic task polling for tools with taskSupport 'optional'.20458 */20459 async handleAutomaticTaskPolling(tool, request, extra) {20460 if (!extra.taskStore) {20461 throw new Error("No task store provided for task-capable tool.");20462 }20463 const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);20464 const handler = tool.handler;20465 const taskExtra = { ...extra, taskStore: extra.taskStore };20466 const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : (20467 // eslint-disable-next-line @typescript-eslint/no-explicit-any20468 await Promise.resolve(handler.createTask(taskExtra))20469 );20470 const taskId = createTaskResult.task.taskId;20471 let task = createTaskResult.task;20472 const pollInterval = task.pollInterval ?? 5e3;20473 while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {20474 await new Promise((resolve) => setTimeout(resolve, pollInterval));20475 const updatedTask = await extra.taskStore.getTask(taskId);20476 if (!updatedTask) {20477 throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);20478 }20479 task = updatedTask;20480 }20481 return await extra.taskStore.getTaskResult(taskId);20482 }20483 setCompletionRequestHandler() {20484 if (this._completionHandlerInitialized) {20485 return;20486 }20487 this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));20488 this.server.registerCapabilities({20489 completions: {}20490 });20491 this.server.setRequestHandler(CompleteRequestSchema, async (request) => {20492 switch (request.params.ref.type) {20493 case "ref/prompt":20494 assertCompleteRequestPrompt(request);20495 return this.handlePromptCompletion(request, request.params.ref);20496 case "ref/resource":20497 assertCompleteRequestResourceTemplate(request);20498 return this.handleResourceCompletion(request, request.params.ref);20499 default:20500 throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);20501 }20502 });20503 this._completionHandlerInitialized = true;20504 }20505 async handlePromptCompletion(request, ref) {20506 const prompt = this._registeredPrompts[ref.name];20507 if (!prompt) {20508 throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);20509 }20510 if (!prompt.enabled) {20511 throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);20512 }20513 if (!prompt.argsSchema) {20514 return EMPTY_COMPLETION_RESULT;20515 }20516 const promptShape = getObjectShape(prompt.argsSchema);20517 const field = promptShape?.[request.params.argument.name];20518 if (!isCompletable(field)) {20519 return EMPTY_COMPLETION_RESULT;20520 }20521 const completer = getCompleter(field);20522 if (!completer) {20523 return EMPTY_COMPLETION_RESULT;20524 }20525 const suggestions = await completer(request.params.argument.value, request.params.context);20526 return createCompletionResult(suggestions);20527 }20528 async handleResourceCompletion(request, ref) {20529 const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);20530 if (!template) {20531 if (this._registeredResources[ref.uri]) {20532 return EMPTY_COMPLETION_RESULT;20533 }20534 throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);20535 }20536 const completer = template.resourceTemplate.completeCallback(request.params.argument.name);20537 if (!completer) {20538 return EMPTY_COMPLETION_RESULT;20539 }20540 const suggestions = await completer(request.params.argument.value, request.params.context);20541 return createCompletionResult(suggestions);20542 }20543 setResourceRequestHandlers() {20544 if (this._resourceHandlersInitialized) {20545 return;20546 }20547 this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));20548 this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));20549 this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));20550 this.server.registerCapabilities({20551 resources: {20552 listChanged: true20553 }20554 });20555 this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {20556 const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({20557 uri,20558 name: resource.name,20559 ...resource.metadata20560 }));20561 const templateResources = [];20562 for (const template of Object.values(this._registeredResourceTemplates)) {20563 if (!template.resourceTemplate.listCallback) {20564 continue;20565 }20566 const result = await template.resourceTemplate.listCallback(extra);20567 for (const resource of result.resources) {20568 templateResources.push({20569 ...template.metadata,20570 // the defined resource metadata should override the template metadata if present20571 ...resource20572 });20573 }20574 }20575 return { resources: [...resources, ...templateResources] };20576 });20577 this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {20578 const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({20579 name,20580 uriTemplate: template.resourceTemplate.uriTemplate.toString(),20581 ...template.metadata20582 }));20583 return { resourceTemplates };20584 });20585 this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {20586 const uri = new URL(request.params.uri);20587 const resource = this._registeredResources[uri.toString()];20588 if (resource) {20589 if (!resource.enabled) {20590 throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);20591 }20592 return resource.readCallback(uri, extra);20593 }20594 for (const template of Object.values(this._registeredResourceTemplates)) {20595 const variables = template.resourceTemplate.uriTemplate.match(uri.toString());20596 if (variables) {20597 return template.readCallback(uri, variables, extra);20598 }20599 }20600 throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);20601 });20602 this._resourceHandlersInitialized = true;20603 }20604 setPromptRequestHandlers() {20605 if (this._promptHandlersInitialized) {20606 return;20607 }20608 this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));20609 this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));20610 this.server.registerCapabilities({20611 prompts: {20612 listChanged: true20613 }20614 });20615 this.server.setRequestHandler(ListPromptsRequestSchema, () => ({20616 prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {20617 return {20618 name,20619 title: prompt.title,20620 description: prompt.description,20621 arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 020622 };20623 })20624 }));20625 this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {20626 const prompt = this._registeredPrompts[request.params.name];20627 if (!prompt) {20628 throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);20629 }20630 if (!prompt.enabled) {20631 throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);20632 }20633 if (prompt.argsSchema) {20634 const argsObj = normalizeObjectSchema(prompt.argsSchema);20635 const parseResult = await safeParseAsync2(argsObj, request.params.arguments);20636 if (!parseResult.success) {20637 const error2 = "error" in parseResult ? parseResult.error : "Unknown error";20638 const errorMessage = getParseErrorMessage(error2);20639 throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);20640 }20641 const args = parseResult.data;20642 const cb = prompt.callback;20643 return await Promise.resolve(cb(args, extra));20644 } else {20645 const cb = prompt.callback;20646 return await Promise.resolve(cb(extra));20647 }20648 });20649 this._promptHandlersInitialized = true;20650 }20651 resource(name, uriOrTemplate, ...rest) {20652 let metadata;20653 if (typeof rest[0] === "object") {20654 metadata = rest.shift();20655 }20656 const readCallback = rest[0];20657 if (typeof uriOrTemplate === "string") {20658 if (this._registeredResources[uriOrTemplate]) {20659 throw new Error(`Resource ${uriOrTemplate} is already registered`);20660 }20661 const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback);20662 this.setResourceRequestHandlers();20663 this.sendResourceListChanged();20664 return registeredResource;20665 } else {20666 if (this._registeredResourceTemplates[name]) {20667 throw new Error(`Resource template ${name} is already registered`);20668 }20669 const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback);20670 this.setResourceRequestHandlers();20671 this.sendResourceListChanged();20672 return registeredResourceTemplate;20673 }20674 }20675 registerResource(name, uriOrTemplate, config2, readCallback) {20676 if (typeof uriOrTemplate === "string") {20677 if (this._registeredResources[uriOrTemplate]) {20678 throw new Error(`Resource ${uriOrTemplate} is already registered`);20679 }20680 const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, config2, readCallback);20681 this.setResourceRequestHandlers();20682 this.sendResourceListChanged();20683 return registeredResource;20684 } else {20685 if (this._registeredResourceTemplates[name]) {20686 throw new Error(`Resource template ${name} is already registered`);20687 }20688 const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, config2, readCallback);20689 this.setResourceRequestHandlers();20690 this.sendResourceListChanged();20691 return registeredResourceTemplate;20692 }20693 }20694 _createRegisteredResource(name, title, uri, metadata, readCallback) {20695 const registeredResource = {20696 name,20697 title,20698 metadata,20699 readCallback,20700 enabled: true,20701 disable: () => registeredResource.update({ enabled: false }),20702 enable: () => registeredResource.update({ enabled: true }),20703 remove: () => registeredResource.update({ uri: null }),20704 update: (updates) => {20705 if (typeof updates.uri !== "undefined" && updates.uri !== uri) {20706 delete this._registeredResources[uri];20707 if (updates.uri)20708 this._registeredResources[updates.uri] = registeredResource;20709 }20710 if (typeof updates.name !== "undefined")20711 registeredResource.name = updates.name;20712 if (typeof updates.title !== "undefined")20713 registeredResource.title = updates.title;20714 if (typeof updates.metadata !== "undefined")20715 registeredResource.metadata = updates.metadata;20716 if (typeof updates.callback !== "undefined")20717 registeredResource.readCallback = updates.callback;20718 if (typeof updates.enabled !== "undefined")20719 registeredResource.enabled = updates.enabled;20720 this.sendResourceListChanged();20721 }20722 };20723 this._registeredResources[uri] = registeredResource;20724 return registeredResource;20725 }20726 _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {20727 const registeredResourceTemplate = {20728 resourceTemplate: template,20729 title,20730 metadata,20731 readCallback,20732 enabled: true,20733 disable: () => registeredResourceTemplate.update({ enabled: false }),20734 enable: () => registeredResourceTemplate.update({ enabled: true }),20735 remove: () => registeredResourceTemplate.update({ name: null }),20736 update: (updates) => {20737 if (typeof updates.name !== "undefined" && updates.name !== name) {20738 delete this._registeredResourceTemplates[name];20739 if (updates.name)20740 this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;20741 }20742 if (typeof updates.title !== "undefined")20743 registeredResourceTemplate.title = updates.title;20744 if (typeof updates.template !== "undefined")20745 registeredResourceTemplate.resourceTemplate = updates.template;20746 if (typeof updates.metadata !== "undefined")20747 registeredResourceTemplate.metadata = updates.metadata;20748 if (typeof updates.callback !== "undefined")20749 registeredResourceTemplate.readCallback = updates.callback;20750 if (typeof updates.enabled !== "undefined")20751 registeredResourceTemplate.enabled = updates.enabled;20752 this.sendResourceListChanged();20753 }20754 };20755 this._registeredResourceTemplates[name] = registeredResourceTemplate;20756 const variableNames = template.uriTemplate.variableNames;20757 const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v));20758 if (hasCompleter) {20759 this.setCompletionRequestHandler();20760 }20761 return registeredResourceTemplate;20762 }20763 _createRegisteredPrompt(name, title, description, argsSchema, callback) {20764 const registeredPrompt = {20765 title,20766 description,20767 argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema),20768 callback,20769 enabled: true,20770 disable: () => registeredPrompt.update({ enabled: false }),20771 enable: () => registeredPrompt.update({ enabled: true }),20772 remove: () => registeredPrompt.update({ name: null }),20773 update: (updates) => {20774 if (typeof updates.name !== "undefined" && updates.name !== name) {20775 delete this._registeredPrompts[name];20776 if (updates.name)20777 this._registeredPrompts[updates.name] = registeredPrompt;20778 }20779 if (typeof updates.title !== "undefined")20780 registeredPrompt.title = updates.title;20781 if (typeof updates.description !== "undefined")20782 registeredPrompt.description = updates.description;20783 if (typeof updates.argsSchema !== "undefined")20784 registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);20785 if (typeof updates.callback !== "undefined")20786 registeredPrompt.callback = updates.callback;20787 if (typeof updates.enabled !== "undefined")20788 registeredPrompt.enabled = updates.enabled;20789 this.sendPromptListChanged();20790 }20791 };20792 this._registeredPrompts[name] = registeredPrompt;20793 if (argsSchema) {20794 const hasCompletable = Object.values(argsSchema).some((field) => {20795 const inner = field instanceof ZodOptional ? field._def?.innerType : field;20796 return isCompletable(inner);20797 });20798 if (hasCompletable) {20799 this.setCompletionRequestHandler();20800 }20801 }20802 return registeredPrompt;20803 }20804 _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {20805 validateAndWarnToolName(name);20806 const registeredTool = {20807 title,20808 description,20809 inputSchema: getZodSchemaObject(inputSchema),20810 outputSchema: getZodSchemaObject(outputSchema),20811 annotations,20812 execution,20813 _meta,20814 handler,20815 enabled: true,20816 disable: () => registeredTool.update({ enabled: false }),20817 enable: () => registeredTool.update({ enabled: true }),20818 remove: () => registeredTool.update({ name: null }),20819 update: (updates) => {20820 if (typeof updates.name !== "undefined" && updates.name !== name) {20821 if (typeof updates.name === "string") {20822 validateAndWarnToolName(updates.name);20823 }20824 delete this._registeredTools[name];20825 if (updates.name)20826 this._registeredTools[updates.name] = registeredTool;20827 }20828 if (typeof updates.title !== "undefined")20829 registeredTool.title = updates.title;20830 if (typeof updates.description !== "undefined")20831 registeredTool.description = updates.description;20832 if (typeof updates.paramsSchema !== "undefined")20833 registeredTool.inputSchema = objectFromShape(updates.paramsSchema);20834 if (typeof updates.outputSchema !== "undefined")20835 registeredTool.outputSchema = objectFromShape(updates.outputSchema);20836 if (typeof updates.callback !== "undefined")20837 registeredTool.handler = updates.callback;20838 if (typeof updates.annotations !== "undefined")20839 registeredTool.annotations = updates.annotations;20840 if (typeof updates._meta !== "undefined")20841 registeredTool._meta = updates._meta;20842 if (typeof updates.enabled !== "undefined")20843 registeredTool.enabled = updates.enabled;20844 this.sendToolListChanged();20845 }20846 };20847 this._registeredTools[name] = registeredTool;20848 this.setToolRequestHandlers();20849 this.sendToolListChanged();20850 return registeredTool;20851 }20852 /**20853 * tool() implementation. Parses arguments passed to overrides defined above.20854 */20855 tool(name, ...rest) {20856 if (this._registeredTools[name]) {20857 throw new Error(`Tool ${name} is already registered`);20858 }20859 let description;20860 let inputSchema;20861 let outputSchema;20862 let annotations;20863 if (typeof rest[0] === "string") {20864 description = rest.shift();20865 }20866 if (rest.length > 1) {20867 const firstArg = rest[0];20868 if (isZodRawShapeCompat(firstArg)) {20869 inputSchema = rest.shift();20870 if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {20871 annotations = rest.shift();20872 }20873 } else if (typeof firstArg === "object" && firstArg !== null) {20874 if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) {20875 throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);20876 }20877 annotations = rest.shift();20878 }20879 }20880 const callback = rest[0];20881 return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);20882 }20883 /**20884 * Registers a tool with a config object and callback.20885 */20886 registerTool(name, config2, cb) {20887 if (this._registeredTools[name]) {20888 throw new Error(`Tool ${name} is already registered`);20889 }20890 const { title, description, inputSchema, outputSchema, annotations, _meta } = config2;20891 return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);20892 }20893 prompt(name, ...rest) {20894 if (this._registeredPrompts[name]) {20895 throw new Error(`Prompt ${name} is already registered`);20896 }20897 let description;20898 if (typeof rest[0] === "string") {20899 description = rest.shift();20900 }20901 let argsSchema;20902 if (rest.length > 1) {20903 argsSchema = rest.shift();20904 }20905 const cb = rest[0];20906 const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb);20907 this.setPromptRequestHandlers();20908 this.sendPromptListChanged();20909 return registeredPrompt;20910 }20911 /**20912 * Registers a prompt with a config object and callback.20913 */20914 registerPrompt(name, config2, cb) {20915 if (this._registeredPrompts[name]) {20916 throw new Error(`Prompt ${name} is already registered`);20917 }20918 const { title, description, argsSchema } = config2;20919 const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);20920 this.setPromptRequestHandlers();20921 this.sendPromptListChanged();20922 return registeredPrompt;20923 }20924 /**20925 * Checks if the server is connected to a transport.20926 * @returns True if the server is connected20927 */20928 isConnected() {20929 return this.server.transport !== void 0;20930 }20931 /**20932 * Sends a logging message to the client, if connected.20933 * Note: You only need to send the parameters object, not the entire JSON RPC message20934 * @see LoggingMessageNotification20935 * @param params20936 * @param sessionId optional for stateless and backward compatibility20937 */20938 async sendLoggingMessage(params, sessionId) {20939 return this.server.sendLoggingMessage(params, sessionId);20940 }20941 /**20942 * Sends a resource list changed event to the client, if connected.20943 */20944 sendResourceListChanged() {20945 if (this.isConnected()) {20946 this.server.sendResourceListChanged();20947 }20948 }20949 /**20950 * Sends a tool list changed event to the client, if connected.20951 */20952 sendToolListChanged() {20953 if (this.isConnected()) {20954 this.server.sendToolListChanged();20955 }20956 }20957 /**20958 * Sends a prompt list changed event to the client, if connected.20959 */20960 sendPromptListChanged() {20961 if (this.isConnected()) {20962 this.server.sendPromptListChanged();20963 }20964 }20965};20966var EMPTY_OBJECT_JSON_SCHEMA = {20967 type: "object",20968 properties: {}20969};20970function isZodTypeLike(value) {20971 return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";20972}20973function isZodSchemaInstance(obj) {20974 return "_def" in obj || "_zod" in obj || isZodTypeLike(obj);20975}20976function isZodRawShapeCompat(obj) {20977 if (typeof obj !== "object" || obj === null) {20978 return false;20979 }20980 if (isZodSchemaInstance(obj)) {20981 return false;20982 }20983 if (Object.keys(obj).length === 0) {20984 return true;20985 }20986 return Object.values(obj).some(isZodTypeLike);20987}20988function getZodSchemaObject(schema) {20989 if (!schema) {20990 return void 0;20991 }20992 if (isZodRawShapeCompat(schema)) {20993 return objectFromShape(schema);20994 }20995 if (!isZodSchemaInstance(schema)) {20996 throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");20997 }20998 return schema;20999}21000function promptArgumentsFromSchema(schema) {21001 const shape = getObjectShape(schema);21002 if (!shape)21003 return [];21004 return Object.entries(shape).map(([name, field]) => {21005 const description = getSchemaDescription(field);21006 const isOptional = isSchemaOptional(field);21007 return {21008 name,21009 description,21010 required: !isOptional21011 };21012 });21013}21014function getMethodValue(schema) {21015 const shape = getObjectShape(schema);21016 const methodSchema = shape?.method;21017 if (!methodSchema) {21018 throw new Error("Schema is missing a method literal");21019 }21020 const value = getLiteralValue(methodSchema);21021 if (typeof value === "string") {21022 return value;21023 }21024 throw new Error("Schema method literal must be a string");21025}21026function createCompletionResult(suggestions) {21027 return {21028 completion: {21029 values: suggestions.slice(0, 100),21030 total: suggestions.length,21031 hasMore: suggestions.length > 10021032 }21033 };21034}21035var EMPTY_COMPLETION_RESULT = {21036 completion: {21037 values: [],21038 hasMore: false21039 }21040};2104121042// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js21043import process2 from "node:process";2104421045// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js21046var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;21047var ReadBuffer = class {21048 constructor(options) {21049 this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;21050 }21051 append(chunk) {21052 const newSize = (this._buffer?.length ?? 0) + chunk.length;21053 if (newSize > this._maxBufferSize) {21054 this.clear();21055 throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);21056 }21057 this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;21058 }21059 readMessage() {21060 if (!this._buffer) {21061 return null;21062 }21063 const index = this._buffer.indexOf("\n");21064 if (index === -1) {21065 return null;21066 }21067 const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");21068 this._buffer = this._buffer.subarray(index + 1);21069 return deserializeMessage(line);21070 }21071 clear() {21072 this._buffer = void 0;21073 }21074};21075function deserializeMessage(line) {21076 return JSONRPCMessageSchema.parse(JSON.parse(line));21077}21078function serializeMessage(message) {21079 return JSON.stringify(message) + "\n";21080}2108121082// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js21083var StdioServerTransport = class {21084 constructor(_stdin = process2.stdin, _stdout = process2.stdout, options) {21085 this._stdin = _stdin;21086 this._stdout = _stdout;21087 this._started = false;21088 this._ondata = (chunk) => {21089 try {21090 this._readBuffer.append(chunk);21091 this.processReadBuffer();21092 } catch (error2) {21093 this.onerror?.(error2);21094 this.close().catch(() => {21095 });21096 }21097 };21098 this._onerror = (error2) => {21099 this.onerror?.(error2);21100 };21101 this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });21102 }21103 /**21104 * Starts listening for messages on stdin.21105 */21106 async start() {21107 if (this._started) {21108 throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");21109 }21110 this._started = true;21111 this._stdin.on("data", this._ondata);21112 this._stdin.on("error", this._onerror);21113 }21114 processReadBuffer() {21115 while (true) {21116 try {21117 const message = this._readBuffer.readMessage();21118 if (message === null) {21119 break;21120 }21121 this.onmessage?.(message);21122 } catch (error2) {21123 this.onerror?.(error2);21124 }21125 }21126 }21127 async close() {21128 this._stdin.off("data", this._ondata);21129 this._stdin.off("error", this._onerror);21130 const remainingDataListeners = this._stdin.listenerCount("data");21131 if (remainingDataListeners === 0) {21132 this._stdin.pause();21133 }21134 this._readBuffer.clear();21135 this.onclose?.();21136 }21137 send(message) {21138 return new Promise((resolve) => {21139 const json = serializeMessage(message);21140 if (this._stdout.write(json)) {21141 resolve();21142 } else {21143 this._stdout.once("drain", resolve);21144 }21145 });21146 }21147};2114821149// src/index.ts21150var BASE_URL = (process.env.TENDRIL_BASE_URL ?? "https://www.ten-dril.com").replace(/\/+$/, "");21151var API_KEY = process.env.TENDRIL_API_KEY;21152async function call(path, body) {21153 const headers = { "content-type": "application/json" };21154 if (API_KEY) headers["authorization"] = `Bearer ${API_KEY}`;21155 const res = await fetch(`${BASE_URL}${path}`, {21156 method: body === void 0 ? "GET" : "POST",21157 headers,21158 ...body === void 0 ? {} : { body: JSON.stringify(body) }21159 });21160 const text = await res.text();21161 try {21162 return JSON.parse(text);21163 } catch {21164 return { success: false, error: { code: "ERR_NON_JSON", message: text.slice(0, 500) } };21165 }21166}21167function textResult(text, isError = false) {21168 return { content: [{ type: "text", text }], ...isError ? { isError: true } : {} };21169}21170function errText(env) {21171 return `Tendril error ${env.error?.code ?? "UNKNOWN"}: ${env.error?.message ?? "request failed"}`;21172}21173var server = new McpServer({ name: "tendril", version: "0.1.0" });21174server.tool(21175 "tendril_scrape",21176 "Fetch a single web page through Tendril and return clean Markdown (plus optional links, structured data, and metadata). Use this to read the content of a specific URL. Tendril runs real WebKit behind a residential IP and extracts deterministically.",21177 {21178 url: external_exports.string().url().describe("The absolute URL to scrape"),21179 formats: external_exports.array(external_exports.enum(["markdown", "html", "links", "structured"])).optional().describe("Output formats to include (default: markdown)"),21180 onlyMainContent: external_exports.boolean().optional().describe("Strip nav/footer/ads and keep the main article (default: true)"),21181 tier: external_exports.enum(["auto", "http"]).optional().describe("Fetch tier. 'http' forces Tier 0 output even if escalation is suggested (default: auto)")21182 },21183 async ({ url, formats, onlyMainContent, tier }) => {21184 const env = await call("/v1/scrape", {21185 url,21186 formats: formats ?? ["markdown"],21187 ...onlyMainContent !== void 0 ? { onlyMainContent } : {},21188 ...tier !== void 0 ? { tier } : {}21189 });21190 if (!env.success) return textResult(errText(env), true);21191 const d = env.data;21192 const parts = [];21193 if (typeof d.markdown === "string") parts.push(d.markdown);21194 if (d.structured) parts.push("\n\n---\nStructured data:\n" + JSON.stringify(d.structured, null, 2));21195 if (Array.isArray(d.links)) parts.push(`2119621197---21198${d.links.length} links extracted.`);21199 if (d.html && !d.markdown) parts.push(String(d.html).slice(0, 2e4));21200 return textResult(parts.join("") || JSON.stringify(d, null, 2));21201 }21202);21203server.tool(21204 "tendril_map",21205 "Discover the URLs of a website without rendering \u2014 merges sitemaps, robots.txt, homepage links and /llms.txt. Use this to find pages on a site before scraping them, or to get a site's structure quickly.",21206 {21207 url: external_exports.string().url().describe("The site root to map, e.g. https://example.com"),21208 search: external_exports.string().optional().describe("Only return URLs containing this substring"),21209 limit: external_exports.number().int().min(1).max(5e4).optional().describe("Max URLs to return (default: 100)"),21210 includeSubdomains: external_exports.boolean().optional().describe("Include subdomains of the apex (default: false)")21211 },21212 async ({ url, search, limit, includeSubdomains }) => {21213 const env = await call("/v1/map", {21214 url,21215 limit: limit ?? 100,21216 ...search !== void 0 ? { search } : {},21217 ...includeSubdomains !== void 0 ? { includeSubdomains } : {}21218 });21219 if (!env.success) return textResult(errText(env), true);21220 const d = env.data;21221 const lines = d.links.map((l) => `- ${l.url} (${l.source})`).join("\n");21222 return textResult(`${d.count} URLs discovered on ${url}:2122321224${lines}`);21225 }21226);21227server.tool(21228 "tendril_status",21229 "Check Tendril's health and which fetch tiers are currently available. Call this if scrape/map requests are failing.",21230 {},21231 async () => {21232 const env = await call("/v1/status", void 0);21233 return textResult(JSON.stringify(env.data ?? env, null, 2));21234 }21235);21236async function main() {21237 const transport = new StdioServerTransport();21238 await server.connect(transport);21239 process.stderr.write(`tendril-mcp connected (base=${BASE_URL})21240`);21241}21242main().catch((err) => {21243 process.stderr.write(`tendril-mcp fatal: ${String(err)}21244`);21245 process.exit(1);21246});21247