← Back
Editing: angie-integration.js
/******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ 4018 (__unused_webpack_module, exports) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; function fmtDef(validate, compare) { return { validate, compare }; } exports.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(getTime(true), compareTime), "date-time": fmtDef(getDateTime(true), compareDateTime), "iso-time": fmtDef(getTime(), compareIsoTime), "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "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, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: { type: "number", validate: validateInt32 }, // signed 64 bit integer int64: { type: "number", validate: validateInt64 }, // C-type float float: { type: "number", validate: validateNumber }, // C-type double double: { type: "number", validate: validateNumber }, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true, }; exports.fastFormats = { ...exports.fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, }; exports.formatNames = Object.keys(exports.fullFormats); function isLeapYear(year) { // https://tools.ietf.org/html/rfc3339#appendix-C return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function date(str) { // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 const matches = DATE.exec(str); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return (month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])); } function compareDate(d1, d2) { if (!(d1 && d2)) return undefined; if (d1 > d2) return 1; if (d1 < d2) return -1; return 0; } const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; function getTime(strictTimeZone) { return function time(str) { const matches = TIME.exec(str); if (!matches) return false; const hr = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tz = matches[4]; const tzSign = matches[5] === "-" ? -1 : 1; const tzH = +(matches[6] || 0); const tzM = +(matches[7] || 0); if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false; if (hr <= 23 && min <= 59 && sec < 60) return true; // leap second const utcMin = min - tzM * tzSign; const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; }; } function compareTime(s1, s2) { if (!(s1 && s2)) return undefined; const t1 = new Date("2020-01-01T" + s1).valueOf(); const t2 = new Date("2020-01-01T" + s2).valueOf(); if (!(t1 && t2)) return undefined; return t1 - t2; } function compareIsoTime(t1, t2) { if (!(t1 && t2)) return undefined; const a1 = TIME.exec(t1); const a2 = TIME.exec(t2); if (!(a1 && a2)) return undefined; t1 = a1[1] + a1[2] + a1[3]; t2 = a2[1] + a2[2] + a2[3]; if (t1 > t2) return 1; if (t1 < t2) return -1; return 0; } const DATE_TIME_SEPARATOR = /t|\s/i; function getDateTime(strictTimeZone) { const time = getTime(strictTimeZone); return function date_time(str) { // http://tools.ietf.org/html/rfc3339#section-5.6 const dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); }; } function compareDateTime(dt1, dt2) { if (!(dt1 && dt2)) return undefined; const d1 = new Date(dt1).valueOf(); const d2 = new Date(dt2).valueOf(); if (!(d1 && d2)) return undefined; return d1 - d2; } function compareIsoDateTime(dt1, dt2) { if (!(dt1 && dt2)) return undefined; const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); const res = compareDate(d1, d2); if (res === undefined) return undefined; return res || compareTime(t1, t2); } const NOT_URI_FRAGMENT = /\/|:/; const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; function uri(str) { // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." return NOT_URI_FRAGMENT.test(str) && URI.test(str); } const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; function byte(str) { BYTE.lastIndex = 0; return BYTE.test(str); } const MIN_INT32 = -(2 ** 31); const MAX_INT32 = 2 ** 31 - 1; function validateInt32(value) { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; } function validateInt64(value) { // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64 return Number.isInteger(value); } function validateNumber() { return true; } const Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch (e) { return false; } } //# sourceMappingURL=formats.js.map /***/ }, /***/ 8182 (module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", ({ value: true })); const formats_1 = __webpack_require__(4018); const limit_1 = __webpack_require__(6461); const codegen_1 = __webpack_require__(9029); const fullName = new codegen_1.Name("fullFormats"); const fastName = new codegen_1.Name("fastFormats"); const formatsPlugin = (ajv, opts = { keywords: true }) => { if (Array.isArray(opts)) { addFormats(ajv, opts, formats_1.fullFormats, fullName); return ajv; } const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; const list = opts.formats || formats_1.formatNames; addFormats(ajv, list, formats, exportName); if (opts.keywords) (0, limit_1.default)(ajv); return ajv; }; formatsPlugin.get = (name, mode = "full") => { const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; const f = formats[name]; if (!f) throw new Error(`Unknown format "${name}"`); return f; }; function addFormats(ajv, list, fs, exportName) { var _a; var _b; (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require("ajv-formats/dist/formats").${exportName}`); for (const f of list) ajv.addFormat(f, fs[f]); } module.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = formatsPlugin; //# sourceMappingURL=index.js.map /***/ }, /***/ 6461 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.A = void 0; const ajv_1 = __webpack_require__(3282); const codegen_1 = __webpack_require__(9029); const ops = codegen_1.operators; const KWDs = { formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, }; const error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, }; exports.A = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self } = it; if (!opts.validateFormats) return; const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); if (fCxt.$data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats, }); const fmt = gen.const("fmt", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`); cxt.fail$data((0, codegen_1.or)((0, codegen_1._) `typeof ${fmt} != "object"`, (0, codegen_1._) `${fmt} instanceof RegExp`, (0, codegen_1._) `typeof ${fmt}.compare != "function"`, compareCode(fmt))); } function validateFormat() { const format = fCxt.schema; const fmtDef = self.formats[format]; if (!fmtDef || fmtDef === true) return; if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); } const fmt = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined, }); cxt.fail$data(compareCode(fmt)); } function compareCode(fmt) { return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; } }, dependencies: ["format"], }; const formatLimitPlugin = (ajv) => { ajv.addKeyword(exports.A); return ajv; }; exports["default"] = formatLimitPlugin; //# sourceMappingURL=limit.js.map /***/ }, /***/ 3282 (module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; const core_1 = __webpack_require__(4042); const draft7_1 = __webpack_require__(6144); const discriminator_1 = __webpack_require__(6653); const draft7MetaSchema = __webpack_require__(2079); const META_SUPPORT_DATA = ["/properties"]; const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; class Ajv extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); } } exports.Ajv = Ajv; module.exports = exports = Ajv; module.exports.Ajv = Ajv; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = Ajv; var validate_1 = __webpack_require__(2586); Object.defineProperty(exports, "KeywordCxt", ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } })); var codegen_1 = __webpack_require__(9029); Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return codegen_1._; } })); Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return codegen_1.str; } })); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return codegen_1.stringify; } })); Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return codegen_1.nil; } })); Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return codegen_1.Name; } })); Object.defineProperty(exports, "CodeGen", ({ enumerable: true, get: function () { return codegen_1.CodeGen; } })); var validation_error_1 = __webpack_require__(3558); Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return validation_error_1.default; } })); var ref_error_1 = __webpack_require__(4551); Object.defineProperty(exports, "MissingRefError", ({ enumerable: true, get: function () { return ref_error_1.default; } })); //# sourceMappingURL=ajv.js.map /***/ }, /***/ 1520 (__unused_webpack_module, exports) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; // eslint-disable-next-line @typescript-eslint/no-extraneous-class class _CodeOrName { } exports._CodeOrName = _CodeOrName; exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; class Name extends _CodeOrName { constructor(s) { super(); if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } } exports.Name = Name; class _Code extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a; return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, ""))); } get names() { var _a; return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}))); } } exports._Code = _Code; exports.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports._ = _; const plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== undefined) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`; } exports.strConcat = strConcat; // TODO do not allow arrays here function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports.stringify = stringify; function safeStringify(x) { return JSON.stringify(x) .replace(/\u2028/g, "\\u2028") .replace(/\u2029/g, "\\u2029"); } exports.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`; } exports.getProperty = getProperty; //Does best effort to format the name properly function getEsmExportName(key) { if (typeof key == "string" && exports.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports.regexpCode = regexpCode; //# sourceMappingURL=code.js.map /***/ }, /***/ 9029 (__unused_webpack_module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; const code_1 = __webpack_require__(1520); const scope_1 = __webpack_require__(7845); var code_2 = __webpack_require__(1520); Object.defineProperty(exports, "_", ({ enumerable: true, get: function () { return code_2._; } })); Object.defineProperty(exports, "str", ({ enumerable: true, get: function () { return code_2.str; } })); Object.defineProperty(exports, "strConcat", ({ enumerable: true, get: function () { return code_2.strConcat; } })); Object.defineProperty(exports, "nil", ({ enumerable: true, get: function () { return code_2.nil; } })); Object.defineProperty(exports, "getProperty", ({ enumerable: true, get: function () { return code_2.getProperty; } })); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return code_2.stringify; } })); Object.defineProperty(exports, "regexpCode", ({ enumerable: true, get: function () { return code_2.regexpCode; } })); Object.defineProperty(exports, "Name", ({ enumerable: true, get: function () { return code_2.Name; } })); var scope_2 = __webpack_require__(7845); Object.defineProperty(exports, "Scope", ({ enumerable: true, get: function () { return scope_2.Scope; } })); Object.defineProperty(exports, "ValueScope", ({ enumerable: true, get: function () { return scope_2.ValueScope; } })); Object.defineProperty(exports, "ValueScopeName", ({ enumerable: true, get: function () { return scope_2.ValueScopeName; } })); Object.defineProperty(exports, "varKinds", ({ enumerable: true, get: function () { return scope_2.varKinds; } })); exports.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+"), }; class Node { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } } class Def extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } } class Assign extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } } class AssignOp extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } } class Label extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } } class Break extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } } class Throw extends Node { constructor(error) { super(); this.error = error; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } } class AnyCode extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : undefined; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } } class ParentNode extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : undefined; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { // iterating backwards improves 1-pass optimization const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : undefined; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } } class BlockNode extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } } class Root extends ParentNode { } class Else extends BlockNode { } Else.kind = "else"; class If extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; // else is ignored here let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof If ? e : e.nodes; if (this.nodes.length) return this; return new If(not(cond), e instanceof If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return undefined; return this; } optimizeNames(names, constants) { var _a; this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } } If.kind = "if"; class For extends BlockNode { } For.kind = "for"; class ForLoop extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } } class ForRange extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } } class ForIter extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } } class Func extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } } Func.kind = "func"; class Return extends ParentNode { render(opts) { return "return " + super.render(opts); } } Return.kind = "return"; class Try extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a, _b; super.optimizeNodes(); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a, _b; super.optimizeNames(names, constants); (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } } class Catch extends BlockNode { constructor(error) { super(); this.error = error; } render(opts) { return `catch(${this.error})` + super.render(opts); } } Catch.kind = "catch"; class Finally extends BlockNode { render(opts) { return "finally" + super.render(opts); } } Finally.kind = "finally"; class CodeGen { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== undefined && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => { this.var(name, (0, code_1._) `${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error = this.name("e"); this._currNode = node.catch = new Catch(error); catchCode(error); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error) { return this._leafNode(new Throw(error)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === undefined) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || (N2 && n instanceof N2)) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } } exports.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === undefined || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return (e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined)); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`; } exports.not = not; const andCode = mappend(exports.operators.AND); // boolean AND (&&) expression with the passed arguments function and(...args) { return args.reduce(andCode); } exports.and = and; const orCode = mappend(exports.operators.OR); // boolean OR (||) expression with the passed arguments function or(...args) { return args.reduce(orCode); } exports.or = or; function mappend(op) { return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`); } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`; } //# sourceMappingURL=index.js.map /***/ }, /***/ 7845 (__unused_webpack_module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; const code_1 = __webpack_require__(1520); class ValueError extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } } var UsedValueState; (function (UsedValueState) { UsedValueState[UsedValueState["Started"] = 0] = "Started"; UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); exports.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var"), }; class Scope { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a, _b; if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return (this._names[prefix] = { prefix, index: 0 }); } } exports.Scope = Scope; class ValueScopeName extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`; } } exports.ValueScopeName = ValueScopeName; const line = (0, code_1._) `\n`; class ValueScope extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a; if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._) `${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`; } else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) { code = (0, code_1._) `${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } } exports.ValueScope = ValueScope; //# sourceMappingURL=scope.js.map /***/ }, /***/ 8708 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.y = void 0; const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const names_1 = __webpack_require__(2023); exports.y = { message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`, }; exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`, }; function reportError(cxt, error = exports.y, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._) `[${errObj}]`); } } exports.reportError = reportError; function reportExtraError(cxt, error = exports.y, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) { /* istanbul ignore if */ if (errsCount === undefined) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._) `${err}.schema`, schemaValue); gen.assign((0, codegen_1._) `${err}.data`, data); } }); } exports.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._) `${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._) `${validateName}.errors`, errs); gen.return(false); } } const E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema"), }; function errorObjectCode(cxt, error, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._) `{}`; return errorObject(cxt, error, errorPaths); } function errorObject(cxt, error, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths), ]; extraErrorProps(cxt, error, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } //# sourceMappingURL=errors.js.map /***/ }, /***/ 3835 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.resolveSchema = __webpack_unused_export__ = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; const codegen_1 = __webpack_require__(9029); const validation_error_1 = __webpack_require__(3558); const names_1 = __webpack_require__(2023); const resolve_1 = __webpack_require__(6939); const util_1 = __webpack_require__(4227); const validate_1 = __webpack_require__(2586); class SchemaEnv { constructor(env) { var _a; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } } exports.SchemaEnv = SchemaEnv; // let codeSize = 0 // let nodeCount = 0 // Compiles schema in SchemaEnv function compileSchema(sch) { // TODO refactor - remove compilations const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`, }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._) `""`, opts: this.opts, self: this, }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); // gen.optimize(1) const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); // console.log("\n\n\n *** \n", sourceCode) const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate }); validate.errors = null; validate.schema = sch.schema; validate.schemaEnv = sch; if (sch.$async) validate.$async = true; if (this.opts.code.source === true) { validate.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate.evaluated = { props: props instanceof codegen_1.Name ? undefined : props, items: items instanceof codegen_1.Name ? undefined : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name, }; if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); } sch.validate = validate; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); // console.log("\n\n\n *** \n", sourceCode, this.opts) throw e; } finally { this._compilations.delete(sch); } } exports.compileSchema = compileSchema; function resolveRef(root, baseId, ref) { var _a; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve.call(this, root, ref); if (_sch === undefined) { const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === undefined) return; return (root.refs[ref] = inlineOrCompile.call(this, _sch)); } exports.resolveRef = resolveRef; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } // Index of schema compilation in the currently compiled list function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } __webpack_unused_export__ = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } // resolve and compile the references ($ref) // TODO returns AnySchemaObject (if the schema can be inlined) or validation function function resolve(root, // information about the root schema for the current schema ref // reference to resolve ) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } // Resolve schema, its root and baseId function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it ref // reference to resolve ) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined); // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports.resolveSchema = resolveSchema; const PREVENT_SCOPE_CHANGE = new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions", ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a; if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === undefined) return; schema = partSchema; // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } // even though resolution failed we need to return SchemaEnv to throw exception // so that compileAsync loads missing schema. const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return undefined; } //# sourceMappingURL=index.js.map /***/ }, /***/ 2023 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart"), }; exports["default"] = names; //# sourceMappingURL=names.js.map /***/ }, /***/ 4551 (__unused_webpack_module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", ({ value: true })); const resolve_1 = __webpack_require__(6939); class MissingRefError extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } } exports["default"] = MissingRefError; //# sourceMappingURL=ref_error.js.map /***/ }, /***/ 6939 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; const util_1 = __webpack_require__(4227); const equal = __webpack_require__(2017); const traverse = __webpack_require__(7106); // TODO refactor to use keyword definitions const SIMPLE_INLINED = new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const", ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports.inlineRef = inlineRef; const REF_KEYWORDS = new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor", ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch))); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports._getFullPath = _getFullPath; const TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports.resolveUrl = resolveUrl; const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === undefined) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { // eslint-disable-next-line @typescript-eslint/unbound-method const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports.getSchemaRefs = getSchemaRefs; //# sourceMappingURL=resolve.js.map /***/ }, /***/ 396 (__unused_webpack_module, exports) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.getRules = exports.isJSONType = void 0; const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; const jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] }, }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {}, }; } exports.getRules = getRules; //# sourceMappingURL=rules.js.map /***/ }, /***/ 4227 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = __webpack_unused_export__ = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = __webpack_unused_export__ = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = __webpack_unused_export__ = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; const codegen_1 = __webpack_require__(9029); const code_1 = __webpack_require__(1520); // TODO refactor to use Set function toHash(arr) { const hash = {}; for (const item of arr) hash[item] = true; return hash; } exports.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } __webpack_unused_export__ = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._) `${schema}`; } return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } __webpack_unused_export__ = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) { return (gen, from, to, toName) => { const res = to === undefined ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._) `${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => (from === true ? true : { ...from, ...to }), resultToName: evaluatedPropsToName, }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), resultToName: (gen, items) => gen.var("items", items), }), }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._) `{}`); if (ps !== undefined) setEvaluated(gen, props, ps); return props; } exports.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true)); } __webpack_unused_export__ = setEvaluated; const snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)), }); } exports.useFunc = useFunc; var Type; (function (Type) { Type[Type["Num"] = 0] = "Num"; Type[Type["Str"] = 1] = "Str"; })(Type || (exports.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { // let path if (dataProp instanceof codegen_1.Name) { const isNumber = dataPropType === Type.Num; return jsPropertySyntax ? isNumber ? (0, codegen_1._) `"[" + ${dataProp} + "]"` : (0, codegen_1._) `"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._) `"/" + ${dataProp}` : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports.checkStrictMode = checkStrictMode; //# sourceMappingURL=util.js.map /***/ }, /***/ 7887 (__unused_webpack_module, exports) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a; return (schema[rule.keyword] !== undefined || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined))); } exports.shouldUseRule = shouldUseRule; //# sourceMappingURL=applicability.js.map /***/ }, /***/ 8727 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; const errors_1 = __webpack_require__(8708); const codegen_1 = __webpack_require__(9029); const names_1 = __webpack_require__(2023); const boolError = { message: "boolean schema is false", }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._) `${validateName}.errors`, null); gen.return(true); } } exports.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); // TODO var falseSchemaError(it); } else { gen.var(valid, true); // TODO var } } exports.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; // TODO maybe some other interface should be used for non-keyword validation errors... const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it, }; (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors); } //# sourceMappingURL=boolSchema.js.map /***/ }, /***/ 208 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; const rules_1 = __webpack_require__(396); const applicability_1 = __webpack_require__(7887); const errors_1 = __webpack_require__(8708); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); var DataType; (function (DataType) { DataType[DataType["Correct"] = 0] = "Correct"; DataType[DataType["Wrong"] = 1] = "Wrong"; })(DataType || (exports.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== undefined) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports.getSchemaTypes = getSchemaTypes; // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports.coerceAndCheckDataType = coerceAndCheckDataType; const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._) `undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen .assign(data, (0, codegen_1._) `${data}[0]`) .assign(dataType, (0, codegen_1._) `typeof ${data}`) .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._) `${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._) `${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`) .assign(coerced, (0, codegen_1._) `"" + ${data}`) .elseIf((0, codegen_1._) `${data} === null`) .assign(coerced, (0, codegen_1._) `""`); return; case "number": gen .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`) .assign(coerced, (0, codegen_1._) `+${data}`); return; case "integer": gen .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`) .assign(coerced, (0, codegen_1._) `+${data}`); return; case "boolean": gen .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`) .assign(coerced, false) .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`) .assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`) .assign(coerced, (0, codegen_1._) `[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { // TODO use gen.property gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._) `${data} ${EQ} null`; case "array": cond = (0, codegen_1._) `Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil); } } exports.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._) `typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports.checkDataTypes = checkDataTypes; const typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`, }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it, }; } //# sourceMappingURL=dataType.js.map /***/ }, /***/ 7870 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.assignDefaults = void 0; const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === undefined) return; const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._) `${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`; } // `${childData} === undefined` + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } //# sourceMappingURL=defaults.js.map /***/ }, /***/ 2586 (__unused_webpack_module, exports, __webpack_require__) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; const boolSchema_1 = __webpack_require__(8727); const dataType_1 = __webpack_require__(208); const applicability_1 = __webpack_require__(7887); const dataType_2 = __webpack_require__(208); const defaults_1 = __webpack_require__(7870); const keyword_1 = __webpack_require__(3673); const subschema_1 = __webpack_require__(4495); const codegen_1 = __webpack_require__(9029); const names_1 = __webpack_require__(2023); const resolve_1 = __webpack_require__(6939); const util_1 = __webpack_require__(4227); const errors_1 = __webpack_require__(8708); // schema compilation - generates validation function, subschemaCode (below) is used for subschemas function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._) `""`); gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`); gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`)); gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil; } // schema compilation - this function is used recursively to generate code for sub-schemas function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); // TODO var gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { // TODO assign unevaluated gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._) `${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._) `${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._) `${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } // TODO make it "ok" call? if (!allErrors) gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults }, } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")); } function includesType(ts, t) { return ts.includes(t) || (t === "integer" && ts.includes("number")); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } class KeywordCxt { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), undefined, failAction); } fail(condition) { if (condition === undefined) { this.error(); if (!this.allErrors) this.gen.if(false); // this branch will be removed by gen.optimize return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== undefined) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== undefined) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } } exports.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment of segments) { if (segment) { data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; expr = (0, codegen_1._) `${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports.getData = getData; //# sourceMappingURL=index.js.map /***/ }, /***/ 3673 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; const codegen_1 = __webpack_require__(9029); const names_1 = __webpack_require__(2023); const code_1 = __webpack_require__(5765); const errors_1 = __webpack_require__(8708); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true, }, valid); cxt.pass(valid, () => cxt.error(true)); } exports.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._) `${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !(("compile" in def && !$data) || def.schema === false); gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a; gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); } } exports.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => { gen .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`) .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { // TODO add tests return (!schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || (allowUndefined && typeof schema == "undefined"))); } exports.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { /* istanbul ignore if */ if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports.validateKeywordUsage = validateKeywordUsage; //# sourceMappingURL=keyword.js.map /***/ }, /***/ 4495 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== undefined && schema !== undefined) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== undefined) { const sch = it.schema[keyword]; return schemaProp === undefined ? { schema: sch, schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}`, } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`, }; } if (schema !== undefined) { if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath, }; } throw new Error('either "keyword" or "schema" must be passed'); } exports.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== undefined && dataProp !== undefined) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== undefined) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== undefined) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once? dataContextProps(nextData); if (propertyName !== undefined) subschema.propertyName = propertyName; // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== undefined) subschema.compositeRule = compositeRule; if (createErrors !== undefined) subschema.createErrors = createErrors; if (allErrors !== undefined) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; // not inherited subschema.jtdMetadata = jtdMetadata; // not inherited } exports.extendSubschemaMode = extendSubschemaMode; //# sourceMappingURL=subschema.js.map /***/ }, /***/ 4042 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = void 0; var validate_1 = __webpack_require__(2586); __webpack_unused_export__ = ({ enumerable: true, get: function () { return validate_1.KeywordCxt; } }); var codegen_1 = __webpack_require__(9029); __webpack_unused_export__ = ({ enumerable: true, get: function () { return codegen_1._; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return codegen_1.str; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return codegen_1.stringify; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return codegen_1.nil; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return codegen_1.Name; } }); __webpack_unused_export__ = ({ enumerable: true, get: function () { return codegen_1.CodeGen; } }); const validation_error_1 = __webpack_require__(3558); const ref_error_1 = __webpack_require__(4551); const rules_1 = __webpack_require__(396); const compile_1 = __webpack_require__(3835); const codegen_2 = __webpack_require__(9029); const resolve_1 = __webpack_require__(6939); const dataType_1 = __webpack_require__(208); const util_1 = __webpack_require__(4227); const $dataRefSchema = __webpack_require__(3837); const uri_1 = __webpack_require__(5944); const defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; const EXT_SCOPE_NAMES = new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error", ]); const removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now.", }; const deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.', }; const MAX_EXPRESSION = 200; // eslint-disable-next-line complexity function requiredOptions(o) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver: uriResolver, }; } class Ajv { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = Object.create(null); this._compilations = new Set(); this._loading = {}; this._cache = new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta, schemaId } = this.opts; return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined); } validate(schemaKeyRef, // key, ref or schema object // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents data // to be validated ) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return (sch.validate || this._compileSchemaEnv(sch)); } compileAsync(schema, meta) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, // If array is passed, `key` will be ignored key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. ) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== undefined && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, // schema key _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema ) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== undefined && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === undefined) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return (sch.validate || this._compileSchemaEnv(sch)); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey = schemaKeyRef; this._cache.delete(cacheKey); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def // deprecated ) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === undefined) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType), }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { // TODO return type should be Ajv const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, // optional array of validation errors { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar` ) { if (!errors || errors.length === 0) return "No errors"; return errors .map((e) => `${dataVar}${e.instancePath} ${e.message}`) .reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); // first segment is an empty string let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== undefined) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); /* istanbul ignore if */ if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } } Ajv.ValidationError = validation_error_1.default; Ajv.MissingRefError = ref_error_1.default; exports["default"] = Ajv; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } const noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === undefined) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType), }, }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === undefined) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } //# sourceMappingURL=core.js.map /***/ }, /***/ 6250 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); // https://github.com/ajv-validator/ajv/issues/889 const equal = __webpack_require__(2017); equal.code = 'require("ajv/dist/runtime/equal").default'; exports["default"] = equal; //# sourceMappingURL=equal.js.map /***/ }, /***/ 3853 (__unused_webpack_module, exports) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); // https://mathiasbynens.be/notes/javascript-encoding // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 0xd800 && value <= 0xdbff && pos < len) { // high surrogate, and there is a next character value = str.charCodeAt(pos); if ((value & 0xfc00) === 0xdc00) pos++; // low surrogate } } return length; } exports["default"] = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; //# sourceMappingURL=ucs2length.js.map /***/ }, /***/ 5944 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const uri = __webpack_require__(8343); uri.code = 'require("ajv/dist/runtime/uri").default'; exports["default"] = uri; //# sourceMappingURL=uri.js.map /***/ }, /***/ 3558 (__unused_webpack_module, exports) { Object.defineProperty(exports, "__esModule", ({ value: true })); class ValidationError extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } } exports["default"] = ValidationError; //# sourceMappingURL=validation_error.js.map /***/ }, /***/ 5457 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.validateAdditionalItems = void 0; const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const error = { message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, }; const def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); }, }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._) `${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._) `${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports.validateAdditionalItems = validateAdditionalItems; exports["default"] = def; //# sourceMappingURL=additionalItems.js.map /***/ }, /***/ 8660 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const code_1 = __webpack_require__(5765); const codegen_1 = __webpack_require__(9029); const names_1 = __webpack_require__(2023); const util_1 = __webpack_require__(4227); const error = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`, }; const def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; /* istanbul ignore if */ if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { // TODO maybe an option instead of hard-coded 8? const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._) `delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str, }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false, }); } cxt.subschema(subschema, valid); } }, }; exports["default"] = def; //# sourceMappingURL=additionalProperties.js.map /***/ }, /***/ 5844 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const util_1 = __webpack_require__(4227); const def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); }, }; exports["default"] = def; //# sourceMappingURL=allOf.js.map /***/ }, /***/ 6505 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const code_1 = __webpack_require__(5765); const def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" }, }; exports["default"] = def; //# sourceMappingURL=anyOf.js.map /***/ }, /***/ 2661 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const error = { message: ({ params: { min, max } }) => max === undefined ? (0, codegen_1.str) `must contain at least ${min} valid item(s)` : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`, }; const def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === undefined ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._) `${data}.length`); cxt.setParams({ min, max }); if (max === undefined && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== undefined && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._) `${len} >= ${min}`; if (max !== undefined) cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === undefined && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== undefined) gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true, }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._) `${count}++`); if (max === undefined) { gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true)); } } }, }; exports["default"] = def; //# sourceMappingURL=contains.js.map /***/ }, /***/ 3025 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); __webpack_unused_export__ = __webpack_unused_export__ = exports.z3 = void 0; const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const code_1 = __webpack_require__(5765); exports.z3 = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}`, // TODO change to reference }; const def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports.z3, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); }, }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", "), }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } __webpack_unused_export__ = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } __webpack_unused_export__ = validateSchemaDeps; exports["default"] = def; //# sourceMappingURL=dependencies.js.map /***/ }, /***/ 1239 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const error = { message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`, }; const def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === undefined && parentSchema.else === undefined) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false, }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._) `${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } }, }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema); } exports["default"] = def; //# sourceMappingURL=if.js.map /***/ }, /***/ 6378 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const additionalItems_1 = __webpack_require__(5457); const prefixItems_1 = __webpack_require__(5354); const items_1 = __webpack_require__(494); const items2020_1 = __webpack_require__(3966); const contains_1 = __webpack_require__(2661); const dependencies_1 = __webpack_require__(3025); const propertyNames_1 = __webpack_require__(9713); const additionalProperties_1 = __webpack_require__(8660); const properties_1 = __webpack_require__(117); const patternProperties_1 = __webpack_require__(5333); const not_1 = __webpack_require__(7923); const anyOf_1 = __webpack_require__(6505); const oneOf_1 = __webpack_require__(6163); const allOf_1 = __webpack_require__(5844); const if_1 = __webpack_require__(1239); const thenElse_1 = __webpack_require__(4426); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default, ]; // array if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports["default"] = getApplicator; //# sourceMappingURL=index.js.map /***/ }, /***/ 494 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.validateTuple = void 0; const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const code_1 = __webpack_require__(5765); const def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); }, }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._) `${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i, }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports.validateTuple = validateTuple; exports["default"] = def; //# sourceMappingURL=items.js.map /***/ }, /***/ 3966 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const code_1 = __webpack_require__(5765); const additionalItems_1 = __webpack_require__(5457); const error = { message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, }; const def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); }, }; exports["default"] = def; //# sourceMappingURL=items2020.js.map /***/ }, /***/ 7923 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const util_1 = __webpack_require__(4227); const def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false, }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" }, }; exports["default"] = def; //# sourceMappingURL=not.js.map /***/ }, /***/ 6163 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const error = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`, }; const def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error, code(cxt) { const { gen, schema, parentSchema, it } = cxt; /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true, }, schValid); } if (i > 0) { gen .if((0, codegen_1._) `${schValid} && ${valid}`) .assign(valid, false) .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`) .else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } }, }; exports["default"] = def; //# sourceMappingURL=oneOf.js.map /***/ }, /***/ 5333 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const code_1 = __webpack_require__(5765); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const util_2 = __webpack_require__(4227); const def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || (alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true))) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); // TODO var validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str, }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._) `${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) // or if all properties were evaluated (props === true) gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } }, }; exports["default"] = def; //# sourceMappingURL=patternProperties.js.map /***/ }, /***/ 5354 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const items_1 = __webpack_require__(494); const def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items"), }; exports["default"] = def; //# sourceMappingURL=prefixItems.js.map /***/ }, /***/ 117 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const validate_1 = __webpack_require__(2586); const code_1 = __webpack_require__(5765); const util_1 = __webpack_require__(4227); const additionalProperties_1 = __webpack_require__(8660); const def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop, }, valid); } }, }; exports["default"] = def; //# sourceMappingURL=properties.js.map /***/ }, /***/ 9713 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const error = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`, }; const def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true, }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); }, }; exports["default"] = def; //# sourceMappingURL=propertyNames.js.map /***/ }, /***/ 4426 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const util_1 = __webpack_require__(4227); const def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === undefined) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); }, }; exports["default"] = def; //# sourceMappingURL=thenElse.js.map /***/ }, /***/ 5765 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = __webpack_unused_export__ = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = __webpack_unused_export__ = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const names_1 = __webpack_require__(2023); const util_2 = __webpack_require__(4227); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true); cxt.error(); }); } exports.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`))); } exports.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._) `Object.prototype.hasOwnProperty`, }); } __webpack_unused_export__ = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`; } exports.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } __webpack_unused_export__ = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData], ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`; } exports.callValidateCode = callValidateCode; const newRegExp = (0, codegen_1._) `new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`, }); } exports.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._) `${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num, }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it } = cxt; /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true, }, schValid); gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) // or if all properties and items were evaluated (it.props === true && it.items === true) if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports.validateUnion = validateUnion; //# sourceMappingURL=code.js.map /***/ }, /***/ 3463 (__unused_webpack_module, exports) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); }, }; exports["default"] = def; //# sourceMappingURL=id.js.map /***/ }, /***/ 2128 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const id_1 = __webpack_require__(3463); const ref_1 = __webpack_require__(3693); const core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default, ]; exports["default"] = core; //# sourceMappingURL=index.js.map /***/ }, /***/ 3693 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); __webpack_unused_export__ = __webpack_unused_export__ = void 0; const ref_error_1 = __webpack_require__(4551); const code_1 = __webpack_require__(5765); const codegen_1 = __webpack_require__(9029); const names_1 = __webpack_require__(2023); const compile_1 = __webpack_require__(3835); const util_1 = __webpack_require__(4227); const def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === undefined) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref, }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } }, }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`; } __webpack_unused_export__ = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._) `${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a; if (!it.opts.unevaluated) return; const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; // TODO refactor if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== undefined) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== undefined) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } __webpack_unused_export__ = callRef; exports["default"] = def; //# sourceMappingURL=ref.js.map /***/ }, /***/ 6653 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const types_1 = __webpack_require__(7652); const compile_1 = __webpack_require__(3835); const ref_error_1 = __webpack_require__(4551); const util_1 = __webpack_require__(4227); const error = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, }; const def = { keyword: "discriminator", type: "object", schemaType: "object", error, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === undefined) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required }) { return Array.isArray(required) && required.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } }, }; exports["default"] = def; //# sourceMappingURL=index.js.map /***/ }, /***/ 7652 (__unused_webpack_module, exports) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.DiscrError = void 0; var DiscrError; (function (DiscrError) { DiscrError["Tag"] = "tag"; DiscrError["Mapping"] = "mapping"; })(DiscrError || (exports.DiscrError = DiscrError = {})); //# sourceMappingURL=types.js.map /***/ }, /***/ 6144 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const core_1 = __webpack_require__(2128); const validation_1 = __webpack_require__(7060); const applicator_1 = __webpack_require__(6378); const format_1 = __webpack_require__(7532); const metadata_1 = __webpack_require__(9857); const draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary, ]; exports["default"] = draft7Vocabularies; //# sourceMappingURL=draft7.js.map /***/ }, /***/ 4737 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const error = { message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`, }; const def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats, }); const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); // TODO simplify gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._) `${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._) `${format}(${data})`; const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : undefined; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._) `await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`; } } }, }; exports["default"] = def; //# sourceMappingURL=format.js.map /***/ }, /***/ 7532 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const format_1 = __webpack_require__(4737); const format = [format_1.default]; exports["default"] = format; //# sourceMappingURL=index.js.map /***/ }, /***/ 9857 (__unused_webpack_module, exports) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); exports.contentVocabulary = exports.metadataVocabulary = void 0; exports.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples", ]; exports.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema", ]; //# sourceMappingURL=metadata.js.map /***/ }, /***/ 7935 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const equal_1 = __webpack_require__(6250); const error = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`, }; const def = { keyword: "const", $data: true, error, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || (schema && typeof schema == "object")) { cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._) `${schema} !== ${data}`); } }, }; exports["default"] = def; //# sourceMappingURL=const.js.map /***/ }, /***/ 8643 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const equal_1 = __webpack_require__(6250); const error = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`, }; const def = { keyword: "enum", schemaType: "array", $data: true, error, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default))); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._) `${data} === ${sch}`; } }, }; exports["default"] = def; //# sourceMappingURL=enum.js.map /***/ }, /***/ 7060 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const limitNumber_1 = __webpack_require__(5882); const multipleOf_1 = __webpack_require__(3439); const limitLength_1 = __webpack_require__(7307); const pattern_1 = __webpack_require__(422); const limitProperties_1 = __webpack_require__(4486); const required_1 = __webpack_require__(4003); const limitItems_1 = __webpack_require__(1163); const uniqueItems_1 = __webpack_require__(617); const const_1 = __webpack_require__(7935); const enum_1 = __webpack_require__(8643); const validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default, ]; exports["default"] = validation; //# sourceMappingURL=index.js.map /***/ }, /***/ 1163 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const error = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, }; const def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`); }, }; exports["default"] = def; //# sourceMappingURL=limitItems.js.map /***/ }, /***/ 7307 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const ucs2length_1 = __webpack_require__(3853); const error = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, }; const def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`); }, }; exports["default"] = def; //# sourceMappingURL=limitLength.js.map /***/ }, /***/ 5882 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const ops = codegen_1.operators; const KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, }; const error = { message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, }; const def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); }, }; exports["default"] = def; //# sourceMappingURL=limitNumber.js.map /***/ }, /***/ 4486 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const error = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, }; const def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`); }, }; exports["default"] = def; //# sourceMappingURL=limitProperties.js.map /***/ }, /***/ 3439 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const codegen_1 = __webpack_require__(9029); const error = { message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`, }; const def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error, code(cxt) { const { gen, data, schemaCode, it } = cxt; // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data) const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._) `${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); }, }; exports["default"] = def; //# sourceMappingURL=multipleOf.js.map /***/ }, /***/ 422 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const code_1 = __webpack_require__(5765); const util_1 = __webpack_require__(4227); const codegen_1 = __webpack_require__(9029); const error = { message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`, }; const def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; if ($data) { const { regExp } = it.opts.code; const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp); const valid = gen.let("valid"); gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); cxt.fail$data((0, codegen_1._) `!${valid}`); } else { const regExp = (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`); } }, }; exports["default"] = def; //# sourceMappingURL=pattern.js.map /***/ }, /***/ 4003 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const code_1 = __webpack_require__(5765); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const error = { message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`, }; const def = { keyword: "required", type: "object", schemaType: "array", $data: true, error, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } }, }; exports["default"] = def; //# sourceMappingURL=required.js.map /***/ }, /***/ 617 (__unused_webpack_module, exports, __webpack_require__) { var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const dataType_1 = __webpack_require__(208); const codegen_1 = __webpack_require__(9029); const util_1 = __webpack_require__(4227); const equal_1 = __webpack_require__(6250); const error = { message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`, }; const def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._) `${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._) `{}`); gen.for((0, codegen_1._) `;${i}--;`, () => { gen.let(item, (0, codegen_1._) `${data}[${i}]`); gen.if(wrongType, (0, codegen_1._) `continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`); gen .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._) `${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }) .code((0, codegen_1._) `${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } }, }; exports["default"] = def; //# sourceMappingURL=uniqueItems.js.map /***/ }, /***/ 2017 (module) { // do not edit .js files directly - edit src/index.jst module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; }; /***/ }, /***/ 7106 (module) { var traverse = module.exports = function (schema, opts, cb) { // Legacy support for v0.3.1 and earlier. if (typeof opts == 'function') { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; var post = cb.post || function() {}; _traverse(opts, pre, post, schema, '', schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == 'object' && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i=0; i<sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == 'object') { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) { _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, '~0').replace(/\//g, '~1'); } /***/ }, /***/ 8343 (module, __unused_webpack_exports, __webpack_require__) { const { normalizeIPv6, removeDotSegments, removeDotSegmentsRelative, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = __webpack_require__(4834) const { SCHEMES, getSchemeHandler } = __webpack_require__(343) const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u const MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.' const MALFORMED_HOST_ERROR = 'URI host is malformed.' // ASCII characters outside the RFC 3986 reg-name set (unreserved, sub-delims // and "%" for pct-encoded): C0 controls, space, DEL, and "#/:<>?@[\]^`{|}. const FORBIDDEN_DOMAIN_HOST_CHARACTER = /[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u /** * RFC 3986 section 3.1 does not allow percent-encoding in a scheme, so the * scheme is validated as-is and never decoded. Decoding would let inert input * such as `%6Aavascript:` become a live `javascript:` scheme. * * @param {string} scheme * @returns {string} */ function validateScheme (scheme) { const stringScheme = String(scheme) if (!VALID_SCHEME.test(stringScheme)) { throw new TypeError(MALFORMED_SCHEME_ERROR) } return stringScheme } /** * @template {import('./types/index').URIComponent|string} T * @param {T} uri * @param {import('./types/index').Options} [options] * @returns {T} */ function normalize (uri, options) { if (typeof uri === 'string') { uri = /** @type {T} */ (normalizeString(uri, options)) } else if (typeof uri === 'object') { uri = /** @type {T} */ (parse(serialize(uri, options), options)) } return uri } /** * @param {string} baseURI * @param {string} relativeURI * @param {import('./types/index').Options} [options] * @returns {string} */ function resolve (baseURI, relativeURI, options) { const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' } const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed, malformedPercentEncoding: baseMalformedPercentEncoding, malformedSchemeSpecific: baseMalformedSchemeSpecific, malformedHost: baseMalformedHost, malformedScheme: baseMalformedScheme } = parseWithStatus(baseURI, schemelessOptions) const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed, malformedPercentEncoding: relativeMalformedPercentEncoding, malformedSchemeSpecific: relativeMalformedSchemeSpecific, malformedHost: relativeMalformedHost, malformedScheme: relativeMalformedScheme } = parseWithStatus(relativeURI, schemelessOptions) if ( baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme ) { throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.') } const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true) const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme) const resolvedHost = resolved.host const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6) // Inputs are parsed scheme-neutrally, so delimiters and controls in a domain // host are only detected here, once the final scheme is known. They always // fail closed, including in percent-encoded hosts. if (hasForbiddenDomainHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)) { throw new Error(MALFORMED_HOST_ERROR) } canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP) // Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname // parser can reject them even though fast-uri preserves them safely as RFC // 3986 data. A raw non-ASCII host must still fail closed if conversion fails. const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 && !/\P{ASCII}/u.test(resolvedHost) if (resolved.error && !encodedASCIIHost) { throw new Error(resolved.error) } schemelessOptions.skipEscape = true return serialize(resolved, schemelessOptions) } /** * @param {import ('./types/index').URIComponent} base * @param {import ('./types/index').URIComponent} relative * @param {import('./types/index').Options} [options] * @param {boolean} [skipNormalization=false] * @returns {import ('./types/index').URIComponent} */ function resolveComponent (base, relative, options, skipNormalization) { /** @type {import('./types/index').URIComponent} */ const target = {} if (!skipNormalization) { base = parse(serialize(base, options), options) // normalize base component relative = parse(serialize(relative, options), options) // normalize relative component } options = options || {} if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme // target.authority = relative.authority; target.userinfo = relative.userinfo target.host = relative.host target.port = relative.port target.path = removeDotSegments(relative.path || '') target.query = relative.query } else { if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { // target.authority = relative.authority; target.userinfo = relative.userinfo target.host = relative.host target.port = relative.port target.path = removeDotSegments(relative.path || '') target.query = relative.query } else { if (!relative.path) { target.path = base.path if (relative.query !== undefined) { target.query = relative.query } else { target.query = base.query } } else { if (relative.path[0] === '/') { target.path = removeDotSegments(relative.path) } else { const baseHasAuthority = base.userinfo !== undefined || base.host !== undefined || base.port !== undefined if (baseHasAuthority && !base.path) { target.path = '/' + relative.path } else if (!base.path) { target.path = relative.path } else { target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path } target.path = base.scheme === undefined && !baseHasAuthority && target.path[0] !== '/' ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path) } target.query = relative.query } // target.authority = base.authority; target.userinfo = base.userinfo target.host = base.host target.port = base.port } target.scheme = base.scheme } target.fragment = relative.fragment return target } /** * @param {import ('./types/index').URIComponent|string} uriA * @param {import ('./types/index').URIComponent|string} uriB * @param {import ('./types/index').Options} options * @returns {boolean} */ function equal (uriA, uriB, options) { const normalizedA = normalizeComparableURI(uriA, options) const normalizedB = normalizeComparableURI(uriB, options) return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB } /** * @param {Readonly<import('./types/index').URIComponent>} cmpts * @param {import('./types/index').Options} [opts] * @returns {string} */ function serialize (cmpts, opts) { const component = { host: cmpts.host, scheme: cmpts.scheme, userinfo: cmpts.userinfo, port: cmpts.port, path: cmpts.path, query: cmpts.query, nid: cmpts.nid, nss: cmpts.nss, uuid: cmpts.uuid, fragment: cmpts.fragment, reference: cmpts.reference, resourceName: cmpts.resourceName, secure: cmpts.secure, error: '' } const options = Object.assign({}, opts) const uriTokens = [] if (component.scheme) { component.scheme = validateScheme(component.scheme) } // find scheme handler const schemeHandler = getSchemeHandler(options.scheme || component.scheme) // perform scheme specific serialization if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options) const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined // A reference with no emitted scheme is path-noscheme: a bare ':' in its // first path segment would reparse as a scheme (RFC 3986 3.3/4.2). Enforced // under skipEscape too (resolve()), so the reapply below gates on this flag. const schemelessReference = (component.scheme === undefined || options.reference === 'suffix') && !hasAuthority const pathNoScheme = !options.skipEscape && schemelessReference if (component.path !== undefined) { if (!options.skipEscape) { component.path = serializePathEncoding(component.path, pathNoScheme) } else { component.path = normalizePercentEncoding(component.path) } } if (options.reference !== 'suffix' && component.scheme) { // Scheme handlers may replace the scheme during serialization. component.scheme = validateScheme(component.scheme) uriTokens.push(component.scheme, ':') } const authority = recomposeAuthority(component) if (authority !== undefined) { if (options.reference !== 'suffix') { uriTokens.push('//') } uriTokens.push(authority) if (component.path && component.path[0] !== '/') { uriTokens.push('/') } } if (component.path !== undefined) { let s = component.path if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { // A relative-path reference keeps its unresolvable leading ".." segments // and must never become root-relative (RFC 3986 section 5.2.4 applies to // merged target paths, not to the reference itself). s = schemelessReference && s[0] !== '/' ? removeDotSegmentsRelative(s) : removeDotSegments(s) } // Dot-segment removal can expose a colon that was not originally in the // first segment (for example, "./a:b"). Reapply path-noscheme encoding so // the serialized relative reference cannot be reparsed as a URI scheme. if (schemelessReference) { s = serializePathEncoding(s, true) } if ( authority === undefined && s[0] === '/' && s[1] === '/' ) { // don't allow the path to start with "//" s = '/%2F' + s.slice(2) } uriTokens.push(s) } if (component.query !== undefined) { uriTokens.push('?', encodeQuery(component.query)) } if (component.fragment !== undefined) { uriTokens.push('#', encodeFragment(component.fragment)) } return uriTokens.join('') } const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u // Captures the authority component (between "//" and the next "/", "?" or "#"), // with or without a scheme prefix, for the literal-backslash rejection below. const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/ // Captures the leading authority-introducer region after an optional scheme: a // run of forward slashes, backslashes, and the characters the WHATWG URL parser // removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer // is exactly "//". Node treats "\" as "/" on special schemes and strips those // characters first, so forms like "\\", "/\", "\/", "/<TAB>/", or a leading // "<TAB>//" reach an authority in Node while fast-uri's URI_PARSE folds them into // the path group (host confusion / SSRF / redirect bypass). const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/ /** * @param {import('./types/index').URIComponent} parsed * @param {RegExpMatchArray} matches * @returns {string|undefined} */ function getParseError (parsed, matches) { if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') { return 'URI path must start with "/" when authority is present.' } if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) { return 'URI port is malformed.' } return undefined } /** * Checks percent syntax without decoding the represented octets. RFC 3986 * percent-encoding is byte-oriented, so sequences such as `%FF` are valid even * though they are not independently valid UTF-8. * * @param {string|undefined} component * @returns {boolean} */ function hasMalformedPercentEncoding (component) { if (component === undefined) return false let percent = component.indexOf('%') while (percent !== -1) { if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) { return true } percent = component.indexOf('%', percent + 3) } return false } /** * Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`). * An unterminated `[` is not a literal, so it must still be validated as a * reg-name instead of being waved through as an IP. * * @param {string} host * @returns {boolean} */ function isIPLiteral (host) { return host[0] === '[' && host[host.length - 1] === ']' } /** * @param {RegExpMatchArray} matches * @returns {boolean} */ function hasMalformedComponentPercentEncoding (matches) { // Bracketed IP literals use a raw "%" as the zone separator for historical // compatibility. Their parsing is intentionally left to normalizeIPv6. const host = matches[4] return hasMalformedPercentEncoding(matches[3]) || (host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]) } /** * @param {import('./types/index').URIComponent} parsed * @param {import('./types/index').Options} options * @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler * @param {boolean} isIP * @returns {boolean} whether host conversion failed */ function canonicalizeHost (parsed, options, schemeHandler, isIP) { if (hasForbiddenDomainHost(parsed, options, schemeHandler, isIP)) { parsed.error = parsed.error || MALFORMED_HOST_ERROR return true } if ( !options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host) ) { let url try { url = new URL('http://' + parsed.host) } catch (e) { parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e return true } // The WHATWG parser must have read the whole input as a host. Anything // else means it found a delimiter fast-uri did not, so its hostname would // describe a different authority. if (!isHostOnlyURL(url)) { parsed.error = parsed.error || MALFORMED_HOST_ERROR return true } parsed.host = url.hostname } return false } /** * Whether a domain host contains an ASCII character that RFC 3986 does not * allow in a reg-name (unreserved, sub-delims, or pct-encoded). Such a host is * rejected instead of being handed to the WHATWG URL parser, which would treat * "@" as a userinfo delimiter (silently dropping the data before it) and strip * TAB, LF, and CR. Non-ASCII characters remain allowed for IDNs. * * @param {import('./types/index').URIComponent} parsed * @param {import('./types/index').Options} options * @param {{ domainHost?: boolean }|undefined} schemeHandler * @param {boolean} isIP * @returns {boolean} */ function hasForbiddenDomainHost (parsed, options, schemeHandler, isIP) { return Boolean( parsed.host && isIP === false && !isIPLiteral(parsed.host) && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && FORBIDDEN_DOMAIN_HOST_CHARACTER.test(parsed.host) ) } /** * @param {URL} url * @returns {boolean} */ function isHostOnlyURL (url) { return url.username === '' && url.password === '' && url.port === '' && url.pathname === '/' && url.search === '' && url.hash === '' && url.hostname !== '' } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }} */ function parseWithStatus (uri, opts) { const options = Object.assign({}, opts) /** @type {import('./types/index').URIComponent} */ const parsed = { scheme: undefined, userinfo: undefined, host: '', port: undefined, path: '', query: undefined, fragment: undefined } let malformedAuthorityOrPort = false let malformedPercentEncoding = false let malformedSchemeSpecific = false let malformedHost = false let malformedIPLiteral = false let malformedScheme = false let isIP = false if (options.reference === 'suffix') { if (options.scheme) { uri = options.scheme + ':' + uri } else { uri = '//' + uri } } // A literal backslash (U+005C) is not a valid RFC 3986 URI character and is // not an authority delimiter. Reject it in the authority rather than // rewriting it: normalizing "\" -> "/" (WHATWG error recovery) could silently // change the resource identified by an otherwise-invalid input, and lets "\" // act as a host delimiter here while Node's native URL parses a different // host (SSRF / redirect / origin-allowlist bypass). Percent-encoded %5C is // untouched and remains valid encoded data. const authorityMatch = uri.match(AUTHORITY_PREFIX) if (authorityMatch !== null && authorityMatch[1].indexOf('\\') !== -1) { parsed.error = 'URI authority must not contain a literal backslash.' malformedAuthorityOrPort = true } // Reject a malformed or whitespace-smuggled authority introducer. fast-uri // only recognizes a literal "//"; anything else in the leading separator run // (a backslash, or a "//" that appears only after removing the TAB/LF/CR that // Node strips) means the authority fast-uri parses differs from the one Node's // URL resolves. Reject rather than rewrite, mirroring the literal-backslash // guard above. Percent-encoded forms (%5C, %09) are untouched, valid data. const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION) if (introducerMatch !== null) { const region = introducerMatch[1] const normalizedRegion = region.replace(/[\t\n\r]/g, '') // Two or more leading separators introduce an authority. if (normalizedRegion.length >= 2) { if (normalizedRegion.slice(0, 2) !== '//') { parsed.error = parsed.error || 'URI authority must not contain a literal backslash.' malformedAuthorityOrPort = true } else if (region.length !== normalizedRegion.length) { parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.' malformedAuthorityOrPort = true } } } const matches = uri.match(URI_PARSE) if (matches) { // store each component parsed.scheme = matches[1] parsed.userinfo = matches[3] parsed.host = matches[4] parsed.port = parseInt(matches[5], 10) parsed.path = matches[6] || '' parsed.query = matches[7] parsed.fragment = matches[8] if (parsed.scheme !== undefined) { if (VALID_SCHEME.test(parsed.scheme)) { parsed.scheme = parsed.scheme.toLowerCase() } else { parsed.error = parsed.error || MALFORMED_SCHEME_ERROR malformedScheme = true } } malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches) if (malformedPercentEncoding) { parsed.error = parsed.error || 'URI contains malformed percent-encoding.' } // fix port number if (isNaN(parsed.port)) { parsed.port = matches[5] } const parseError = getParseError(parsed, matches) if (parseError !== undefined) { parsed.error = parsed.error || parseError malformedAuthorityOrPort = true } if (parsed.host) { const ipv4result = isIPv4(parsed.host) if (ipv4result === false) { const bracketedIPLiteral = isIPLiteral(parsed.host) const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1 const ipv6result = normalizeIPv6(parsed.host) isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true) parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase() if (malformedIPLiteral) { parsed.error = parsed.error || MALFORMED_HOST_ERROR malformedAuthorityOrPort = true } } else { isIP = true } } if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) { parsed.reference = 'same-document' } else if (parsed.scheme === undefined) { parsed.reference = 'relative' } else if (parsed.fragment === undefined) { parsed.reference = 'absolute' } else { parsed.reference = 'uri' } // check for reference errors if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) { parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.' } // find scheme handler const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme) // convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts if (!malformedIPLiteral) { malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP) } if (uri.indexOf('%') !== -1 && parsed.host !== undefined && !malformedIPLiteral) { let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true) if (!isIP) { // Fold reg-name case after decoding unreserved octets. The second // pass only restores uppercase hex in escapes that remain encoded. host = normalizePercentEncoding(host.toLowerCase()) } // Resolution parses both inputs with the internal `null` scheme before // the effective scheme is known. Keep raw host delimiters for that step // so resolve() can reject them for domain-host schemes; the resolved // authority is encoded when it is serialized. parsed.host = isIP || options.scheme !== 'null' ? reescapeHostDelimiters(host, isIP) : host } if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) { if (parsed.path) { parsed.path = normalizePathEncoding(parsed.path) } if (parsed.query) { parsed.query = normalizeQueryFragmentEncoding(parsed.query) } if (parsed.fragment) { parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment) } } // perform scheme specific parsing if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(parsed, options) if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) { malformedSchemeSpecific = true } } } else { parsed.error = parsed.error || 'URI can not be parsed.' } return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns */ function parse (uri, opts) { return parseWithStatus(uri, opts).parsed } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns {string} */ function normalizeString (uri, opts) { return normalizeStringWithStatus(uri, opts).normalized } /** * @param {string} uri * @param {import('./types/index').Options} [opts] * @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }} */ function normalizeStringWithStatus (uri, opts) { const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts) return { normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts), malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } } /** * @param {import ('./types/index').URIComponent|string} uri * @param {import('./types/index').Options} [opts] * @returns {string|undefined} */ function normalizeComparableURI (uri, opts) { if (typeof uri !== 'string' && typeof uri !== 'object') { return undefined } let value try { value = typeof uri === 'string' ? uri : serialize(uri, opts) } catch { return undefined } const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts) return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized } const fastUri = { SCHEMES, normalize, resolve, resolveComponent, equal, serialize, parse } module.exports = fastUri module.exports["default"] = fastUri module.exports.fastUri = fastUri /***/ }, /***/ 343 (module, __unused_webpack_exports, __webpack_require__) { const { isUUID } = __webpack_require__(4834) const URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu const supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws', 'wss', 'urn', 'urn:uuid']) /** @typedef {supportedSchemeNames[number]} SchemeName */ /** * @param {string} name * @returns {name is SchemeName} */ function isValidSchemeName (name) { return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1 } /** * @callback SchemeFn * @param {import('../types/index').URIComponent} component * @param {import('../types/index').Options} options * @returns {import('../types/index').URIComponent} */ /** * @typedef {Object} SchemeHandler * @property {SchemeName} scheme - The scheme name. * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. * @property {SchemeFn} parse - Function to parse the URI component for this scheme. * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. */ /** * @param {import('../types/index').URIComponent} wsComponent * @returns {boolean} */ function wsIsSecure (wsComponent) { if (wsComponent.secure === true) { return true } else if (wsComponent.secure === false) { return false } else if (wsComponent.scheme) { return ( wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') && (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') && (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S') ) } else { return false } } /** @type {SchemeFn} */ function httpParse (component) { if (!component.host) { component.error = component.error || 'HTTP URIs must have a host.' } return component } /** @type {SchemeFn} */ function httpSerialize (component) { const secure = String(component.scheme).toLowerCase() === 'https' // normalize the default port if (component.port === (secure ? 443 : 80) || component.port === '') { component.port = undefined } // normalize the empty path if (!component.path) { component.path = '/' } // NOTE: We do not parse query strings for HTTP URIs // as WWW Form Url Encoded query strings are part of the HTML4+ spec, // and not the HTTP spec. return component } /** @type {SchemeFn} */ function wsParse (wsComponent) { // indicate if the secure flag is set wsComponent.secure = wsIsSecure(wsComponent) // construct resouce name wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '') wsComponent.path = undefined wsComponent.query = undefined return wsComponent } /** @type {SchemeFn} */ function wsSerialize (wsComponent) { // normalize the default port if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') { wsComponent.port = undefined } // ensure scheme matches secure flag if (typeof wsComponent.secure === 'boolean') { wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws') wsComponent.secure = undefined } // reconstruct path from resource name if (wsComponent.resourceName) { const queryIndex = wsComponent.resourceName.indexOf('?') const path = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex) wsComponent.path = (path && path !== '/' ? path : undefined) wsComponent.query = queryIndex === -1 ? undefined : wsComponent.resourceName.slice(queryIndex + 1) wsComponent.resourceName = undefined } // forbid fragment component wsComponent.fragment = undefined return wsComponent } /** @type {SchemeFn} */ function urnParse (urnComponent, options) { if (!urnComponent.path) { urnComponent.error = 'URN can not be parsed' return urnComponent } const matches = urnComponent.path.match(URN_REG) if (matches && matches[0] === urnComponent.path) { const scheme = options.scheme || urnComponent.scheme || 'urn' urnComponent.nid = matches[1].toLowerCase() urnComponent.nss = matches[2] const urnScheme = `${scheme}:${options.nid || urnComponent.nid}` const schemeHandler = getSchemeHandler(urnScheme) urnComponent.path = undefined if (schemeHandler) { urnComponent = schemeHandler.parse(urnComponent, options) } } else { urnComponent.error = urnComponent.error || 'URN can not be parsed.' } return urnComponent } /** @type {SchemeFn} */ function urnSerialize (urnComponent, options) { if (urnComponent.nid === undefined) { throw new Error('URN without nid cannot be serialized') } const scheme = options.scheme || urnComponent.scheme || 'urn' const nid = urnComponent.nid.toLowerCase() const urnScheme = `${scheme}:${options.nid || nid}` const schemeHandler = getSchemeHandler(urnScheme) if (schemeHandler) { urnComponent = schemeHandler.serialize(urnComponent, options) } const uriComponent = urnComponent const nss = urnComponent.nss uriComponent.path = `${nid || options.nid}:${nss}` options.skipEscape = true return uriComponent } /** @type {SchemeFn} */ function urnuuidParse (urnComponent, options) { const uuidComponent = urnComponent uuidComponent.uuid = uuidComponent.nss uuidComponent.nss = undefined if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { uuidComponent.error = uuidComponent.error || 'UUID is not valid.' } return uuidComponent } /** @type {SchemeFn} */ function urnuuidSerialize (uuidComponent) { const urnComponent = uuidComponent // normalize UUID urnComponent.nss = (uuidComponent.uuid || '').toLowerCase() return urnComponent } const http = /** @type {SchemeHandler} */ ({ scheme: 'http', domainHost: true, parse: httpParse, serialize: httpSerialize }) const https = /** @type {SchemeHandler} */ ({ scheme: 'https', domainHost: http.domainHost, parse: httpParse, serialize: httpSerialize }) const ws = /** @type {SchemeHandler} */ ({ scheme: 'ws', domainHost: true, parse: wsParse, serialize: wsSerialize }) const wss = /** @type {SchemeHandler} */ ({ scheme: 'wss', domainHost: ws.domainHost, parse: ws.parse, serialize: ws.serialize }) const urn = /** @type {SchemeHandler} */ ({ scheme: 'urn', parse: urnParse, serialize: urnSerialize, skipNormalize: true }) const urnuuid = /** @type {SchemeHandler} */ ({ scheme: 'urn:uuid', parse: urnuuidParse, serialize: urnuuidSerialize, skipNormalize: true }) const SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({ http, https, ws, wss, urn, 'urn:uuid': urnuuid }) Object.setPrototypeOf(SCHEMES, null) /** * @param {string|undefined} scheme * @returns {SchemeHandler|undefined} */ function getSchemeHandler (scheme) { return ( scheme && ( SCHEMES[/** @type {SchemeName} */ (scheme)] || SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())]) ) || undefined } module.exports = { wsIsSecure, SCHEMES, isValidSchemeName, getSchemeHandler, } /***/ }, /***/ 4834 (module) { /** @type {(value: string) => boolean} */ const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu) /** @type {(value: string) => boolean} */ const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u) /** @type {(value: string) => boolean} */ const isPort = RegExp.prototype.test.bind(/^\d*$/u) /** @type {(value: string) => boolean} */ const isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu) /** @type {(value: string) => boolean} */ const isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu) /** @type {(value: string) => boolean} */ const isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u) /** @type {(value: string) => boolean} */ const isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u) /** @type {(value: string) => boolean} */ const isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u) const BYTE_HEX = new Array(256) { const HEX_DIGITS = '0123456789ABCDEF' for (let i = 0; i < 256; i++) { BYTE_HEX[i] = '%' + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 0xF] } } function percentEncodeNonAscii (cp) { if (cp < 0x800) { return BYTE_HEX[0xC0 | (cp >> 6)] + BYTE_HEX[0x80 | (cp & 0x3F)] } if (cp < 0x10000) { return BYTE_HEX[0xE0 | (cp >> 12)] + BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] + BYTE_HEX[0x80 | (cp & 0x3F)] } return BYTE_HEX[0xF0 | (cp >> 18)] + BYTE_HEX[0x80 | ((cp >> 12) & 0x3F)] + BYTE_HEX[0x80 | ((cp >> 6) & 0x3F)] + BYTE_HEX[0x80 | (cp & 0x3F)] } /** * @param {Array<string>} input * @returns {string} */ function stringArrayToHexStripped (input) { let acc = '' let code = 0 let i = 0 for (i = 0; i < input.length; i++) { code = input[i].charCodeAt(0) if (code === 48) { continue } if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) { return '' } acc += input[i] break } for (i += 1; i < input.length; i++) { code = input[i].charCodeAt(0) if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) { return '' } acc += input[i] } return acc } /** @type {(value: string) => boolean} */ const isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/) /** @type {(value: string) => boolean} */ const isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/) /** @type {(value: string) => boolean} */ const isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/) /** * @param {string} value * @returns {boolean} */ const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u) /** * @param {string} zone * @returns {boolean} */ function isZoneIdentifier (zone) { if (zone.length === 0) return false for (let i = 0; i < zone.length; i++) { if (isZoneCharacter(zone[i])) continue if (zone[i] === '%' && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) { i += 2 continue } return false } return true } /** * Compresses the longest run of zero hextets to "::" per RFC 5952. A run of a * single zero hextet is left uncompressed. On ties the leftmost run wins. * * @param {string[]} hextets * @returns {string} */ function compressIPv6ZeroRun (hextets) { let bestStart = -1 let bestLength = 0 let runStart = -1 let runLength = 0 for (let i = 0; i < hextets.length; i++) { if (hextets[i] === '0') { if (runStart === -1) runStart = i runLength++ if (runLength > bestLength) { bestLength = runLength bestStart = runStart } } else { runStart = -1 runLength = 0 } } if (bestLength < 2) return hextets.join(':') const head = hextets.slice(0, bestStart).join(':') const tail = hextets.slice(bestStart + bestLength).join(':') return head + '::' + tail } /** * Validates an IPv6 address against the alternatives in RFC 3986 section * 3.2.2 and returns the same address with leading hextet zeroes removed. * An embedded IPv4 address counts as two hextets and is only valid at the end. * * @param {string} input * @returns {string|undefined} */ function normalizeIPv6Address (input) { const compression = input.indexOf('::') if (compression !== -1 && input.indexOf('::', compression + 1) !== -1) return undefined const left = compression === -1 ? input.split(':') : input.slice(0, compression).split(':') const right = compression === -1 ? [] : input.slice(compression + 2).split(':') if (compression !== -1) { if (left.length === 1 && left[0] === '') left.length = 0 if (right.length === 1 && right[0] === '') right.length = 0 } const parts = left.concat(right) let hextetCount = 0 for (let i = 0; i < parts.length; i++) { const part = parts[i] if (part === '') return undefined if (part.indexOf('.') !== -1) { if (i !== parts.length - 1 || (compression !== -1 && right.length === 0) || !isIPv4(part)) return undefined hextetCount += 2 continue } if (!isHextet(part)) return undefined parts[i] = parseInt(part, 16).toString(16) hextetCount++ } if (compression === -1) { if (hextetCount !== 8) return undefined return compressIPv6ZeroRun(parts) } if (hextetCount >= 8) return undefined // expand "::" then re-compress the longest run for a canonical result const expanded = parts.slice(0, left.length) for (let i = hextetCount; i < 8; i++) expanded.push('0') for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]) return compressIPv6ZeroRun(expanded) } /** * @typedef {Object} NormalizeIPv6Result * @property {string} host - The normalized host. * @property {string} [escapedHost] - The escaped host. * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. * @property {boolean} [isIPVFuture] - Indicates if the host is an IPvFuture literal. * @property {boolean} [error] - Indicates if a bracketed IP literal is malformed. */ /** * Validates and normalizes a bracketed IP literal. Raw zone separators remain * accepted for backwards compatibility, while encoded separators and zone * contents follow RFC 6874. * * @param {string} host * @returns {NormalizeIPv6Result} */ function normalizeIPv6 (host) { const bracketed = host[0] === '[' && host[host.length - 1] === ']' const hasBracket = host[0] === '[' || host[host.length - 1] === ']' if (hasBracket && !bracketed) return { host, isIPV6: false, error: true } let input = bracketed ? host.slice(1, -1) : host if (bracketed && isIPvFuture(input)) { input = input.toLowerCase() return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true } } if (findToken(input, ':') < 2) { return { host, isIPV6: false, error: bracketed } } let zoneIdentifier = '' const zoneSeparator = input.indexOf('%') if (zoneSeparator !== -1) { const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === '%25' ? 3 : 1 zoneIdentifier = input.slice(zoneSeparator + separatorLength) if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true } input = input.slice(0, zoneSeparator) } const address = normalizeIPv6Address(input) if (address === undefined) return { host, isIPV6: false, error: true } return { host: address + (zoneIdentifier ? '%' + zoneIdentifier : ''), escapedHost: address + (zoneIdentifier ? '%25' + zoneIdentifier : ''), isIPV6: true } } /** * @param {string} str * @param {string} token * @returns {number} */ function findToken (str, token) { let ind = 0 for (let i = 0; i < str.length; i++) { if (str[i] === token) ind++ } return ind } /** * @param {string} path * @returns {string} * * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 */ function removeDotSegments (path) { let input = path const output = [] let nextSlash = -1 let len = 0 // eslint-disable-next-line no-cond-assign while (len = input.length) { if (len === 1) { if (input === '.') { break } else if (input === '/') { output.push('/') break } else { output.push(input) break } } else if (len === 2) { if (input[0] === '.') { if (input[1] === '.') { break } else if (input[1] === '/') { input = input.slice(2) continue } } else if (input[0] === '/') { if (input[1] === '.' || input[1] === '/') { output.push('/') break } } } else if (len === 3) { if (input === '/..') { if (output.length !== 0) { output.pop() } output.push('/') break } } if (input[0] === '.') { if (input[1] === '.') { if (input[2] === '/') { input = input.slice(3) continue } } else if (input[1] === '/') { input = input.slice(2) continue } } else if (input[0] === '/') { if (input[1] === '.') { if (input[2] === '/') { input = input.slice(2) continue } else if (input[2] === '.') { if (input[3] === '/') { input = input.slice(3) if (output.length !== 0) { output.pop() } continue } } } } // Rule 2E: Move normal path segment to output if ((nextSlash = input.indexOf('/', 1)) === -1) { output.push(input) break } else { output.push(input.slice(0, nextSlash)) input = input.slice(nextSlash) } } return output.join('') } /** * Removes dot segments from the path of a relative reference (a path that does * not start with "/") without changing what it resolves to against any base. * Unlike `removeDotSegments`, leading ".." segments that cannot be collapsed * are kept, the result never becomes root-relative, and a result that would be * empty or start with an empty segment is prefixed with "." (an empty path * means "same document" and a leading "//" would introduce an authority). * * @param {string} path * @returns {string} */ function removeDotSegmentsRelative (path) { if (path === '' || path[0] === '/') { return removeDotSegments(path) } const segments = path.split('/') const last = segments.length - 1 /** @type {string[]} */ const output = [] let trailingDirectory = false for (let i = 0; i <= last; i++) { const segment = segments[i] if (segment === '.' || segment === '..') { if (segment === '..') { if (output.length !== 0 && output[output.length - 1] !== '..') { output.pop() } else { output.push('..') } } trailingDirectory = i === last } else { output.push(segment) } } if (trailingDirectory && output[output.length - 1] !== '..') { output.push('') } if (output.length === 0 || output[0] === '' || output[0].includes(':')) { // An empty path, a leading empty segment ("//"), or a first segment // containing ":" (which would be mistaken for a scheme, RFC 3986 section // 4.2) must stay behind a "." segment so the reference keeps its meaning. output.unshift('.') } return output.join('/') } /** * Re-escape RFC 3986 gen-delims that must not appear literally in the host. * After the URI regex parses, these characters cannot be literal in the host * field, so any that appear after decoding came from percent-encoding and * must be restored to prevent authority structure changes. * * @param {string} host * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping) * @returns {string} */ const HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' } const HOST_DELIM_RE = /[@/?#:]/g const HOST_DELIM_NO_COLON_RE = /[@/?#]/g function reescapeHostDelimiters (host, isIP) { const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE re.lastIndex = 0 return host.replace(re, (ch) => HOST_DELIMS[ch]) } /** * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes. * Reserved delimiters such as `%2F` stay escaped; `%2E` is unreserved. * * @param {string} input * @param {boolean} [decodeUnreserved=false] * @returns {string} */ function normalizePercentEncoding (input, decodeUnreserved = false) { if (input.indexOf('%') === -1) { return input } let output = '' for (let i = 0; i < input.length; i++) { if (input[i] === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { const normalizedHex = hex.toUpperCase() const decoded = String.fromCharCode(parseInt(normalizedHex, 16)) if (decodeUnreserved && isUnreserved(decoded)) { output += decoded } else { output += '%' + normalizedHex } i += 2 continue } } output += input[i] } return output } /** * Normalizes path data without turning reserved escapes into live path syntax. * Valid escapes are uppercased, raw unsafe characters are escaped, and only * unreserved bytes that are not `.` are decoded. * * @param {string} input * @returns {string} */ function normalizePathEncoding (input) { let output = '' for (let i = 0; i < input.length; i++) { const ch = input[i] if (ch === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { const normalizedHex = hex.toUpperCase() const decoded = String.fromCharCode(parseInt(normalizedHex, 16)) if (decoded !== '.' && isUnreserved(decoded)) { output += decoded } else { output += '%' + normalizedHex } i += 2 continue } } if (isPathCharacter(ch)) { output += ch } else { const code = input.charCodeAt(i) if (code < 0x80) { output += isEscapeSafe(code) ? ch : BYTE_HEX[code] } else if (code < 0xD800 || code > 0xDFFF) { output += percentEncodeNonAscii(code) } else if (code <= 0xDBFF && i + 1 < input.length) { const low = input.charCodeAt(i + 1) if (low >= 0xDC00 && low <= 0xDFFF) { output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)) i++ } else { output += percentEncodeNonAscii(0xFFFD) } } else { output += percentEncodeNonAscii(0xFFFD) } } } return output } /** * Serializes a path without rewriting reserved data. Raw RFC 3986 path * characters remain literal, valid escapes are preserved and uppercased, and * everything else is UTF-8 percent-encoded. In a path-noscheme, a colon in the * first segment must be escaped so the result cannot be parsed as a scheme. * * @param {string} input * @param {boolean} [pathNoScheme=false] * @returns {string} */ function serializePathEncoding (input, pathNoScheme = false) { let output = '' let firstSegment = pathNoScheme && input[0] !== '/' for (let i = 0; i < input.length; i++) { const ch = input[i] if (ch === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { output += '%' + hex.toUpperCase() i += 2 continue } } if (ch === '/') { firstSegment = false } if (isPathCharacter(ch) && (ch !== ':' || !firstSegment)) { output += ch } else { const code = input.charCodeAt(i) if (code < 0x80) { output += BYTE_HEX[code] } else if (code < 0xD800 || code > 0xDFFF) { output += percentEncodeNonAscii(code) } else if (code <= 0xDBFF && i + 1 < input.length) { const low = input.charCodeAt(i + 1) if (low >= 0xDC00 && low <= 0xDFFF) { output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)) i++ } else { output += percentEncodeNonAscii(0xFFFD) } } else { output += percentEncodeNonAscii(0xFFFD) } } } return output } /** * Percent-encodes a URI component using its RFC 3986 literal character set. * Existing valid escapes are preserved and normalized to uppercase hex. * * @param {string} input * @param {(value: string) => boolean} isAllowed * @returns {string} */ function encodeComponent (input, isAllowed) { let output = '' for (let i = 0; i < input.length; i++) { const ch = input[i] if (ch === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { output += '%' + hex.toUpperCase() i += 2 continue } } if (isAllowed(ch)) { output += ch } else { const code = input.charCodeAt(i) if (code < 0x80) { output += BYTE_HEX[code] } else if (code < 0xD800 || code > 0xDFFF) { output += percentEncodeNonAscii(code) } else if (code <= 0xDBFF && i + 1 < input.length) { const low = input.charCodeAt(i + 1) if (low >= 0xDC00 && low <= 0xDFFF) { output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)) i++ } else { output += percentEncodeNonAscii(0xFFFD) } } else { output += percentEncodeNonAscii(0xFFFD) } } } return output } /** * Encodes userinfo while preserving its RFC 3986 §3.2.1 literal characters. * In particular, authority delimiters such as `@`, `/`, `?`, and `#` are data. * * @param {string} input * @returns {string} */ function encodeUserinfo (input) { return encodeComponent(input, isUserinfoCharacter) } /** * Encodes query data using the RFC 3986 §3.4 grammar. A literal `#` must be * escaped because it would otherwise begin the fragment component. * * @param {string} input * @returns {string} */ function encodeQuery (input) { return encodeComponent(input, isQueryFragmentCharacter) } /** * Encodes fragment data using the RFC 3986 §3.5 grammar. * * @param {string} input * @returns {string} */ function encodeFragment (input) { return encodeComponent(input, isQueryFragmentCharacter) } function isEscapeSafe (cp) { return ( (cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x5A) || (cp >= 0x61 && cp <= 0x7A) || cp === 0x2A || cp === 0x2B || cp === 0x2D || cp === 0x2E || cp === 0x2F || cp === 0x40 || cp === 0x5F ) } /** * Normalizes the percent-encoding of a query or fragment component. * * Like `normalizePathEncoding`, but uses the query/fragment character set * (which additionally allows `?`) and decodes `.` since it has no dot-segment * meaning outside of a path. * * @param {string} input * @returns {string} */ function normalizeQueryFragmentEncoding (input) { let output = '' for (let i = 0; i < input.length; i++) { const ch = input[i] if (ch === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { const normalizedHex = hex.toUpperCase() const decoded = String.fromCharCode(parseInt(normalizedHex, 16)) if (isUnreserved(decoded)) { output += decoded } else { output += '%' + normalizedHex } i += 2 continue } } if (isQueryFragmentCharacter(ch)) { output += ch } else { const code = input.charCodeAt(i) if (code < 0x80) { output += isEscapeSafe(code) ? ch : BYTE_HEX[code] } else if (code < 0xD800 || code > 0xDFFF) { output += percentEncodeNonAscii(code) } else if (code <= 0xDBFF && i + 1 < input.length) { const low = input.charCodeAt(i + 1) if (low >= 0xDC00 && low <= 0xDFFF) { output += percentEncodeNonAscii(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)) i++ } else { output += percentEncodeNonAscii(0xFFFD) } } else { output += percentEncodeNonAscii(0xFFFD) } } } return output } /** * Escapes a component while preserving existing valid percent escapes. * * @param {string} input * @returns {string} */ function escapePreservingEscapes (input) { let output = '' for (let i = 0; i < input.length; i++) { if (input[i] === '%' && i + 2 < input.length) { const hex = input.slice(i + 1, i + 3) if (isHexPair(hex)) { output += '%' + hex.toUpperCase() i += 2 continue } } output += escape(input[i]) } return output } /** * @param {import('../types/index').URIComponent} component * @returns {string|undefined} */ function recomposeAuthority (component) { const uriTokens = [] if (component.userinfo !== undefined) { uriTokens.push(encodeUserinfo(component.userinfo)) uriTokens.push('@') } if (component.host !== undefined) { let host = component.host if (!isIPv4(host)) { let ipV6res = normalizeIPv6(host) if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) { // Decode only unreserved bytes, once. In particular, keep %25 encoded // so it cannot introduce a second escape during recomposition. host = normalizePercentEncoding(host, true) ipV6res = normalizeIPv6(host) } if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) { host = `[${ipV6res.escapedHost}]` } else { host = reescapeHostDelimiters(host, false) } } uriTokens.push(host) } if (typeof component.port === 'number' || typeof component.port === 'string') { const port = String(component.port) if (!isPort(port)) { throw new TypeError('URI port is malformed.') } uriTokens.push(':') uriTokens.push(port) } return uriTokens.length ? uriTokens.join('') : undefined }; module.exports = { nonSimpleDomain, recomposeAuthority, reescapeHostDelimiters, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeUserinfo, encodeQuery, encodeFragment, escapePreservingEscapes, removeDotSegments, removeDotSegmentsRelative, isIPv4, isUUID, normalizeIPv6, stringArrayToHexStripped } /***/ }, /***/ 3837 (module) { module.exports = /*#__PURE__*/JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}'); /***/ }, /***/ 2079 (module) { module.exports = /*#__PURE__*/JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}'); /***/ } /******/ }); /************************************************************************/ /******/ // The module cache /******/ const __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ const cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ const module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ let __webpack_exports__ = {}; ;// ./node_modules/zod/v4/core/core.js /** A special constant with type `never` */ const NEVER = Object.freeze({ status: "aborted", }); function $constructor(name, initializer, params) { function init(inst, def) { var _a; Object.defineProperty(inst, "_zod", { value: inst._zod ?? {}, enumerable: false, }); (_a = inst._zod).traits ?? (_a.traits = new Set()); inst._zod.traits.add(name); initializer(inst, def); // support prototype modifications for (const k in _.prototype) { if (!(k in inst)) Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); } inst._zod.constr = _; inst._zod.def = def; } // doesn't work if Parent has a constructor with arguments const Parent = params?.Parent ?? Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name }); function _(def) { var _a; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a = inst._zod).deferred ?? (_a.deferred = []); for (const fn of inst._zod.deferred) { fn(); } return inst; } Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { if (params?.Parent && inst instanceof params.Parent) return true; return inst?._zod?.traits?.has(name); }, }); Object.defineProperty(_, "name", { value: name }); return _; } ////////////////////////////// UTILITIES /////////////////////////////////////// const $brand = Symbol("zod_brand"); class $ZodAsyncError extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } } const globalConfig = {}; function config(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } ;// ./node_modules/zod/v4/core/regexes.js const cuid = /^[cC][^\s-]{8,}$/; const cuid2 = /^[0-9a-z]+$/; const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; const xid = /^[0-9a-vA-V]{20}$/; const ksuid = /^[A-Za-z0-9]{27}$/; const nanoid = /^[a-zA-Z0-9_-]{21}$/; /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; /** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; /** Returns a regex for validating an RFC 4122 UUID. * * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ const uuid = (version) => { if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); /** Practical email validation */ const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; /** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; /** The classic emailregex.com regex for RFC 5322-compliant emails */ const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; /** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression const _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji() { return new RegExp(_emoji, "u"); } const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; const 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})$/; const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; const base64url = /^[A-Za-z0-9_-]*$/; // based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address // export const hostname: RegExp = // /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; // https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) const e164 = /^\+(?:[0-9]){6,14}[0-9]$/; // const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } // Adapted from https://stackoverflow.com/a/3143231 function datetime(args) { const time = timeSource({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); const timeRegex = `${time}(?:${opts.join("|")})`; return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } const string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; const bigint = /^\d+n?$/; const integer = /^\d+$/; const number = /^-?\d+(?:\.\d+)?/i; const regexes_boolean = /true|false/i; const _null = /null/i; const _undefined = /undefined/i; // regex for string with no uppercase letters const lowercase = /^[^A-Z]*$/; // regex for string with no lowercase letters const uppercase = /^[^a-z]*$/; ;// ./node_modules/zod/v4/core/util.js // functions function assertEqual(val) { return val; } function assertNotEqual(val) { return val; } function assertIs(_arg) { } function assertNever(_x) { throw new Error(); } function assert(_) { } function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); const values = Object.entries(entries) .filter(([k, _]) => numericValues.indexOf(+k) === -1) .map(([_, v]) => v); return values; } function joinValues(array, separator = "|") { return array.map((val) => stringifyPrimitive(val)).join(separator); } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { const set = false; return { get value() { if (!set) { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } throw new Error("cached value already set"); }, }; } function nullish(input) { return input === null || input === undefined; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return (valInt % stepInt) / 10 ** decCount; } function defineLazy(object, key, getter) { const set = false; Object.defineProperty(object, key, { get() { if (!set) { const value = getter(); object[key] = value; return value; } throw new Error("cached value already set"); }, set(v) { Object.defineProperty(object, key, { value: v, // configurable: true, }); // object[key] = v; }, configurable: true, }); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true, }); } function getElementAtPath(obj, path) { if (!path) return obj; return path.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key) => promisesObj[key]); return Promise.all(promises).then((results) => { const resolvedObj = {}; for (let i = 0; i < keys.length; i++) { resolvedObj[keys[i]] = results[i]; } return resolvedObj; }); } function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; for (let i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } function esc(str) { return JSON.stringify(str); } const captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { }; function util_isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } const util_allowsEval = cached(() => { if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { return false; } try { const F = Function; new F(""); return true; } catch (_) { return false; } }); function isPlainObject(o) { if (util_isObject(o) === false) return false; // modified constructor const ctor = o.constructor; if (ctor === undefined) return true; // modified prototype const prot = ctor.prototype; if (util_isObject(prot) === false) return false; // ctor doesn't have static `isPrototypeOf` if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function numKeys(data) { let keyCount = 0; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { keyCount++; } } return keyCount; } const getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return "undefined"; case "string": return "string"; case "number": return Number.isNaN(data) ? "nan" : "number"; case "boolean": return "boolean"; case "function": return "function"; case "bigint": return "bigint"; case "symbol": return "symbol"; case "object": if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return "promise"; } if (typeof Map !== "undefined" && data instanceof Map) { return "map"; } if (typeof Set !== "undefined" && data instanceof Set) { return "set"; } if (typeof Date !== "undefined" && data instanceof Date) { return "date"; } if (typeof File !== "undefined" && data instanceof File) { return "file"; } return "object"; default: throw new Error(`Unknown data type: ${t}`); } }; const propertyKeyTypes = new Set(["string", "number", "symbol"]); const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } // zod-specific utils function clone(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== undefined) { if (params?.error !== undefined) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function createTransparentProxy(getter) { let target; return new Proxy({}, { get(_, prop, receiver) { target ?? (target = getter()); return Reflect.get(target, prop, receiver); }, set(_, prop, value, receiver) { target ?? (target = getter()); return Reflect.set(target, prop, value, receiver); }, has(_, prop) { target ?? (target = getter()); return Reflect.has(target, prop); }, deleteProperty(_, prop) { target ?? (target = getter()); return Reflect.deleteProperty(target, prop); }, ownKeys(_) { target ?? (target = getter()); return Reflect.ownKeys(target); }, getOwnPropertyDescriptor(_, prop) { target ?? (target = getter()); return Reflect.getOwnPropertyDescriptor(target, prop); }, defineProperty(_, prop, descriptor) { target ?? (target = getter()); return Reflect.defineProperty(target, prop, descriptor); }, }); } function stringifyPrimitive(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } const NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-3.4028234663852886e38, 3.4028234663852886e38], float64: [-Number.MAX_VALUE, Number.MAX_VALUE], }; const BIGINT_FORMAT_RANGES = (/* unused pure expression or super */ null && ({ int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], })); function pick(schema, mask) { const newShape = {}; const currDef = schema._zod.def; //.shape; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; // pick key newShape[key] = currDef.shape[key]; } return clone(schema, { ...schema._zod.def, shape: newShape, checks: [], }); } function omit(schema, mask) { const newShape = { ...schema._zod.def.shape }; const currDef = schema._zod.def; //.shape; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } return clone(schema, { ...schema._zod.def, shape: newShape, checks: [], }); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const def = { ...schema._zod.def, get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); // self-caching return _shape; }, checks: [], // delete existing checks }; return clone(schema, def); } function merge(a, b) { return clone(a, { ...a._zod.def, get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; assignProp(this, "shape", _shape); // self-caching return _shape; }, catchall: b._zod.def.catchall, checks: [], // delete existing checks }); } function partial(Class, schema, mask) { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in oldShape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; // if (oldShape[key]!._zod.optin === "optional") continue; shape[key] = Class ? new Class({ type: "optional", innerType: oldShape[key], }) : oldShape[key]; } } else { for (const key in oldShape) { // if (oldShape[key]!._zod.optin === "optional") continue; shape[key] = Class ? new Class({ type: "optional", innerType: oldShape[key], }) : oldShape[key]; } } return clone(schema, { ...schema._zod.def, shape, checks: [], }); } function required(Class, schema, mask) { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; // overwrite with non-optional shape[key] = new Class({ type: "nonoptional", innerType: oldShape[key], }); } } else { for (const key in oldShape) { // overwrite with non-optional shape[key] = new Class({ type: "nonoptional", innerType: oldShape[key], }); } } return clone(schema, { ...schema._zod.def, shape, // optional: [], checks: [], }); } function aborted(x, startIndex = 0) { for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue !== true) return true; } return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a; (_a = iss).path ?? (_a.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue(iss, ctx, config) { const full = { ...iss, path: iss.path ?? [] }; // for backwards compatibility if (!iss.message) { const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; full.message = message; } // delete (full as any).def; delete full.inst; delete full.continue; if (!ctx?.reportInput) { delete full.input; } return full; } function getSizableOrigin(input) { if (input instanceof Set) return "set"; if (input instanceof Map) return "map"; if (input instanceof File) return "file"; return "unknown"; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function util_issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst, }; } return { ...iss }; } function cleanEnum(obj) { return Object.entries(obj) .filter(([k, _]) => { // return true if NaN, meaning it's not a number, thus a string key return Number.isNaN(Number.parseInt(k, 10)); }) .map((el) => el[1]); } // instanceof class Class { constructor(..._args) { } } ;// ./node_modules/zod/v4/core/checks.js /* unused harmony import specifier */ var core; /* unused harmony import specifier */ var util; // import { $ZodType } from "./schemas.js"; const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { var _a; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a = inst._zod).onattach ?? (_a.onattach = []); }); const numericOriginMap = { number: "number", bigint: "bigint", object: "date", }; const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort, }); }; }); const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort, }); }; }); const $ZodCheckMultipleOf = /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst) => { var _a; (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ origin: typeof payload.value, code: "not_multiple_of", divisor: def.value, input: payload.value, inst, continue: !def.abort, }); }; }); const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { $ZodCheck.init(inst, def); // no format checks def.format = def.format || "float64"; const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { // invalid_format issue // payload.issues.push({ // expected: def.format, // format: def.format, // code: "invalid_format", // input, // inst, // }); // invalid_type issue payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", input, inst, }); return; // not_multiple_of issue // payload.issues.push({ // code: "not_multiple_of", // origin: "number", // input, // inst, // divisor: 1, // }); } if (!Number.isSafeInteger(input)) { if (input > 0) { // too_big payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort, }); } else { // too_small payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort, }); } return; } } if (input < minimum) { payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort, }); } if (input > maximum) { payload.issues.push({ origin: "number", input, code: "too_big", maximum, inst, }); } }; }); const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); // no format checks const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; }); inst._zod.check = (payload) => { const input = payload.value; if (input < minimum) { payload.issues.push({ origin: "bigint", input, code: "too_small", minimum: minimum, inclusive: true, inst, continue: !def.abort, }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inst, }); } }; }))); const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { var _a; $ZodCheck.init(inst, def); (_a = inst._zod.def).when ?? (_a.when = (payload) => { const val = payload.value; return !util.nullish(val) && val.size !== undefined; }); inst._zod.onattach.push((inst) => { const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size <= def.maximum) return; payload.issues.push({ origin: util.getSizableOrigin(input), code: "too_big", maximum: def.maximum, input, inst, continue: !def.abort, }); }; }))); const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { var _a; $ZodCheck.init(inst, def); (_a = inst._zod.def).when ?? (_a.when = (payload) => { const val = payload.value; return !util.nullish(val) && val.size !== undefined; }); inst._zod.onattach.push((inst) => { const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size >= def.minimum) return; payload.issues.push({ origin: util.getSizableOrigin(input), code: "too_small", minimum: def.minimum, input, inst, continue: !def.abort, }); }; }))); const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { var _a; $ZodCheck.init(inst, def); (_a = inst._zod.def).when ?? (_a.when = (payload) => { const val = payload.value; return !util.nullish(val) && val.size !== undefined; }); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.minimum = def.size; bag.maximum = def.size; bag.size = def.size; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size === def.size) return; const tooBig = size > def.size; payload.issues.push({ origin: util.getSizableOrigin(input), ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort, }); }; }))); const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a; $ZodCheck.init(inst, def); (_a = inst._zod.def).when ?? (_a.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== undefined; }); inst._zod.onattach.push((inst) => { const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length <= def.maximum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort, }); }; }); const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { var _a; $ZodCheck.init(inst, def); (_a = inst._zod.def).when ?? (_a.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== undefined; }); inst._zod.onattach.push((inst) => { const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length >= def.minimum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort, }); }; }); const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a; $ZodCheck.init(inst, def); (_a = inst._zod.def).when ?? (_a.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== undefined; }); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.minimum = def.length; bag.maximum = def.length; bag.length = def.length; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length === def.length) return; const origin = getLengthableOrigin(input); const tooBig = length > def.length; payload.issues.push({ origin, ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort, }); }; }); const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a, _b; $ZodCheck.init(inst, def); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.format = def.format; if (def.pattern) { bag.patterns ?? (bag.patterns = new Set()); bag.patterns.add(def.pattern); } }); if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: def.format, input: payload.value, ...(def.pattern ? { pattern: def.pattern.toString() } : {}), inst, continue: !def.abort, }); }); else (_b = inst._zod).check ?? (_b.check = () => { }); }); const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { $ZodCheckStringFormat.init(inst, def); inst._zod.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "regex", input: payload.value, pattern: def.pattern.toString(), inst, continue: !def.abort, }); }; }); const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { def.pattern ?? (def.pattern = lowercase); $ZodCheckStringFormat.init(inst, def); }); const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { def.pattern ?? (def.pattern = uppercase); $ZodCheckStringFormat.init(inst, def); }); const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); def.pattern = pattern; inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.patterns ?? (bag.patterns = new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: def.includes, input: payload.value, inst, continue: !def.abort, }); }; }); const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.patterns ?? (bag.patterns = new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: def.prefix, input: payload.value, inst, continue: !def.abort, }); }; }); const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.patterns ?? (bag.patterns = new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: def.suffix, input: payload.value, inst, continue: !def.abort, }); }; }); /////////////////////////////////// ///// $ZodCheckProperty ///// /////////////////////////////////// function handleCheckPropertyResult(result, payload, property) { if (result.issues.length) { payload.issues.push(...util.prefixIssues(property, result.issues)); } } const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { const result = def.schema._zod.run({ value: payload.value[def.property], issues: [], }, {}); if (result instanceof Promise) { return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); } handleCheckPropertyResult(result, payload, def.property); return; }; }))); const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); inst._zod.onattach.push((inst) => { inst._zod.bag.mime = def.mime; }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; payload.issues.push({ code: "invalid_value", values: def.mime, input: payload.value.type, inst, }); }; }))); const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); ;// ./node_modules/zod/v4/core/doc.js class Doc { constructor(args = []) { this.content = []; this.indent = 0; if (this) this.args = args; } indented(fn) { this.indent += 1; fn(this); this.indent -= 1; } write(arg) { if (typeof arg === "function") { arg(this, { execution: "sync" }); arg(this, { execution: "async" }); return; } const content = arg; const lines = content.split("\n").filter((x) => x); const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); for (const line of dedented) { this.content.push(line); } } compile() { const F = Function; const args = this?.args; const content = this?.content ?? [``]; const lines = [...content.map((x) => ` ${x}`)]; // console.log(lines.join("\n")); return new F(...args, lines.join("\n")); } } ;// ./node_modules/zod/v4/core/errors.js const initializer = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false, }); Object.defineProperty(inst, "issues", { value: def, enumerable: false, }); Object.defineProperty(inst, "message", { get() { return JSON.stringify(def, jsonStringifyReplacer, 2); }, enumerable: true, // configurable: false, }); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false, }); }; const $ZodError = $constructor("$ZodError", initializer); const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); function flattenError(error, mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } function formatError(error, _mapper) { const mapper = _mapper || function (issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union" && issue.errors.length) { issue.errors.map((issues) => processError({ issues })); } else if (issue.code === "invalid_key") { processError({ issues: issue.issues }); } else if (issue.code === "invalid_element") { processError({ issues: issue.issues }); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(error); return fieldErrors; } function treeifyError(error, _mapper) { const mapper = _mapper || function (issue) { return issue.message; }; const result = { errors: [] }; const processError = (error, path = []) => { var _a, _b; for (const issue of error.issues) { if (issue.code === "invalid_union" && issue.errors.length) { // regular union error issue.errors.map((issues) => processError({ issues }, issue.path)); } else if (issue.code === "invalid_key") { processError({ issues: issue.issues }, issue.path); } else if (issue.code === "invalid_element") { processError({ issues: issue.issues }, issue.path); } else { const fullpath = [...path, ...issue.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue)); continue; } let curr = result; let i = 0; while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue)); } i++; } } } }; processError(error); return result; } /** Format a ZodError as a human-readable string in the following form. * * From * * ```ts * ZodError { * issues: [ * { * expected: 'string', * code: 'invalid_type', * path: [ 'username' ], * message: 'Invalid input: expected string' * }, * { * expected: 'number', * code: 'invalid_type', * path: [ 'favoriteNumbers', 1 ], * message: 'Invalid input: expected number' * } * ]; * } * ``` * * to * * ``` * username * ✖ Expected number, received string at "username * favoriteNumbers[0] * ✖ Invalid input: expected number * ``` */ function toDotPath(path) { const segs = []; for (const seg of path) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); else { if (segs.length) segs.push("."); segs.push(seg); } } return segs.join(""); } function prettifyError(error) { const lines = []; // sort by path length const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length); // Process each issue for (const issue of issues) { lines.push(`✖ ${issue.message}`); if (issue.path?.length) lines.push(` → at ${toDotPath(issue.path)}`); } // Convert Map to formatted string return lines.join("\n"); } ;// ./node_modules/zod/v4/core/parse.js const _parse = (_Err) => (schema, value, _ctx, _params) => { const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, _params?.callee); throw e; } return result.value; }; const parse = /* @__PURE__*/ _parse($ZodRealError); const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, params?.callee); throw e; } return result.value; }; const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); const _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } return result.issues.length ? { success: false, error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), } : { success: true, data: result.value }; }; const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; return result.issues.length ? { success: false, error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), } : { success: true, data: result.value }; }; const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); ;// ./node_modules/zod/v4/core/versions.js const version = { major: 4, minor: 0, patch: 0, }; ;// ./node_modules/zod/v4/core/schemas.js /* unused harmony import specifier */ var checks; /* unused harmony import specifier */ var schemas_core; /* unused harmony import specifier */ var regexes; /* unused harmony import specifier */ var schemas_util; const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { var _a; inst ?? (inst = {}); inst._zod.def = def; // set _def property inst._zod.bag = inst._zod.bag || {}; // initialize _bag object inst._zod.version = version; const checks = [...(inst._zod.def.checks ?? [])]; // if inst is itself a checks.$ZodCheck, run it as a check if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } // for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); } } if (checks.length === 0) { // deferred initializer // inst._zod.parse is not yet defined (_a = inst._zod).deferred ?? (_a.deferred = []); inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks, ctx) => { let isAborted = aborted(payload); let asyncResult; for (const ch of checks) { if (ch._zod.def.when) { const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted) { continue; } const currLen = payload.issues.length; const _ = ch._zod.check(payload); if (_ instanceof Promise && ctx?.async === false) { throw new $ZodAsyncError(); } if (asyncResult || _ instanceof Promise) { asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { await _; const nextLen = payload.issues.length; if (nextLen === currLen) return; if (!isAborted) isAborted = aborted(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted) isAborted = aborted(payload, currLen); } } if (asyncResult) { return asyncResult.then(() => { return payload; }); } return payload; }; inst._zod.run = (payload, ctx) => { const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return result.then((result) => runChecks(result, checks, ctx)); } return runChecks(result, checks, ctx); }; } inst["~standard"] = { validate: (value) => { try { const r = safeParse(inst, value); return r.success ? { value: r.data } : { issues: r.error?.issues }; } catch (_) { return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); } }, vendor: "zod", version: 1, }; }); const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_) { } if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst, }); return payload; }; }); const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { // check initialization must come first $ZodCheckStringFormat.init(inst, def); $ZodString.init(inst, def); }); const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { def.pattern ?? (def.pattern = guid); $ZodStringFormat.init(inst, def); }); const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { if (def.version) { const versionMap = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8, }; const v = versionMap[def.version]; if (v === undefined) throw new Error(`Invalid UUID version: "${def.version}"`); def.pattern ?? (def.pattern = uuid(v)); } else def.pattern ?? (def.pattern = uuid()); $ZodStringFormat.init(inst, def); }); const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const orig = payload.value; const url = new URL(orig); const href = url.href; if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: hostname.source, input: payload.value, inst, continue: !def.abort, }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort, }); } } // payload.value = url.href; if (!orig.endsWith("/") && href.endsWith("/")) { payload.value = href.slice(0, -1); } else { payload.value = href; } return; } catch (_) { payload.issues.push({ code: "invalid_format", format: "url", input: payload.value, inst, continue: !def.abort, }); } }; }); const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { def.pattern ?? (def.pattern = emoji()); $ZodStringFormat.init(inst, def); }); const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { def.pattern ?? (def.pattern = nanoid); $ZodStringFormat.init(inst, def); }); const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { def.pattern ?? (def.pattern = cuid); $ZodStringFormat.init(inst, def); }); const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { def.pattern ?? (def.pattern = cuid2); $ZodStringFormat.init(inst, def); }); const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { def.pattern ?? (def.pattern = ulid); $ZodStringFormat.init(inst, def); }); const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { def.pattern ?? (def.pattern = xid); $ZodStringFormat.init(inst, def); }); const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { def.pattern ?? (def.pattern = ksuid); $ZodStringFormat.init(inst, def); }); const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { def.pattern ?? (def.pattern = datetime(def)); $ZodStringFormat.init(inst, def); }); const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { def.pattern ?? (def.pattern = date); $ZodStringFormat.init(inst, def); }); const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { def.pattern ?? (def.pattern = time(def)); $ZodStringFormat.init(inst, def); }); const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { def.pattern ?? (def.pattern = duration); $ZodStringFormat.init(inst, def); }); const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.format = `ipv4`; }); }); const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag; bag.format = `ipv6`; }); inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); // return; } catch { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort, }); } }; }); const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); // not used for validation $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { const [address, prefix] = payload.value.split("/"); try { if (!prefix) throw new Error(); const prefixNum = Number(prefix); if (`${prefixNum}` !== prefix) throw new Error(); if (prefixNum < 0 || prefixNum > 128) throw new Error(); new URL(`http://[${address}]`); } catch { payload.issues.push({ code: "invalid_format", format: "cidrv6", input: payload.value, inst, continue: !def.abort, }); } }; }); ////////////////////////////// ZodBase64 ////////////////////////////// function isValidBase64(data) { if (data === "") return true; if (data.length % 4 !== 0) return false; try { atob(data); return true; } catch { return false; } } const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { def.pattern ?? (def.pattern = base64); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { inst._zod.bag.contentEncoding = "base64"; }); inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort, }); }; }); ////////////////////////////// ZodBase64 ////////////////////////////// function isValidBase64URL(data) { if (!base64url.test(data)) return false; const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); return isValidBase64(padded); } const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { def.pattern ?? (def.pattern = base64url); $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { inst._zod.bag.contentEncoding = "base64url"; }); inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64url", input: payload.value, inst, continue: !def.abort, }); }; }); const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); ////////////////////////////// ZodJWT ////////////////////////////// function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); if (tokensParts.length !== 3) return false; const [header] = tokensParts; if (!header) return false; const parsedHeader = JSON.parse(atob(header)); if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; if (!parsedHeader.alg) return false; if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; } catch { return false; } } const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (isValidJWT(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", format: "jwt", input: payload.value, inst, continue: !def.abort, }); }; }); const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodCustomStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (def.fn(payload.value)) return; payload.issues.push({ code: "invalid_format", format: def.format, input: payload.value, inst, continue: !def.abort, }); }; }))); const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = inst._zod.bag.pattern ?? number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...(received ? { received } : {}), }); return payload; }; }); const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); // no format checksp }); const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = regexes_boolean; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst, }); return payload; }; }); const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodBigInt", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = regexes.bigint; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = BigInt(payload.value); } catch (_) { } if (typeof payload.value === "bigint") return payload; payload.issues.push({ expected: "bigint", code: "invalid_type", input: payload.value, inst, }); return payload; }; }))); const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodBigInt", (inst, def) => { checks.$ZodCheckBigIntFormat.init(inst, def); $ZodBigInt.init(inst, def); // no format checks }))); const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", input, inst, }); return payload; }; }))); const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodUndefined", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = regexes.undefined; inst._zod.values = new Set([undefined]); inst._zod.optin = "optional"; inst._zod.optout = "optional"; inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", input, inst, }); return payload; }; }))); const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _null; inst._zod.values = new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst, }); return payload; }; }); const $ZodAny = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodAny", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }))); const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.issues.push({ expected: "never", code: "invalid_type", input: payload.value, inst, }); return payload; }; }); const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", input, inst, }); return payload; }; }))); const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodDate", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (def.coerce) { try { payload.value = new Date(payload.value); } catch (_err) { } } const input = payload.value; const isDate = input instanceof Date; const isValidDate = isDate && !Number.isNaN(input.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", input, ...(isDate ? { received: "Invalid Date" } : {}), inst, }); return payload; }; }))); function handleArrayResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst, }); return payload; } payload.value = Array(input.length); const proms = []; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run({ value: item, issues: [], }, ctx); if (result instanceof Promise) { proms.push(result.then((result) => handleArrayResult(result, payload, i))); } else { handleArrayResult(result, payload, i); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; //handleArrayResultsAsync(parseResults, final); }; }); function handleObjectResult(result, final, key) { // if(isOptional) if (result.issues.length) { final.issues.push(...prefixIssues(key, result.issues)); } final.value[key] = result.value; } function handleOptionalObjectResult(result, final, key, input) { if (result.issues.length) { // validation failed against value schema if (input[key] === undefined) { // if input was undefined, ignore the error if (key in input) { final.value[key] = undefined; } else { final.value[key] = result.value; } } else { final.issues.push(...prefixIssues(key, result.issues)); } } else if (result.value === undefined) { // validation returned `undefined` if (key in input) final.value[key] = undefined; } else { // non-undefined value final.value[key] = result.value; } } const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { // requires cast because technically $ZodObject doesn't extend $ZodType.init(inst, def); const _normalized = cached(() => { const keys = Object.keys(def.shape); for (const k of keys) { if (!(def.shape[k] instanceof $ZodType)) { throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { shape: def.shape, keys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys), }; }); defineLazy(inst._zod, "propValues", () => { const shape = def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { propValues[key] ?? (propValues[key] = new Set()); for (const v of field.values) propValues[key].add(v); } } return propValues; }); const generateFastpass = (shape) => { const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key) => { const k = esc(key); return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; }; doc.write(`const input = payload.value;`); const ids = Object.create(null); let counter = 0; for (const key of normalized.keys) { ids[key] = `key_${counter++}`; } // A: preserve key order { doc.write(`const newResult = {}`); for (const key of normalized.keys) { if (normalized.optionalKeys.has(key)) { const id = ids[key]; doc.write(`const ${id} = ${parseStr(key)};`); const k = esc(key); doc.write(` if (${id}.issues.length) { if (input[${k}] === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { payload.issues = payload.issues.concat( ${id}.issues.map((iss) => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}], })) ); } } else if (${id}.value === undefined) { if (${k} in input) newResult[${k}] = undefined; } else { newResult[${k}] = ${id}.value; } `); } else { const id = ids[key]; // const id = ids[key]; doc.write(`const ${id} = ${parseStr(key)};`); doc.write(` if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}] })));`); doc.write(`newResult[${esc(key)}] = ${id}.value`); } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); const fn = doc.compile(); return (payload, ctx) => fn(shape, payload, ctx); }; let fastpass; const isObject = util_isObject; const jit = !globalConfig.jitless; const allowsEval = util_allowsEval; const fastEnabled = jit && allowsEval.value; // && !def.catchall; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst, }); return payload; } const proms = []; if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { // always synchronous if (!fastpass) fastpass = generateFastpass(def.shape); payload = fastpass(payload, ctx); } else { payload.value = {}; const shape = value.shape; for (const key of value.keys) { const el = shape[key]; // do not add omitted optional keys // if (!(key in input)) { // if (optionalKeys.has(key)) continue; // payload.issues.push({ // code: "invalid_type", // path: [key], // expected: "nonoptional", // note: `Missing required key: "${key}"`, // input, // inst, // }); // } const r = el._zod.run({ value: input[key], issues: [] }, ctx); const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; if (r instanceof Promise) { proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key))); } else if (isOptional) { handleOptionalObjectResult(r, payload, key, input); } else { handleObjectResult(r, payload, key); } } } if (!catchall) { // return payload; return proms.length ? Promise.all(proms).then(() => payload) : payload; } const unrecognized = []; // iterate over input keys const keySet = value.keySet; const _catchall = catchall._zod; const t = _catchall.def.type; for (const key of Object.keys(input)) { if (keySet.has(key)) continue; if (t === "never") { unrecognized.push(key); continue; } const r = _catchall.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r) => handleObjectResult(r, payload, key))); } else { handleObjectResult(r, payload, key); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, input, inst, }); } if (!proms.length) return payload; return Promise.all(proms).then(() => { return payload; }); }; }); function handleUnionResults(results, final, inst, ctx) { for (const result of results) { if (result.issues.length === 0) { final.value = result.value; return final; } } final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), }); return final; } const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined); defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); defineLazy(inst._zod, "values", () => { if (def.options.every((o) => o._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } return undefined; }); defineLazy(inst._zod, "pattern", () => { if (def.options.every((o) => o._zod.pattern)) { const patterns = def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return undefined; }); inst._zod.parse = (payload, ctx) => { let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [], }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { if (result.issues.length === 0) return result; results.push(result); } } if (!async) return handleUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results) => { return handleUnionResults(results, payload, inst, ctx); }); }; }); const $ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("$ZodDiscriminatedUnion", (inst, def) => { $ZodUnion.init(inst, def); const _super = inst._zod.parse; defineLazy(inst._zod, "propValues", () => { const propValues = {}; for (const option of def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); for (const [k, v] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = new Set(); for (const val of v) { propValues[k].add(val); } } } return propValues; }); const disc = cached(() => { const opts = def.options; const map = new Map(); for (const o of opts) { const values = o._zod.propValues[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); for (const v of values) { if (map.has(v)) { throw new Error(`Duplicate discriminator value "${String(v)}"`); } map.set(v, o); } } return map; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!util_isObject(input)) { payload.issues.push({ code: "invalid_type", expected: "object", input, inst, }); return payload; } const opt = disc.value.get(input?.[def.discriminator]); if (opt) { return opt._zod.run(payload, ctx); } if (def.unionFallback) { return _super(payload, ctx); } // no matching discriminator payload.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", input, path: [def.discriminator], inst, }); return payload; }; }); const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; const left = def.left._zod.run({ value: input, issues: [] }, ctx); const right = def.right._zod.run({ value: input, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left, right]) => { return handleIntersectionResults(payload, left, right); }); } return handleIntersectionResults(payload, left, right); }; }); function mergeValues(a, b) { // const aType = parse.t(a); // const bType = parse.t(b); if (a === b) { return { valid: true, data: a }; } if (a instanceof Date && b instanceof Date && +a === +b) { return { valid: true, data: a }; } if (isPlainObject(a) && isPlainObject(b)) { const bKeys = Object.keys(b); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [key, ...sharedValue.mergeErrorPath], }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return { valid: false, mergeErrorPath: [] }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [index, ...sharedValue.mergeErrorPath], }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } return { valid: false, mergeErrorPath: [] }; } function handleIntersectionResults(result, left, right) { if (left.issues.length) { result.issues.push(...left.issues); } if (right.issues.length) { result.issues.push(...right.issues); } if (aborted(result)) return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; return result; } const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ input, inst, expected: "tuple", code: "invalid_type", }); return payload; } payload.value = []; const proms = []; if (!def.rest) { const tooBig = input.length > items.length; const tooSmall = input.length < optStart - 1; if (tooBig || tooSmall) { payload.issues.push({ input, inst, origin: "array", ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), }); return payload; } } let i = -1; for (const item of items) { i++; if (i >= input.length) if (i >= optStart) continue; const result = item._zod.run({ value: input[i], issues: [], }, ctx); if (result instanceof Promise) { proms.push(result.then((result) => handleTupleResult(result, payload, i))); } else { handleTupleResult(result, payload, i); } } if (def.rest) { const rest = input.slice(items.length); for (const el of rest) { i++; const result = def.rest._zod.run({ value: el, issues: [], }, ctx); if (result instanceof Promise) { proms.push(result.then((result) => handleTupleResult(result, payload, i))); } else { handleTupleResult(result, payload, i); } } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }))); function handleTupleResult(result, final, index) { if (result.issues.length) { final.issues.push(...schemas_util.prefixIssues(index, result.issues)); } final.value[index] = result.value; } const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isPlainObject(input)) { payload.issues.push({ expected: "record", code: "invalid_type", input, inst, }); return payload; } const proms = []; if (def.keyType._zod.values) { const values = def.keyType._zod.values; payload.value = {}; for (const key of values) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result) => { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[key] = result.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[key] = result.value; } } } let unrecognized; for (const key in input) { if (!values.has(key)) { unrecognized = unrecognized ?? []; unrecognized.push(key); } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", input, inst, keys: unrecognized, }); } } else { payload.value = {}; for (const key of Reflect.ownKeys(input)) { if (key === "__proto__") continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (keyResult.issues.length) { payload.issues.push({ origin: "record", code: "invalid_key", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst, }); payload.value[keyResult.value] = keyResult.value; continue; } const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result) => { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[keyResult.value] = result.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[keyResult.value] = result.value; } } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", input, inst, }); return payload; } const proms = []; payload.value = new Map(); for (const [key, value] of input) { const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); })); } else { handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }))); function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { if (keyResult.issues.length) { if (schemas_util.propertyKeyTypes.has(typeof key)) { final.issues.push(...schemas_util.prefixIssues(key, keyResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_key", input, inst, issues: keyResult.issues.map((iss) => schemas_util.finalizeIssue(iss, ctx, schemas_core.config())), }); } } if (valueResult.issues.length) { if (schemas_util.propertyKeyTypes.has(typeof key)) { final.issues.push(...schemas_util.prefixIssues(key, valueResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_element", input, inst, key: key, issues: valueResult.issues.map((iss) => schemas_util.finalizeIssue(iss, ctx, schemas_core.config())), }); } } final.value.set(keyResult.value, valueResult.value); } const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Set)) { payload.issues.push({ input, inst, expected: "set", code: "invalid_type", }); return payload; } const proms = []; payload.value = new Set(); for (const item of input) { const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result) => handleSetResult(result, payload))); } else handleSetResult(result, payload); } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }))); function handleSetResult(result, final) { if (result.issues.length) { final.issues.push(...result.issues); } final.value.add(result.value); } const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); inst._zod.values = new Set(values); inst._zod.pattern = new RegExp(`^(${values .filter((k) => propertyKeyTypes.has(typeof k)) .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString())) .join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (inst._zod.values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values, input, inst, }); return payload; }; }); const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); inst._zod.values = new Set(def.values); inst._zod.pattern = new RegExp(`^(${def.values .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o))) .join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (inst._zod.values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, input, inst, }); return payload; }; }); const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", input, inst, }); return payload; }; }))); const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const _out = def.transform(payload.value, payload); if (_ctx.async) { const output = _out instanceof Promise ? _out : Promise.resolve(_out); return output.then((output) => { payload.value = output; return payload; }); } if (_out instanceof Promise) { throw new $ZodAsyncError(); } payload.value = _out; return payload; }; }); const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.optout = "optional"; defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; }); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { return def.innerType._zod.run(payload, ctx); } if (payload.value === undefined) { return payload; } return def.innerType._zod.run(payload, ctx); }; }); const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; }); defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); // inst._zod.qin = "true"; inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (payload.value === undefined) { payload.value = def.defaultValue; /** * $ZodDefault always returns the default value immediately. * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ return payload; } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result) => handleDefaultResult(result, def)); } return handleDefaultResult(result, def); }; }); function handleDefaultResult(payload, def) { if (payload.value === undefined) { payload.value = def.defaultValue; } return payload; } const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (payload.value === undefined) { payload.value = def.defaultValue; } return def.innerType._zod.run(payload, ctx); }; }); const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => { const v = def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result) => handleNonOptionalResult(result, inst)); } return handleNonOptionalResult(result, inst); }; }); function handleNonOptionalResult(payload, inst) { if (!payload.issues.length && payload.value === undefined) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: payload.value, inst, }); } return payload; } const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodSuccess", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result) => { payload.value = result.issues.length === 0; return payload; }); } payload.value = result.issues.length === 0; return payload; }; }))); const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result) => { payload.value = result.value; if (result.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), }, input: payload.value, }); payload.issues = []; } return payload; }); } payload.value = result.value; if (result.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), }, input: payload.value, }); payload.issues = []; } return payload; }; }); const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodNaN", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { payload.issues.push({ input: payload.value, inst, expected: "nan", code: "invalid_type", }); return payload; } return payload; }; }))); const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); inst._zod.parse = (payload, ctx) => { const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left) => handlePipeResult(left, def, ctx)); } return handlePipeResult(left, def, ctx); }; }); function handlePipeResult(left, def, ctx) { if (aborted(left)) { return left; } return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); } const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then(handleReadonlyResult); } return handleReadonlyResult(result); }; }); function handleReadonlyResult(payload) { payload.value = Object.freeze(payload.value); return payload; } const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (part instanceof $ZodType) { if (!part._zod.pattern) { // if (!source) throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; if (!source) throw new Error(`Invalid template literal part: ${part._zod.traits}`); const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; regexParts.push(source.slice(start, end)); } else if (part === null || schemas_util.primitiveTypes.has(typeof part)) { regexParts.push(schemas_util.escapeRegex(`${part}`)); } else { throw new Error(`Invalid template literal part: ${part}`); } } inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "string") { payload.issues.push({ input: payload.value, inst, expected: "template_literal", code: "invalid_type", }); return payload; } inst._zod.pattern.lastIndex = 0; if (!inst._zod.pattern.test(payload.value)) { payload.issues.push({ input: payload.value, inst, code: "invalid_format", format: "template_literal", pattern: inst._zod.pattern.source, }); return payload; } return payload; }; }))); const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodPromise", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); }; }))); const $ZodLazy = /*@__PURE__*/ (/* unused pure expression or super */ null && (schemas_core.$constructor("$ZodLazy", (inst, def) => { $ZodType.init(inst, def); schemas_util.defineLazy(inst._zod, "innerType", () => def.getter()); schemas_util.defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); schemas_util.defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); schemas_util.defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin); schemas_util.defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); }; }))); const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { $ZodCheck.init(inst, def); $ZodType.init(inst, def); inst._zod.parse = (payload, _) => { return payload; }; inst._zod.check = (payload) => { const input = payload.value; const r = def.fn(input); if (r instanceof Promise) { return r.then((r) => handleRefineResult(r, payload, input, inst)); } handleRefineResult(r, payload, input, inst); return; }; }); function handleRefineResult(result, payload, input, inst) { if (!result) { const _iss = { code: "custom", input, inst, // incorporates params.error into issue reporting path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting continue: !inst._zod.def.abort, // params: inst._zod.def.params, }; if (inst._zod.def.params) _iss.params = inst._zod.def.params; payload.issues.push(util_issue(_iss)); } } ;// ./node_modules/zod/v4/core/registries.js const $output = Symbol("ZodOutput"); const $input = Symbol("ZodInput"); class $ZodRegistry { constructor() { this._map = new Map(); this._idmap = new Map(); } add(schema, ..._meta) { const meta = _meta[0]; this._map.set(schema, meta); if (meta && typeof meta === "object" && "id" in meta) { if (this._idmap.has(meta.id)) { throw new Error(`ID ${meta.id} already exists in the registry`); } this._idmap.set(meta.id, schema); } return this; } clear() { this._map = new Map(); this._idmap = new Map(); return this; } remove(schema) { const meta = this._map.get(schema); if (meta && typeof meta === "object" && "id" in meta) { this._idmap.delete(meta.id); } this._map.delete(schema); return this; } get(schema) { // return this._map.get(schema) as any; // inherit metadata const p = schema._zod.parent; if (p) { const pm = { ...(this.get(p) ?? {}) }; delete pm.id; // do not inherit id return { ...pm, ...this._map.get(schema) }; } return this._map.get(schema); } has(schema) { return this._map.has(schema); } } // registries function registry() { return new $ZodRegistry(); } const globalRegistry = /*@__PURE__*/ registry(); ;// ./node_modules/zod/v4/core/api.js /* unused harmony import specifier */ var api_checks; /* unused harmony import specifier */ var schemas; /* unused harmony import specifier */ var api_util; function _string(Class, params) { return new Class({ type: "string", ...normalizeParams(params), }); } function _coercedString(Class, params) { return new Class({ type: "string", coerce: true, ...api_util.normalizeParams(params), }); } function _email(Class, params) { return new Class({ type: "string", format: "email", check: "string_format", abort: false, ...normalizeParams(params), }); } function _guid(Class, params) { return new Class({ type: "string", format: "guid", check: "string_format", abort: false, ...normalizeParams(params), }); } function _uuid(Class, params) { return new Class({ type: "string", format: "uuid", check: "string_format", abort: false, ...normalizeParams(params), }); } function _uuidv4(Class, params) { return new Class({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...normalizeParams(params), }); } function _uuidv6(Class, params) { return new Class({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...normalizeParams(params), }); } function _uuidv7(Class, params) { return new Class({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...normalizeParams(params), }); } function _url(Class, params) { return new Class({ type: "string", format: "url", check: "string_format", abort: false, ...normalizeParams(params), }); } function api_emoji(Class, params) { return new Class({ type: "string", format: "emoji", check: "string_format", abort: false, ...normalizeParams(params), }); } function _nanoid(Class, params) { return new Class({ type: "string", format: "nanoid", check: "string_format", abort: false, ...normalizeParams(params), }); } function _cuid(Class, params) { return new Class({ type: "string", format: "cuid", check: "string_format", abort: false, ...normalizeParams(params), }); } function _cuid2(Class, params) { return new Class({ type: "string", format: "cuid2", check: "string_format", abort: false, ...normalizeParams(params), }); } function _ulid(Class, params) { return new Class({ type: "string", format: "ulid", check: "string_format", abort: false, ...normalizeParams(params), }); } function _xid(Class, params) { return new Class({ type: "string", format: "xid", check: "string_format", abort: false, ...normalizeParams(params), }); } function _ksuid(Class, params) { return new Class({ type: "string", format: "ksuid", check: "string_format", abort: false, ...normalizeParams(params), }); } function _ipv4(Class, params) { return new Class({ type: "string", format: "ipv4", check: "string_format", abort: false, ...normalizeParams(params), }); } function _ipv6(Class, params) { return new Class({ type: "string", format: "ipv6", check: "string_format", abort: false, ...normalizeParams(params), }); } function _cidrv4(Class, params) { return new Class({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...normalizeParams(params), }); } function _cidrv6(Class, params) { return new Class({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...normalizeParams(params), }); } function _base64(Class, params) { return new Class({ type: "string", format: "base64", check: "string_format", abort: false, ...normalizeParams(params), }); } function _base64url(Class, params) { return new Class({ type: "string", format: "base64url", check: "string_format", abort: false, ...normalizeParams(params), }); } function _e164(Class, params) { return new Class({ type: "string", format: "e164", check: "string_format", abort: false, ...normalizeParams(params), }); } function _jwt(Class, params) { return new Class({ type: "string", format: "jwt", check: "string_format", abort: false, ...normalizeParams(params), }); } const TimePrecision = (/* unused pure expression or super */ null && ({ Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6, })); function _isoDateTime(Class, params) { return new Class({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...normalizeParams(params), }); } function _isoDate(Class, params) { return new Class({ type: "string", format: "date", check: "string_format", ...normalizeParams(params), }); } function _isoTime(Class, params) { return new Class({ type: "string", format: "time", check: "string_format", precision: null, ...normalizeParams(params), }); } function _isoDuration(Class, params) { return new Class({ type: "string", format: "duration", check: "string_format", ...normalizeParams(params), }); } function _number(Class, params) { return new Class({ type: "number", checks: [], ...normalizeParams(params), }); } function _coercedNumber(Class, params) { return new Class({ type: "number", coerce: true, checks: [], ...api_util.normalizeParams(params), }); } function _int(Class, params) { return new Class({ type: "number", check: "number_format", abort: false, format: "safeint", ...normalizeParams(params), }); } function _float32(Class, params) { return new Class({ type: "number", check: "number_format", abort: false, format: "float32", ...api_util.normalizeParams(params), }); } function _float64(Class, params) { return new Class({ type: "number", check: "number_format", abort: false, format: "float64", ...api_util.normalizeParams(params), }); } function _int32(Class, params) { return new Class({ type: "number", check: "number_format", abort: false, format: "int32", ...api_util.normalizeParams(params), }); } function _uint32(Class, params) { return new Class({ type: "number", check: "number_format", abort: false, format: "uint32", ...api_util.normalizeParams(params), }); } function _boolean(Class, params) { return new Class({ type: "boolean", ...normalizeParams(params), }); } function _coercedBoolean(Class, params) { return new Class({ type: "boolean", coerce: true, ...api_util.normalizeParams(params), }); } function _bigint(Class, params) { return new Class({ type: "bigint", ...api_util.normalizeParams(params), }); } function _coercedBigint(Class, params) { return new Class({ type: "bigint", coerce: true, ...api_util.normalizeParams(params), }); } function _int64(Class, params) { return new Class({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...api_util.normalizeParams(params), }); } function _uint64(Class, params) { return new Class({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...api_util.normalizeParams(params), }); } function _symbol(Class, params) { return new Class({ type: "symbol", ...api_util.normalizeParams(params), }); } function api_undefined(Class, params) { return new Class({ type: "undefined", ...api_util.normalizeParams(params), }); } function api_null(Class, params) { return new Class({ type: "null", ...normalizeParams(params), }); } function _any(Class) { return new Class({ type: "any", }); } function _unknown(Class) { return new Class({ type: "unknown", }); } function _never(Class, params) { return new Class({ type: "never", ...normalizeParams(params), }); } function _void(Class, params) { return new Class({ type: "void", ...api_util.normalizeParams(params), }); } function _date(Class, params) { return new Class({ type: "date", ...api_util.normalizeParams(params), }); } function _coercedDate(Class, params) { return new Class({ type: "date", coerce: true, ...api_util.normalizeParams(params), }); } function _nan(Class, params) { return new Class({ type: "nan", ...api_util.normalizeParams(params), }); } function _lt(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: false, }); } function _lte(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: true, }); } function _gt(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: false, }); } function _gte(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: true, }); } function _positive(params) { return _gt(0, params); } // negative function _negative(params) { return _lt(0, params); } // nonpositive function _nonpositive(params) { return _lte(0, params); } // nonnegative function _nonnegative(params) { return _gte(0, params); } function _multipleOf(value, params) { return new $ZodCheckMultipleOf({ check: "multiple_of", ...normalizeParams(params), value, }); } function _maxSize(maximum, params) { return new api_checks.$ZodCheckMaxSize({ check: "max_size", ...api_util.normalizeParams(params), maximum, }); } function _minSize(minimum, params) { return new api_checks.$ZodCheckMinSize({ check: "min_size", ...api_util.normalizeParams(params), minimum, }); } function _size(size, params) { return new api_checks.$ZodCheckSizeEquals({ check: "size_equals", ...api_util.normalizeParams(params), size, }); } function _maxLength(maximum, params) { const ch = new $ZodCheckMaxLength({ check: "max_length", ...normalizeParams(params), maximum, }); return ch; } function _minLength(minimum, params) { return new $ZodCheckMinLength({ check: "min_length", ...normalizeParams(params), minimum, }); } function _length(length, params) { return new $ZodCheckLengthEquals({ check: "length_equals", ...normalizeParams(params), length, }); } function _regex(pattern, params) { return new $ZodCheckRegex({ check: "string_format", format: "regex", ...normalizeParams(params), pattern, }); } function _lowercase(params) { return new $ZodCheckLowerCase({ check: "string_format", format: "lowercase", ...normalizeParams(params), }); } function _uppercase(params) { return new $ZodCheckUpperCase({ check: "string_format", format: "uppercase", ...normalizeParams(params), }); } function _includes(includes, params) { return new $ZodCheckIncludes({ check: "string_format", format: "includes", ...normalizeParams(params), includes, }); } function _startsWith(prefix, params) { return new $ZodCheckStartsWith({ check: "string_format", format: "starts_with", ...normalizeParams(params), prefix, }); } function _endsWith(suffix, params) { return new $ZodCheckEndsWith({ check: "string_format", format: "ends_with", ...normalizeParams(params), suffix, }); } function _property(property, schema, params) { return new api_checks.$ZodCheckProperty({ check: "property", property, schema, ...api_util.normalizeParams(params), }); } function _mime(types, params) { return new api_checks.$ZodCheckMimeType({ check: "mime_type", mime: types, ...api_util.normalizeParams(params), }); } function _overwrite(tx) { return new $ZodCheckOverwrite({ check: "overwrite", tx, }); } // normalize function _normalize(form) { return _overwrite((input) => input.normalize(form)); } // trim function _trim() { return _overwrite((input) => input.trim()); } // toLowerCase function _toLowerCase() { return _overwrite((input) => input.toLowerCase()); } // toUpperCase function _toUpperCase() { return _overwrite((input) => input.toUpperCase()); } function _array(Class, element, params) { return new Class({ type: "array", element, // get element() { // return element; // }, ...normalizeParams(params), }); } function _union(Class, options, params) { return new Class({ type: "union", options, ...api_util.normalizeParams(params), }); } function _discriminatedUnion(Class, discriminator, options, params) { return new Class({ type: "union", options, discriminator, ...api_util.normalizeParams(params), }); } function _intersection(Class, left, right) { return new Class({ type: "intersection", left, right, }); } // export function _tuple( // Class: util.SchemaClass<schemas.$ZodTuple>, // items: [], // params?: string | $ZodTupleParams // ): schemas.$ZodTuple<[], null>; function _tuple(Class, items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof schemas.$ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new Class({ type: "tuple", items, rest, ...api_util.normalizeParams(params), }); } function _record(Class, keyType, valueType, params) { return new Class({ type: "record", keyType, valueType, ...api_util.normalizeParams(params), }); } function _map(Class, keyType, valueType, params) { return new Class({ type: "map", keyType, valueType, ...api_util.normalizeParams(params), }); } function _set(Class, valueType, params) { return new Class({ type: "set", valueType, ...api_util.normalizeParams(params), }); } function _enum(Class, values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; // if (Array.isArray(values)) { // for (const value of values) { // entries[value] = value; // } // } else { // Object.assign(entries, values); // } // const entries: util.EnumLike = {}; // for (const val of values) { // entries[val] = val; // } return new Class({ type: "enum", entries, ...api_util.normalizeParams(params), }); } /** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. * * ```ts * enum Colors { red, green, blue } * z.enum(Colors); * ``` */ function _nativeEnum(Class, entries, params) { return new Class({ type: "enum", entries, ...api_util.normalizeParams(params), }); } function _literal(Class, value, params) { return new Class({ type: "literal", values: Array.isArray(value) ? value : [value], ...api_util.normalizeParams(params), }); } function _file(Class, params) { return new Class({ type: "file", ...api_util.normalizeParams(params), }); } function _transform(Class, fn) { return new Class({ type: "transform", transform: fn, }); } function _optional(Class, innerType) { return new Class({ type: "optional", innerType, }); } function _nullable(Class, innerType) { return new Class({ type: "nullable", innerType, }); } function _default(Class, innerType, defaultValue) { return new Class({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; }, }); } function _nonoptional(Class, innerType, params) { return new Class({ type: "nonoptional", innerType, ...api_util.normalizeParams(params), }); } function _success(Class, innerType) { return new Class({ type: "success", innerType, }); } function _catch(Class, innerType, catchValue) { return new Class({ type: "catch", innerType, catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), }); } function _pipe(Class, in_, out) { return new Class({ type: "pipe", in: in_, out, }); } function _readonly(Class, innerType) { return new Class({ type: "readonly", innerType, }); } function _templateLiteral(Class, parts, params) { return new Class({ type: "template_literal", parts, ...api_util.normalizeParams(params), }); } function _lazy(Class, getter) { return new Class({ type: "lazy", getter, }); } function _promise(Class, innerType) { return new Class({ type: "promise", innerType, }); } function _custom(Class, fn, _params) { const norm = normalizeParams(_params); norm.abort ?? (norm.abort = true); // default to abort:false const schema = new Class({ type: "custom", check: "custom", fn: fn, ...norm, }); return schema; } // export function _refine<T>( // Class: util.SchemaClass<schemas.$ZodCustom>, // fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, // _params: string | $ZodCustomParams = {} // ): checks.$ZodCheck<T> { // return _custom(Class, fn, _params); // } // same as _custom but defaults to abort:false function _refine(Class, fn, _params) { const schema = new Class({ type: "custom", check: "custom", fn: fn, ...normalizeParams(_params), }); return schema; } function _stringbool(Classes, _params) { const params = api_util.normalizeParams(_params); let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; if (params.case !== "sensitive") { truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); } const truthySet = new Set(truthyArray); const falsySet = new Set(falsyArray); const _Pipe = Classes.Pipe ?? schemas.$ZodPipe; const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; const _String = Classes.String ?? schemas.$ZodString; const _Transform = Classes.Transform ?? schemas.$ZodTransform; const tx = new _Transform({ type: "transform", transform: (input, payload) => { let data = input; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { return true; } else if (falsySet.has(data)) { return false; } else { payload.issues.push({ code: "invalid_value", expected: "stringbool", values: [...truthySet, ...falsySet], input: payload.value, inst: tx, }); return {}; } }, error: params.error, }); // params.error; const innerPipe = new _Pipe({ type: "pipe", in: new _String({ type: "string", error: params.error }), out: tx, error: params.error, }); const outerPipe = new _Pipe({ type: "pipe", in: innerPipe, out: new _Boolean({ type: "boolean", error: params.error, }), error: params.error, }); return outerPipe; } function _stringFormat(Class, format, fnOrRegex, _params = {}) { const params = api_util.normalizeParams(_params); const def = { ...api_util.normalizeParams(_params), check: "string_format", type: "string", format, fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), ...params, }; if (fnOrRegex instanceof RegExp) { def.pattern = fnOrRegex; } const inst = new Class(def); return inst; } ;// ./node_modules/zod/v4/classic/iso.js const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { $ZodISODateTime.init(inst, def); ZodStringFormat.init(inst, def); }); function iso_datetime(params) { return _isoDateTime(ZodISODateTime, params); } const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { $ZodISODate.init(inst, def); ZodStringFormat.init(inst, def); }); function iso_date(params) { return _isoDate(ZodISODate, params); } const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { $ZodISOTime.init(inst, def); ZodStringFormat.init(inst, def); }); function iso_time(params) { return _isoTime(ZodISOTime, params); } const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { $ZodISODuration.init(inst, def); ZodStringFormat.init(inst, def); }); function iso_duration(params) { return _isoDuration(ZodISODuration, params); } ;// ./node_modules/zod/v4/classic/errors.js /* unused harmony import specifier */ var errors_core; const errors_initializer = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError(inst, mapper), // enumerable: false, }, flatten: { value: (mapper) => flattenError(inst, mapper), // enumerable: false, }, addIssue: { value: (issue) => inst.issues.push(issue), // enumerable: false, }, addIssues: { value: (issues) => inst.issues.push(...issues), // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; }, // enumerable: false, }, }); // Object.defineProperty(inst, "isEmpty", { // get() { // return inst.issues.length === 0; // }, // }); }; const ZodError = (/* unused pure expression or super */ null && (errors_core.$constructor("ZodError", errors_initializer))); const ZodRealError = $constructor("ZodError", errors_initializer, { Parent: Error, }); // /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ // export type ErrorMapCtx = core.$ZodErrorMapCtx; ;// ./node_modules/zod/v4/classic/parse.js const parse_parse = /* @__PURE__ */ _parse(ZodRealError); const parse_parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); ;// ./node_modules/zod/v4/classic/schemas.js /* unused harmony import specifier */ var classic_schemas_core; /* unused harmony import specifier */ var classic_schemas_util; /* unused harmony import specifier */ var schemas_checks; const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); inst.def = def; Object.defineProperty(inst, "_def", { value: def }); // base methods inst.check = (...checks) => { return inst.clone({ ...def, checks: [ ...(def.checks ?? []), ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), ], } // { parent: true } ); }; inst.clone = (def, params) => clone(inst, def, params); inst.brand = () => inst; inst.register = ((reg, meta) => { reg.add(inst, meta); return inst; }); // parsing inst.parse = (data, params) => parse_parse(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => parse_safeParse(inst, data, params); inst.parseAsync = async (data, params) => parse_parseAsync(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => parse_safeParseAsync(inst, data, params); inst.spa = inst.safeParseAsync; // refinements inst.refine = (check, params) => inst.check(refine(check, params)); inst.superRefine = (refinement) => inst.check(superRefine(refinement)); inst.overwrite = (fn) => inst.check(_overwrite(fn)); // wrappers inst.optional = () => optional(inst); inst.nullable = () => nullable(inst); inst.nullish = () => optional(nullable(inst)); inst.nonoptional = (params) => nonoptional(inst, params); inst.array = () => array(inst); inst.or = (arg) => union([inst, arg]); inst.and = (arg) => intersection(inst, arg); inst.transform = (tx) => pipe(inst, transform(tx)); inst.default = (def) => schemas_default(inst, def); inst.prefault = (def) => prefault(inst, def); // inst.coalesce = (def, params) => coalesce(inst, def, params); inst.catch = (params) => schemas_catch(inst, params); inst.pipe = (target) => pipe(inst, target); inst.readonly = () => readonly(inst); // meta inst.describe = (description) => { const cl = inst.clone(); globalRegistry.add(cl, { description }); return cl; }; Object.defineProperty(inst, "description", { get() { return globalRegistry.get(inst)?.description; }, configurable: true, }); inst.meta = (...args) => { if (args.length === 0) { return globalRegistry.get(inst); } const cl = inst.clone(); globalRegistry.add(cl, args[0]); return cl; }; // helpers inst.isOptional = () => inst.safeParse(undefined).success; inst.isNullable = () => inst.safeParse(null).success; return inst; }); /** @internal */ const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { $ZodString.init(inst, def); ZodType.init(inst, def); const bag = inst._zod.bag; inst.format = bag.format ?? null; inst.minLength = bag.minimum ?? null; inst.maxLength = bag.maximum ?? null; // validations inst.regex = (...args) => inst.check(_regex(...args)); inst.includes = (...args) => inst.check(_includes(...args)); inst.startsWith = (...args) => inst.check(_startsWith(...args)); inst.endsWith = (...args) => inst.check(_endsWith(...args)); inst.min = (...args) => inst.check(_minLength(...args)); inst.max = (...args) => inst.check(_maxLength(...args)); inst.length = (...args) => inst.check(_length(...args)); inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); inst.lowercase = (params) => inst.check(_lowercase(params)); inst.uppercase = (params) => inst.check(_uppercase(params)); // transforms inst.trim = () => inst.check(_trim()); inst.normalize = (...args) => inst.check(_normalize(...args)); inst.toLowerCase = () => inst.check(_toLowerCase()); inst.toUpperCase = () => inst.check(_toUpperCase()); }); const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); inst.email = (params) => inst.check(_email(ZodEmail, params)); inst.url = (params) => inst.check(_url(ZodURL, params)); inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); inst.emoji = (params) => inst.check(api_emoji(ZodEmoji, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); inst.xid = (params) => inst.check(_xid(ZodXID, params)); inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); inst.e164 = (params) => inst.check(_e164(ZodE164, params)); // iso inst.datetime = (params) => inst.check(iso_datetime(params)); inst.date = (params) => inst.check(iso_date(params)); inst.time = (params) => inst.check(iso_time(params)); inst.duration = (params) => inst.check(iso_duration(params)); }); function schemas_string(params) { return _string(ZodString, params); } const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_email(params) { return classic_schemas_core._email(ZodEmail, params); } const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodGUID.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_guid(params) { return classic_schemas_core._guid(ZodGUID, params); } const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_uuid(params) { return classic_schemas_core._uuid(ZodUUID, params); } function uuidv4(params) { return classic_schemas_core._uuidv4(ZodUUID, params); } // ZodUUIDv6 function uuidv6(params) { return classic_schemas_core._uuidv6(ZodUUID, params); } // ZodUUIDv7 function uuidv7(params) { return classic_schemas_core._uuidv7(ZodUUID, params); } const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); function url(params) { return classic_schemas_core._url(ZodURL, params); } const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodEmoji.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_emoji(params) { return classic_schemas_core._emoji(ZodEmoji, params); } const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodNanoID.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_nanoid(params) { return classic_schemas_core._nanoid(ZodNanoID, params); } const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodCUID.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_cuid(params) { return classic_schemas_core._cuid(ZodCUID, params); } const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodCUID2.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_cuid2(params) { return classic_schemas_core._cuid2(ZodCUID2, params); } const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodULID.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_ulid(params) { return classic_schemas_core._ulid(ZodULID, params); } const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodXID.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_xid(params) { return classic_schemas_core._xid(ZodXID, params); } const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodKSUID.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_ksuid(params) { return classic_schemas_core._ksuid(ZodKSUID, params); } const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodIPv4.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_ipv4(params) { return classic_schemas_core._ipv4(ZodIPv4, params); } const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodIPv6.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_ipv6(params) { return classic_schemas_core._ipv6(ZodIPv6, params); } const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { $ZodCIDRv4.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_cidrv4(params) { return classic_schemas_core._cidrv4(ZodCIDRv4, params); } const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { $ZodCIDRv6.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_cidrv6(params) { return classic_schemas_core._cidrv6(ZodCIDRv6, params); } const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_base64(params) { return classic_schemas_core._base64(ZodBase64, params); } const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodBase64URL.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_base64url(params) { return classic_schemas_core._base64url(ZodBase64URL, params); } const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodE164.init(inst, def); ZodStringFormat.init(inst, def); }); function schemas_e164(params) { return classic_schemas_core._e164(ZodE164, params); } const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { // ZodStringFormat.init(inst, def); $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); }); function jwt(params) { return classic_schemas_core._jwt(ZodJWT, params); } const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodCustomStringFormat", (inst, def) => { // ZodStringFormat.init(inst, def); classic_schemas_core.$ZodCustomStringFormat.init(inst, def); ZodStringFormat.init(inst, def); }))); function stringFormat(format, fnOrRegex, _params = {}) { return classic_schemas_core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { $ZodNumber.init(inst, def); ZodType.init(inst, def); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.int = (params) => inst.check(schemas_int(params)); inst.safe = (params) => inst.check(schemas_int(params)); inst.positive = (params) => inst.check(_gt(0, params)); inst.nonnegative = (params) => inst.check(_gte(0, params)); inst.negative = (params) => inst.check(_lt(0, params)); inst.nonpositive = (params) => inst.check(_lte(0, params)); inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); inst.step = (value, params) => inst.check(_multipleOf(value, params)); // inst.finite = (params) => inst.check(core.finite(params)); inst.finite = () => inst; const bag = inst._zod.bag; inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); inst.isFinite = true; inst.format = bag.format ?? null; }); function schemas_number(params) { return _number(ZodNumber, params); } const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); ZodNumber.init(inst, def); }); function schemas_int(params) { return _int(ZodNumberFormat, params); } function float32(params) { return classic_schemas_core._float32(ZodNumberFormat, params); } function float64(params) { return classic_schemas_core._float64(ZodNumberFormat, params); } function int32(params) { return classic_schemas_core._int32(ZodNumberFormat, params); } function uint32(params) { return classic_schemas_core._uint32(ZodNumberFormat, params); } const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodType.init(inst, def); }); function schemas_boolean(params) { return _boolean(ZodBoolean, params); } const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodBigInt", (inst, def) => { classic_schemas_core.$ZodBigInt.init(inst, def); ZodType.init(inst, def); inst.gte = (value, params) => inst.check(schemas_checks.gte(value, params)); inst.min = (value, params) => inst.check(schemas_checks.gte(value, params)); inst.gt = (value, params) => inst.check(schemas_checks.gt(value, params)); inst.gte = (value, params) => inst.check(schemas_checks.gte(value, params)); inst.min = (value, params) => inst.check(schemas_checks.gte(value, params)); inst.lt = (value, params) => inst.check(schemas_checks.lt(value, params)); inst.lte = (value, params) => inst.check(schemas_checks.lte(value, params)); inst.max = (value, params) => inst.check(schemas_checks.lte(value, params)); inst.positive = (params) => inst.check(schemas_checks.gt(BigInt(0), params)); inst.negative = (params) => inst.check(schemas_checks.lt(BigInt(0), params)); inst.nonpositive = (params) => inst.check(schemas_checks.lte(BigInt(0), params)); inst.nonnegative = (params) => inst.check(schemas_checks.gte(BigInt(0), params)); inst.multipleOf = (value, params) => inst.check(schemas_checks.multipleOf(value, params)); const bag = inst._zod.bag; inst.minValue = bag.minimum ?? null; inst.maxValue = bag.maximum ?? null; inst.format = bag.format ?? null; }))); function schemas_bigint(params) { return classic_schemas_core._bigint(ZodBigInt, params); } const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodBigIntFormat", (inst, def) => { classic_schemas_core.$ZodBigIntFormat.init(inst, def); ZodBigInt.init(inst, def); }))); // int64 function int64(params) { return classic_schemas_core._int64(ZodBigIntFormat, params); } // uint64 function uint64(params) { return classic_schemas_core._uint64(ZodBigIntFormat, params); } const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodSymbol", (inst, def) => { classic_schemas_core.$ZodSymbol.init(inst, def); ZodType.init(inst, def); }))); function symbol(params) { return classic_schemas_core._symbol(ZodSymbol, params); } const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodUndefined", (inst, def) => { classic_schemas_core.$ZodUndefined.init(inst, def); ZodType.init(inst, def); }))); function schemas_undefined(params) { return classic_schemas_core._undefined(ZodUndefined, params); } const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); ZodType.init(inst, def); }); function schemas_null(params) { return api_null(ZodNull, params); } const ZodAny = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodAny", (inst, def) => { classic_schemas_core.$ZodAny.init(inst, def); ZodType.init(inst, def); }))); function any() { return classic_schemas_core._any(ZodAny); } const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodType.init(inst, def); }); function unknown() { return _unknown(ZodUnknown); } const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); ZodType.init(inst, def); }); function never(params) { return _never(ZodNever, params); } const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodVoid", (inst, def) => { classic_schemas_core.$ZodVoid.init(inst, def); ZodType.init(inst, def); }))); function schemas_void(params) { return classic_schemas_core._void(ZodVoid, params); } const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodDate", (inst, def) => { classic_schemas_core.$ZodDate.init(inst, def); ZodType.init(inst, def); inst.min = (value, params) => inst.check(schemas_checks.gte(value, params)); inst.max = (value, params) => inst.check(schemas_checks.lte(value, params)); const c = inst._zod.bag; inst.minDate = c.minimum ? new Date(c.minimum) : null; inst.maxDate = c.maximum ? new Date(c.maximum) : null; }))); function schemas_date(params) { return classic_schemas_core._date(ZodDate, params); } const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); ZodType.init(inst, def); inst.element = def.element; inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); inst.nonempty = (params) => inst.check(_minLength(1, params)); inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); inst.length = (len, params) => inst.check(_length(len, params)); inst.unwrap = () => inst.element; }); function array(element, params) { return _array(ZodArray, element, params); } // .keyof function keyof(schema) { const shape = schema._zod.def.shape; return literal(Object.keys(shape)); } const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { $ZodObject.init(inst, def); ZodType.init(inst, def); defineLazy(inst, "shape", () => def.shape); inst.keyof = () => schemas_enum(Object.keys(inst._zod.def.shape)); inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall }); inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); // inst.nonstrict = () => inst.clone({ ...inst._zod.def, catchall: api.unknown() }); inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); inst.extend = (incoming) => { return extend(inst, incoming); }; inst.merge = (other) => merge(inst, other); inst.pick = (mask) => pick(inst, mask); inst.omit = (mask) => omit(inst, mask); inst.partial = (...args) => partial(ZodOptional, inst, args[0]); inst.required = (...args) => required(ZodNonOptional, inst, args[0]); }); function object(shape, params) { const def = { type: "object", get shape() { assignProp(this, "shape", { ...shape }); return this.shape; }, ...normalizeParams(params), }; return new ZodObject(def); } // strictObject function strictObject(shape, params) { return new ZodObject({ type: "object", get shape() { classic_schemas_util.assignProp(this, "shape", { ...shape }); return this.shape; }, catchall: never(), ...classic_schemas_util.normalizeParams(params), }); } // looseObject function looseObject(shape, params) { return new ZodObject({ type: "object", get shape() { assignProp(this, "shape", { ...shape }); return this.shape; }, catchall: unknown(), ...normalizeParams(params), }); } const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); ZodType.init(inst, def); inst.options = def.options; }); function union(options, params) { return new ZodUnion({ type: "union", options: options, ...normalizeParams(params), }); } const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { ZodUnion.init(inst, def); $ZodDiscriminatedUnion.init(inst, def); }); function discriminatedUnion(discriminator, options, params) { // const [options, params] = args; return new ZodDiscriminatedUnion({ type: "union", options, discriminator, ...normalizeParams(params), }); } const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); ZodType.init(inst, def); }); function intersection(left, right) { return new ZodIntersection({ type: "intersection", left: left, right: right, }); } const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodTuple", (inst, def) => { classic_schemas_core.$ZodTuple.init(inst, def); ZodType.init(inst, def); inst.rest = (rest) => inst.clone({ ...inst._zod.def, rest: rest, }); }))); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof classic_schemas_core.$ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new ZodTuple({ type: "tuple", items: items, rest, ...classic_schemas_util.normalizeParams(params), }); } const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodType.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function record(keyType, valueType, params) { return new ZodRecord({ type: "record", keyType, valueType: valueType, ...normalizeParams(params), }); } // type alksjf = core.output<core.$ZodRecordKey>; function partialRecord(keyType, valueType, params) { return new ZodRecord({ type: "record", keyType: union([keyType, never()]), valueType: valueType, ...classic_schemas_util.normalizeParams(params), }); } const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodMap", (inst, def) => { classic_schemas_core.$ZodMap.init(inst, def); ZodType.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }))); function map(keyType, valueType, params) { return new ZodMap({ type: "map", keyType: keyType, valueType: valueType, ...classic_schemas_util.normalizeParams(params), }); } const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodSet", (inst, def) => { classic_schemas_core.$ZodSet.init(inst, def); ZodType.init(inst, def); inst.min = (...args) => inst.check(classic_schemas_core._minSize(...args)); inst.nonempty = (params) => inst.check(classic_schemas_core._minSize(1, params)); inst.max = (...args) => inst.check(classic_schemas_core._maxSize(...args)); inst.size = (...args) => inst.check(classic_schemas_core._size(...args)); }))); function set(valueType, params) { return new ZodSet({ type: "set", valueType: valueType, ...classic_schemas_util.normalizeParams(params), }); } const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodType.init(inst, def); inst.enum = def.entries; inst.options = Object.values(def.entries); const keys = new Set(Object.keys(def.entries)); inst.extract = (values, params) => { const newEntries = {}; for (const value of values) { if (keys.has(value)) { newEntries[value] = def.entries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum({ ...def, checks: [], ...normalizeParams(params), entries: newEntries, }); }; inst.exclude = (values, params) => { const newEntries = { ...def.entries }; for (const value of values) { if (keys.has(value)) { delete newEntries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum({ ...def, checks: [], ...normalizeParams(params), entries: newEntries, }); }; }); function schemas_enum(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new ZodEnum({ type: "enum", entries, ...normalizeParams(params), }); } /** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. * * ```ts * enum Colors { red, green, blue } * z.enum(Colors); * ``` */ function nativeEnum(entries, params) { return new ZodEnum({ type: "enum", entries, ...classic_schemas_util.normalizeParams(params), }); } const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodType.init(inst, def); inst.values = new Set(def.values); Object.defineProperty(inst, "value", { get() { if (def.values.length > 1) { throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); } return def.values[0]; }, }); }); function literal(value, params) { return new ZodLiteral({ type: "literal", values: Array.isArray(value) ? value : [value], ...normalizeParams(params), }); } const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodFile", (inst, def) => { classic_schemas_core.$ZodFile.init(inst, def); ZodType.init(inst, def); inst.min = (size, params) => inst.check(classic_schemas_core._minSize(size, params)); inst.max = (size, params) => inst.check(classic_schemas_core._maxSize(size, params)); inst.mime = (types, params) => inst.check(classic_schemas_core._mime(Array.isArray(types) ? types : [types], params)); }))); function file(params) { return classic_schemas_core._file(ZodFile, params); } const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.addIssue = (issue) => { if (typeof issue === "string") { payload.issues.push(util_issue(issue, payload.value, def)); } else { // for Zod 3 backwards compatibility const _issue = issue; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = inst); _issue.continue ?? (_issue.continue = true); payload.issues.push(util_issue(_issue)); } }; const output = def.transform(payload.value, payload); if (output instanceof Promise) { return output.then((output) => { payload.value = output; return payload; }); } payload.value = output; return payload; }; }); function transform(fn) { return new ZodTransform({ type: "transform", transform: fn, }); } const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function optional(innerType) { return new ZodOptional({ type: "optional", innerType: innerType, }); } const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nullable(innerType) { return new ZodNullable({ type: "nullable", innerType: innerType, }); } // nullish function schemas_nullish(innerType) { return optional(nullable(innerType)); } const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); function schemas_default(innerType, defaultValue) { return new ZodDefault({ type: "default", innerType: innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; }, }); } const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function prefault(innerType, defaultValue) { return new ZodPrefault({ type: "prefault", innerType: innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; }, }); } const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional(innerType, params) { return new ZodNonOptional({ type: "nonoptional", innerType: innerType, ...normalizeParams(params), }); } const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodSuccess", (inst, def) => { classic_schemas_core.$ZodSuccess.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }))); function success(innerType) { return new ZodSuccess({ type: "success", innerType: innerType, }); } const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); function schemas_catch(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType: innerType, catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), }); } const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodNaN", (inst, def) => { classic_schemas_core.$ZodNaN.init(inst, def); ZodType.init(inst, def); }))); function nan(params) { return classic_schemas_core._nan(ZodNaN, params); } const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); ZodType.init(inst, def); inst.in = def.in; inst.out = def.out; }); function pipe(in_, out) { return new ZodPipe({ type: "pipe", in: in_, out: out, // ...util.normalizeParams(params), }); } const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); ZodType.init(inst, def); }); function readonly(innerType) { return new ZodReadonly({ type: "readonly", innerType: innerType, }); } const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodTemplateLiteral", (inst, def) => { classic_schemas_core.$ZodTemplateLiteral.init(inst, def); ZodType.init(inst, def); }))); function templateLiteral(parts, params) { return new ZodTemplateLiteral({ type: "template_literal", parts, ...classic_schemas_util.normalizeParams(params), }); } const ZodLazy = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodLazy", (inst, def) => { classic_schemas_core.$ZodLazy.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.getter(); }))); function lazy(getter) { return new ZodLazy({ type: "lazy", getter: getter, }); } const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (classic_schemas_core.$constructor("ZodPromise", (inst, def) => { classic_schemas_core.$ZodPromise.init(inst, def); ZodType.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }))); function promise(innerType) { return new ZodPromise({ type: "promise", innerType: innerType, }); } const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); ZodType.init(inst, def); }); // custom checks function check(fn) { const ch = new $ZodCheck({ check: "custom", // ...util.normalizeParams(params), }); ch._zod.check = fn; return ch; } function custom(fn, _params) { return _custom(ZodCustom, fn ?? (() => true), _params); } function refine(fn, _params = {}) { return _refine(ZodCustom, fn, _params); } // superRefine function superRefine(fn) { const ch = check((payload) => { payload.addIssue = (issue) => { if (typeof issue === "string") { payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); } else { // for Zod 3 backwards compatibility const _issue = issue; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(util_issue(_issue)); } }; return fn(payload.value, payload); }); return ch; } function _instanceof(cls, params = { error: `Input not instance of ${cls.name}`, }) { const inst = new ZodCustom({ type: "custom", check: "custom", fn: (data) => data instanceof cls, abort: true, ...classic_schemas_util.normalizeParams(params), }); inst._zod.bag.Class = cls; return inst; } // stringbool const stringbool = (...args) => classic_schemas_core._stringbool({ Pipe: ZodPipe, Boolean: ZodBoolean, String: ZodString, Transform: ZodTransform, }, ...args); function json(params) { const jsonSchema = lazy(() => { return union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), array(jsonSchema), record(schemas_string(), jsonSchema)]); }); return jsonSchema; } // preprocess // /** @deprecated Use `z.pipe()` and `z.transform()` instead. */ function preprocess(fn, schema) { return pipe(transform(fn), schema); } ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/types.js const LATEST_PROTOCOL_VERSION = '2025-11-25'; const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; /* JSON-RPC types */ const JSONRPC_VERSION = '2.0'; /** * Assert 'object' type schema. * * @internal */ const AssertObjectSchema = custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); /** * A progress token, used to associate progress notifications with the original request. */ const ProgressTokenSchema = union([schemas_string(), schemas_number().int()]); /** * An opaque token used to represent a cursor for pagination. */ const CursorSchema = schemas_string(); /** * Task creation parameters, used to ask that the server create a task to represent a request. */ const TaskCreationParamsSchema = looseObject({ /** * Requested duration in milliseconds to retain task from creation. */ ttl: schemas_number().optional(), /** * Time in milliseconds to wait between task status requests. */ pollInterval: schemas_number().optional() }); const TaskMetadataSchema = object({ ttl: schemas_number().optional() }); /** * Metadata for associating messages with a task. * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. */ const RelatedTaskMetadataSchema = object({ taskId: schemas_string() }); const RequestMetaSchema = looseObject({ /** * 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. */ progressToken: ProgressTokenSchema.optional(), /** * If specified, this request is related to the provided task. */ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() }); /** * Common params for any request. */ const BaseRequestParamsSchema = object({ /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ _meta: RequestMetaSchema.optional() }); /** * Common params for any task-augmented request. */ const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * If specified, the caller is requesting task-augmented execution for this request. * The request will return a CreateTaskResult immediately, and the actual result can be * retrieved later via tasks/result. * * Task augmentation is subject to capability negotiation - receivers MUST declare support * for task augmentation of specific request types in their capabilities. */ task: TaskMetadataSchema.optional() }); /** * Checks if a value is a valid TaskAugmentedRequestParams. * @param value - The value to check. * * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. */ const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; const RequestSchema = object({ method: schemas_string(), params: BaseRequestParamsSchema.loose().optional() }); const NotificationsParamsSchema = object({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); const NotificationSchema = object({ method: schemas_string(), params: NotificationsParamsSchema.loose().optional() }); const ResultSchema = looseObject({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); /** * A uniquely identifying ID for a request in JSON-RPC. */ const RequestIdSchema = union([schemas_string(), schemas_number().int()]); /** * A request that expects a response. */ const JSONRPCRequestSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, ...RequestSchema.shape }) .strict(); const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; /** * A notification which does not expect a response. */ const JSONRPCNotificationSchema = object({ jsonrpc: literal(JSONRPC_VERSION), ...NotificationSchema.shape }) .strict(); const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; /** * A successful (non-error) response to a request. */ const JSONRPCResultResponseSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, result: ResultSchema }) .strict(); /** * Checks if a value is a valid JSONRPCResultResponse. * @param value - The value to check. * * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. */ const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; /** * @deprecated Use {@link isJSONRPCResultResponse} instead. * * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) */ const isJSONRPCResponse = (/* unused pure expression or super */ null && (isJSONRPCResultResponse)); /** * Error codes defined by the JSON-RPC specification. */ var ErrorCode; (function (ErrorCode) { // SDK error codes ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; // Standard JSON-RPC error codes ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; // MCP-specific error codes ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; })(ErrorCode || (ErrorCode = {})); /** * A response to a request that indicates an error occurred. */ const JSONRPCErrorResponseSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema.optional(), error: object({ /** * The error type that occurred. */ code: schemas_number().int(), /** * A short description of the error. The message SHOULD be limited to a concise single sentence. */ message: schemas_string(), /** * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ data: unknown().optional() }) }) .strict(); /** * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. */ const JSONRPCErrorSchema = (/* unused pure expression or super */ null && (JSONRPCErrorResponseSchema)); /** * Checks if a value is a valid JSONRPCErrorResponse. * @param value - The value to check. * * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. */ const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; /** * @deprecated Use {@link isJSONRPCErrorResponse} instead. */ const isJSONRPCError = (/* unused pure expression or super */ null && (isJSONRPCErrorResponse)); const JSONRPCMessageSchema = union([ JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema ]); const JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); /* Empty result */ /** * A response that indicates success but carries no data. */ const EmptyResultSchema = ResultSchema.strict(); const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the request to cancel. * * This MUST correspond to the ID of a request previously issued in the same direction. */ requestId: RequestIdSchema.optional(), /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. */ reason: schemas_string().optional() }); /* Cancellation */ /** * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. * * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. * * This notification indicates that the result will be unused, so any associated processing SHOULD cease. * * A client MUST NOT attempt to cancel its `initialize` request. */ const CancelledNotificationSchema = NotificationSchema.extend({ method: literal('notifications/cancelled'), params: CancelledNotificationParamsSchema }); /* Base Metadata */ /** * Icon schema for use in tools, prompts, resources, and implementations. */ const IconSchema = object({ /** * URL or data URI for the icon. */ src: schemas_string(), /** * Optional MIME type for the icon. */ mimeType: schemas_string().optional(), /** * Optional array of strings that specify sizes at which the icon can be used. * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. * * If not provided, the client should assume that the icon can be used at any size. */ sizes: array(schemas_string()).optional(), /** * Optional specifier for the theme this icon is designed for. `light` indicates * the icon is designed to be used with a light background, and `dark` indicates * the icon is designed to be used with a dark background. * * If not provided, the client should assume the icon can be used with any theme. */ theme: schemas_enum(['light', 'dark']).optional() }); /** * Base schema to add `icons` property. * */ const IconsSchema = object({ /** * Optional set of sized icons that the client can display in a user interface. * * Clients that support rendering icons MUST support at least the following MIME types: * - `image/png` - PNG images (safe, universal compatibility) * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) * * Clients that support rendering icons SHOULD also support: * - `image/svg+xml` - SVG images (scalable but requires security precautions) * - `image/webp` - WebP images (modern, efficient format) */ icons: array(IconSchema).optional() }); /** * Base metadata interface for common properties across resources, tools, prompts, and implementations. */ const BaseMetadataSchema = object({ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ name: schemas_string(), /** * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, * even by those unfamiliar with domain-specific terminology. * * If not provided, the name should be used for display (except for Tool, * where `annotations.title` should be given precedence over using `name`, * if present). */ title: schemas_string().optional() }); /* Initialization */ /** * Describes the name and version of an MCP implementation. */ const ImplementationSchema = BaseMetadataSchema.extend({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, version: schemas_string(), /** * An optional URL of the website for this implementation. */ websiteUrl: schemas_string().optional(), /** * An optional human-readable description of what this implementation does. * * This can be used by clients or servers to provide context about their purpose * and capabilities. For example, a server might describe the types of resources * or tools it provides, while a client might describe its intended use case. */ description: schemas_string().optional() }); const FormElicitationCapabilitySchema = intersection(object({ applyDefaults: schemas_boolean().optional() }), record(schemas_string(), unknown())); const ElicitationCapabilitySchema = preprocess(value => { if (value && typeof value === 'object' && !Array.isArray(value)) { if (Object.keys(value).length === 0) { return { form: {} }; } } return value; }, intersection(object({ form: FormElicitationCapabilitySchema.optional(), url: AssertObjectSchema.optional() }), record(schemas_string(), unknown()).optional())); /** * Task capabilities for clients, indicating which request types support task creation. */ const ClientTasksCapabilitySchema = looseObject({ /** * Present if the client supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the client supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for sampling requests. */ sampling: looseObject({ createMessage: AssertObjectSchema.optional() }) .optional(), /** * Task support for elicitation requests. */ elicitation: looseObject({ create: AssertObjectSchema.optional() }) .optional() }) .optional() }); /** * Task capabilities for servers, indicating which request types support task creation. */ const ServerTasksCapabilitySchema = looseObject({ /** * Present if the server supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the server supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for tool requests. */ tools: looseObject({ call: AssertObjectSchema.optional() }) .optional() }) .optional() }); /** * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. */ const ClientCapabilitiesSchema = object({ /** * Experimental, non-standard capabilities that the client supports. */ experimental: record(schemas_string(), AssertObjectSchema).optional(), /** * Present if the client supports sampling from an LLM. */ sampling: object({ /** * Present if the client supports context inclusion via includeContext parameter. * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). */ context: AssertObjectSchema.optional(), /** * Present if the client supports tool use via tools and toolChoice parameters. */ tools: AssertObjectSchema.optional() }) .optional(), /** * Present if the client supports eliciting user input. */ elicitation: ElicitationCapabilitySchema.optional(), /** * Present if the client supports listing roots. */ roots: object({ /** * Whether the client supports issuing notifications for changes to the roots list. */ listChanged: schemas_boolean().optional() }) .optional(), /** * Present if the client supports task creation. */ tasks: ClientTasksCapabilitySchema.optional(), /** * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(schemas_string(), AssertObjectSchema).optional() }); const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. */ protocolVersion: schemas_string(), capabilities: ClientCapabilitiesSchema, clientInfo: ImplementationSchema }); /** * This request is sent from the client to the server when it first connects, asking it to begin initialization. */ const InitializeRequestSchema = RequestSchema.extend({ method: literal('initialize'), params: InitializeRequestParamsSchema }); const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; /** * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. */ const ServerCapabilitiesSchema = object({ /** * Experimental, non-standard capabilities that the server supports. */ experimental: record(schemas_string(), AssertObjectSchema).optional(), /** * Present if the server supports sending log messages to the client. */ logging: AssertObjectSchema.optional(), /** * Present if the server supports sending completions to the client. */ completions: AssertObjectSchema.optional(), /** * Present if the server offers any prompt templates. */ prompts: object({ /** * Whether this server supports issuing notifications for changes to the prompt list. */ listChanged: schemas_boolean().optional() }) .optional(), /** * Present if the server offers any resources to read. */ resources: object({ /** * Whether this server supports clients subscribing to resource updates. */ subscribe: schemas_boolean().optional(), /** * Whether this server supports issuing notifications for changes to the resource list. */ listChanged: schemas_boolean().optional() }) .optional(), /** * Present if the server offers any tools to call. */ tools: object({ /** * Whether this server supports issuing notifications for changes to the tool list. */ listChanged: schemas_boolean().optional() }) .optional(), /** * Present if the server supports task creation. */ tasks: ServerTasksCapabilitySchema.optional(), /** * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(schemas_string(), AssertObjectSchema).optional() }); /** * After receiving an initialize request from the client, the server sends this response. */ const InitializeResultSchema = ResultSchema.extend({ /** * 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. */ protocolVersion: schemas_string(), capabilities: ServerCapabilitiesSchema, serverInfo: ImplementationSchema, /** * Instructions describing how to use the server and its features. * * 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. */ instructions: schemas_string().optional() }); /** * This notification is sent from the client to the server after initialization has finished. */ const InitializedNotificationSchema = NotificationSchema.extend({ method: literal('notifications/initialized'), params: NotificationsParamsSchema.optional() }); const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; /* Ping */ /** * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. */ const PingRequestSchema = RequestSchema.extend({ method: literal('ping'), params: BaseRequestParamsSchema.optional() }); /* Progress notifications */ const ProgressSchema = object({ /** * The progress thus far. This should increase every time progress is made, even if the total is unknown. */ progress: schemas_number(), /** * Total number of items to process (or total progress required), if known. */ total: optional(schemas_number()), /** * An optional message describing the current progress. */ message: optional(schemas_string()) }); const ProgressNotificationParamsSchema = object({ ...NotificationsParamsSchema.shape, ...ProgressSchema.shape, /** * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. */ progressToken: ProgressTokenSchema }); /** * An out-of-band notification used to inform the receiver of a progress update for a long-running request. * * @category notifications/progress */ const ProgressNotificationSchema = NotificationSchema.extend({ method: literal('notifications/progress'), params: ProgressNotificationParamsSchema }); const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * An opaque token representing the current pagination position. * If provided, the server should return results starting after this cursor. */ cursor: CursorSchema.optional() }); /* Pagination */ const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); const PaginatedResultSchema = ResultSchema.extend({ /** * An opaque token representing the pagination position after the last returned result. * If present, there may be more results available. */ nextCursor: CursorSchema.optional() }); /** * The status of a task. * */ const TaskStatusSchema = schemas_enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); /* Tasks */ /** * A pollable state object associated with a request. */ const TaskSchema = object({ taskId: schemas_string(), status: TaskStatusSchema, /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. */ ttl: union([schemas_number(), schemas_null()]), /** * ISO 8601 timestamp when the task was created. */ createdAt: schemas_string(), /** * ISO 8601 timestamp when the task was last updated. */ lastUpdatedAt: schemas_string(), pollInterval: optional(schemas_number()), /** * Optional diagnostic message for failed tasks or other status information. */ statusMessage: optional(schemas_string()) }); /** * Result returned when a task is created, containing the task data wrapped in a task field. */ const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); /** * Parameters for task status notification. */ const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); /** * A notification sent when a task's status changes. */ const TaskStatusNotificationSchema = NotificationSchema.extend({ method: literal('notifications/tasks/status'), params: TaskStatusNotificationParamsSchema }); /** * A request to get the state of a specific task. */ const GetTaskRequestSchema = RequestSchema.extend({ method: literal('tasks/get'), params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) }); /** * The response to a tasks/get request. */ const GetTaskResultSchema = ResultSchema.merge(TaskSchema); /** * A request to get the result of a specific task. */ const GetTaskPayloadRequestSchema = RequestSchema.extend({ method: literal('tasks/result'), params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) }); /** * The response to a tasks/result request. * The structure matches the result type of the original request. * For example, a tools/call task would return the CallToolResult structure. * */ const GetTaskPayloadResultSchema = ResultSchema.loose(); /** * A request to list tasks. */ const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal('tasks/list') }); /** * The response to a tasks/list request. */ const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); /** * A request to cancel a specific task. */ const CancelTaskRequestSchema = RequestSchema.extend({ method: literal('tasks/cancel'), params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) }); /** * The response to a tasks/cancel request. */ const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); /* Resources */ /** * The contents of a specific resource or sub-resource. */ const ResourceContentsSchema = object({ /** * The URI of this resource. */ uri: schemas_string(), /** * The MIME type of this resource, if known. */ mimeType: optional(schemas_string()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); const TextResourceContentsSchema = ResourceContentsSchema.extend({ /** * The text of the item. This must only be set if the item can actually be represented as text (not binary data). */ text: schemas_string() }); /** * A Zod schema for validating Base64 strings that is more performant and * robust for very large inputs than the default regex-based check. It avoids * stack overflows by using the native `atob` function for validation. */ const Base64Schema = schemas_string().refine(val => { try { // atob throws a DOMException if the string contains characters // that are not part of the Base64 character set. atob(val); return true; } catch { return false; } }, { message: 'Invalid Base64 string' }); const BlobResourceContentsSchema = ResourceContentsSchema.extend({ /** * A base64-encoded string representing the binary data of the item. */ blob: Base64Schema }); /** * The sender or recipient of messages and data in a conversation. */ const RoleSchema = schemas_enum(['user', 'assistant']); /** * Optional annotations providing clients additional context about a resource. */ const AnnotationsSchema = object({ /** * Intended audience(s) for the resource. */ audience: array(RoleSchema).optional(), /** * Importance hint for the resource, from 0 (least) to 1 (most). */ priority: schemas_number().min(0).max(1).optional(), /** * ISO 8601 timestamp for the most recent modification. */ lastModified: iso_datetime({ offset: true }).optional() }); /** * A known resource that the server is capable of reading. */ const ResourceSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * The URI of this resource. */ uri: schemas_string(), /** * A description of what this resource represents. * * 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. */ description: optional(schemas_string()), /** * The MIME type of this resource, if known. */ mimeType: optional(schemas_string()), /** * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. * * This can be used by Hosts to display file sizes and estimate context window usage. */ size: optional(schemas_number()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); /** * A template description for resources available on the server. */ const ResourceTemplateSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A URI template (according to RFC 6570) that can be used to construct resource URIs. */ uriTemplate: schemas_string(), /** * A description of what this template is for. * * 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. */ description: optional(schemas_string()), /** * 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. */ mimeType: optional(schemas_string()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); /** * Sent from the client to request a list of resources the server has. */ const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal('resources/list') }); /** * The server's response to a resources/list request from the client. */ const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); /** * Sent from the client to request a list of resource templates the server has. */ const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal('resources/templates/list') }); /** * The server's response to a resources/templates/list request from the client. */ const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. * * @format uri */ uri: schemas_string() }); /** * Parameters for a `resources/read` request. */ const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; /** * Sent from the client to the server, to read a specific resource URI. */ const ReadResourceRequestSchema = RequestSchema.extend({ method: literal('resources/read'), params: ReadResourceRequestParamsSchema }); /** * The server's response to a resources/read request from the client. */ const ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); /** * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. */ const ResourceListChangedNotificationSchema = NotificationSchema.extend({ method: literal('notifications/resources/list_changed'), params: NotificationsParamsSchema.optional() }); const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; /** * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. */ const SubscribeRequestSchema = RequestSchema.extend({ method: literal('resources/subscribe'), params: SubscribeRequestParamsSchema }); const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; /** * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. */ const UnsubscribeRequestSchema = RequestSchema.extend({ method: literal('resources/unsubscribe'), params: UnsubscribeRequestParamsSchema }); /** * Parameters for a `notifications/resources/updated` notification. */ const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. */ uri: schemas_string() }); /** * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. */ const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ method: literal('notifications/resources/updated'), params: ResourceUpdatedNotificationParamsSchema }); /* Prompts */ /** * Describes an argument that a prompt can accept. */ const PromptArgumentSchema = object({ /** * The name of the argument. */ name: schemas_string(), /** * A human-readable description of the argument. */ description: optional(schemas_string()), /** * Whether this argument must be provided. */ required: optional(schemas_boolean()) }); /** * A prompt or prompt template that the server offers. */ const PromptSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * An optional description of what this prompt provides */ description: optional(schemas_string()), /** * A list of arguments to use for templating the prompt. */ arguments: optional(array(PromptArgumentSchema)), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); /** * Sent from the client to request a list of prompts and prompt templates the server has. */ const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal('prompts/list') }); /** * The server's response to a prompts/list request from the client. */ const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); /** * Parameters for a `prompts/get` request. */ const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The name of the prompt or prompt template. */ name: schemas_string(), /** * Arguments to use for templating the prompt. */ arguments: record(schemas_string(), schemas_string()).optional() }); /** * Used by the client to get a prompt provided by the server. */ const GetPromptRequestSchema = RequestSchema.extend({ method: literal('prompts/get'), params: GetPromptRequestParamsSchema }); /** * Text provided to or from an LLM. */ const TextContentSchema = object({ type: literal('text'), /** * The text content of the message. */ text: schemas_string(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * An image provided to or from an LLM. */ const ImageContentSchema = object({ type: literal('image'), /** * The base64-encoded image data. */ data: Base64Schema, /** * The MIME type of the image. Different providers may support different image types. */ mimeType: schemas_string(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * An Audio provided to or from an LLM. */ const AudioContentSchema = object({ type: literal('audio'), /** * The base64-encoded audio data. */ data: Base64Schema, /** * The MIME type of the audio. Different providers may support different audio types. */ mimeType: schemas_string(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * A tool call request from an assistant (LLM). * Represents the assistant's request to use a tool. */ const ToolUseContentSchema = object({ type: literal('tool_use'), /** * The name of the tool to invoke. * Must match a tool name from the request's tools array. */ name: schemas_string(), /** * Unique identifier for this tool call. * Used to correlate with ToolResultContent in subsequent messages. */ id: schemas_string(), /** * Arguments to pass to the tool. * Must conform to the tool's inputSchema. */ input: record(schemas_string(), unknown()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * The contents of a resource, embedded into a prompt or tool call result. */ const EmbeddedResourceSchema = object({ type: literal('resource'), resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * A resource that the server is capable of reading, included in a prompt or tool call result. * * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. */ const ResourceLinkSchema = ResourceSchema.extend({ type: literal('resource_link') }); /** * A content block that can be used in prompts and tool results. */ const ContentBlockSchema = union([ TextContentSchema, ImageContentSchema, AudioContentSchema, ResourceLinkSchema, EmbeddedResourceSchema ]); /** * Describes a message returned as part of a prompt. */ const PromptMessageSchema = object({ role: RoleSchema, content: ContentBlockSchema }); /** * The server's response to a prompts/get request from the client. */ const GetPromptResultSchema = ResultSchema.extend({ /** * An optional description for the prompt. */ description: schemas_string().optional(), messages: array(PromptMessageSchema) }); /** * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. */ const PromptListChangedNotificationSchema = NotificationSchema.extend({ method: literal('notifications/prompts/list_changed'), params: NotificationsParamsSchema.optional() }); /* Tools */ /** * Additional properties describing a Tool to clients. * * NOTE: all properties in ToolAnnotations are **hints**. * They are not guaranteed to provide a faithful description of * tool behavior (including descriptive properties like `title`). * * Clients should never make tool use decisions based on ToolAnnotations * received from untrusted servers. */ const ToolAnnotationsSchema = object({ /** * A human-readable title for the tool. */ title: schemas_string().optional(), /** * If true, the tool does not modify its environment. * * Default: false */ readOnlyHint: schemas_boolean().optional(), /** * If true, the tool may perform destructive updates to its environment. * If false, the tool performs only additive updates. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: true */ destructiveHint: schemas_boolean().optional(), /** * If true, calling the tool repeatedly with the same arguments * will have no additional effect on the its environment. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: false */ idempotentHint: schemas_boolean().optional(), /** * If true, this tool may interact with an "open world" of external * entities. If false, the tool's domain of interaction is closed. * For example, the world of a web search tool is open, whereas that * of a memory tool is not. * * Default: true */ openWorldHint: schemas_boolean().optional() }); /** * Execution-related properties for a tool. */ const ToolExecutionSchema = object({ /** * Indicates the tool's preference for task-augmented execution. * - "required": Clients MUST invoke the tool as a task * - "optional": Clients MAY invoke the tool as a task or normal request * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task * * If not present, defaults to "forbidden". */ taskSupport: schemas_enum(['required', 'optional', 'forbidden']).optional() }); /** * Definition for a tool the client can call. */ const ToolSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A human-readable description of the tool. */ description: schemas_string().optional(), /** * A JSON Schema 2020-12 object defining the expected parameters for the tool. * Must have type: 'object' at the root level per MCP spec. */ inputSchema: object({ type: literal('object'), properties: record(schemas_string(), AssertObjectSchema).optional(), required: array(schemas_string()).optional() }) .catchall(unknown()), /** * An optional JSON Schema 2020-12 object defining the structure of the tool's output * returned in the structuredContent field of a CallToolResult. * Must have type: 'object' at the root level per MCP spec. */ outputSchema: object({ type: literal('object'), properties: record(schemas_string(), AssertObjectSchema).optional(), required: array(schemas_string()).optional() }) .catchall(unknown()) .optional(), /** * Optional additional tool information. */ annotations: ToolAnnotationsSchema.optional(), /** * Execution-related properties for this tool. */ execution: ToolExecutionSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * Sent from the client to request a list of tools the server has. */ const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal('tools/list') }); /** * The server's response to a tools/list request from the client. */ const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); /** * The server's response to a tool call. */ const CallToolResultSchema = ResultSchema.extend({ /** * A list of content objects that represent the result of the tool call. * * If the Tool does not define an outputSchema, this field MUST be present in the result. * For backwards compatibility, this field is always present, but it may be empty. */ content: array(ContentBlockSchema).default([]), /** * An object containing structured tool output. * * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. */ structuredContent: record(schemas_string(), unknown()).optional(), /** * Whether the tool call ended in an error. * * If not set, this is assumed to be false (the call was successful). * * Any errors that originate from the tool SHOULD be reported inside the result * object, with `isError` set to true, _not_ as an MCP protocol-level error * response. Otherwise, the LLM would not be able to see that an error occurred * and self-correct. * * However, any errors in _finding_ the tool, an error indicating that the * server does not support tool calls, or any other exceptional conditions, * should be reported as an MCP error response. */ isError: schemas_boolean().optional() }); /** * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. */ const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); /** * Parameters for a `tools/call` request. */ const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The name of the tool to call. */ name: schemas_string(), /** * Arguments to pass to the tool. */ arguments: record(schemas_string(), unknown()).optional() }); /** * Used by the client to invoke a tool provided by the server. */ const CallToolRequestSchema = RequestSchema.extend({ method: literal('tools/call'), params: CallToolRequestParamsSchema }); /** * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. */ const ToolListChangedNotificationSchema = NotificationSchema.extend({ method: literal('notifications/tools/list_changed'), params: NotificationsParamsSchema.optional() }); /** * Base schema for list changed subscription options (without callback). * Used internally for Zod validation of autoRefresh and debounceMs. */ const ListChangedOptionsBaseSchema = object({ /** * If true, the list will be refreshed automatically when a list changed notification is received. * The callback will be called with the updated list. * * If false, the callback will be called with null items, allowing manual refresh. * * @default true */ autoRefresh: schemas_boolean().default(true), /** * Debounce time in milliseconds for list changed notification processing. * * Multiple notifications received within this timeframe will only trigger one refresh. * Set to 0 to disable debouncing. * * @default 300 */ debounceMs: schemas_number().int().nonnegative().default(300) }); /* Logging */ /** * The severity of a log message. */ const LoggingLevelSchema = schemas_enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); /** * Parameters for a `logging/setLevel` request. */ const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * 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. */ level: LoggingLevelSchema }); /** * A request from the client to the server, to enable or adjust logging. */ const SetLevelRequestSchema = RequestSchema.extend({ method: literal('logging/setLevel'), params: SetLevelRequestParamsSchema }); /** * Parameters for a `notifications/message` notification. */ const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The severity of this log message. */ level: LoggingLevelSchema, /** * An optional name of the logger issuing this message. */ logger: schemas_string().optional(), /** * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. */ data: unknown() }); /** * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. */ const LoggingMessageNotificationSchema = NotificationSchema.extend({ method: literal('notifications/message'), params: LoggingMessageNotificationParamsSchema }); /* Sampling */ /** * Hints to use for model selection. */ const ModelHintSchema = object({ /** * A hint for a model name. */ name: schemas_string().optional() }); /** * The server's preferences for model selection, requested of the client during sampling. */ const ModelPreferencesSchema = object({ /** * Optional hints to use for model selection. */ hints: array(ModelHintSchema).optional(), /** * How much to prioritize cost when selecting a model. */ costPriority: schemas_number().min(0).max(1).optional(), /** * How much to prioritize sampling speed (latency) when selecting a model. */ speedPriority: schemas_number().min(0).max(1).optional(), /** * How much to prioritize intelligence and capabilities when selecting a model. */ intelligencePriority: schemas_number().min(0).max(1).optional() }); /** * Controls tool usage behavior in sampling requests. */ const ToolChoiceSchema = object({ /** * Controls when tools are used: * - "auto": Model decides whether to use tools (default) * - "required": Model MUST use at least one tool before completing * - "none": Model MUST NOT use any tools */ mode: schemas_enum(['auto', 'required', 'none']).optional() }); /** * The result of a tool execution, provided by the user (server). * Represents the outcome of invoking a tool requested via ToolUseContent. */ const ToolResultContentSchema = object({ type: literal('tool_result'), toolUseId: schemas_string().describe('The unique identifier for the corresponding tool call.'), content: array(ContentBlockSchema).default([]), structuredContent: object({}).loose().optional(), isError: schemas_boolean().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * Basic content types for sampling responses (without tool use). * Used for backwards-compatible CreateMessageResult when tools are not used. */ const SamplingContentSchema = discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]); /** * Content block types allowed in sampling messages. * This includes text, image, audio, tool use requests, and tool results. */ const SamplingMessageContentBlockSchema = discriminatedUnion('type', [ TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, ToolResultContentSchema ]); /** * Describes a message issued to or received from an LLM API. */ const SamplingMessageSchema = object({ role: RoleSchema, content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * Parameters for a `sampling/createMessage` request. */ const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ messages: array(SamplingMessageSchema), /** * The server's preferences for which model to select. The client MAY modify or omit this request. */ modelPreferences: ModelPreferencesSchema.optional(), /** * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. */ systemPrompt: schemas_string().optional(), /** * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. * The client MAY ignore this request. * * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. */ includeContext: schemas_enum(['none', 'thisServer', 'allServers']).optional(), temperature: schemas_number().optional(), /** * The requested maximum number of tokens to sample (to prevent runaway completions). * * The client MAY choose to sample fewer tokens than the requested maximum. */ maxTokens: schemas_number().int(), stopSequences: array(schemas_string()).optional(), /** * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. */ metadata: AssertObjectSchema.optional(), /** * Tools that the model may use during generation. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. */ tools: array(ToolSchema).optional(), /** * Controls how the model uses tools. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. * Default is `{ mode: "auto" }`. */ toolChoice: ToolChoiceSchema.optional() }); /** * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. */ const CreateMessageRequestSchema = RequestSchema.extend({ method: literal('sampling/createMessage'), params: CreateMessageRequestParamsSchema }); /** * The client's response to a sampling/create_message request from the server. * This is the backwards-compatible version that returns single content (no arrays). * Used when the request does not include tools. */ const CreateMessageResultSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: schemas_string(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(schemas_enum(['endTurn', 'stopSequence', 'maxTokens']).or(schemas_string())), role: RoleSchema, /** * Response content. Single content block (text, image, or audio). */ content: SamplingContentSchema }); /** * The client's response to a sampling/create_message request when tools were provided. * This version supports array content for tool use flows. */ const CreateMessageResultWithToolsSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: schemas_string(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * - "toolUse": The model wants to use one or more tools * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(schemas_enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(schemas_string())), role: RoleSchema, /** * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". */ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) }); /* Elicitation */ /** * Primitive schema definition for boolean fields. */ const BooleanSchemaSchema = object({ type: literal('boolean'), title: schemas_string().optional(), description: schemas_string().optional(), default: schemas_boolean().optional() }); /** * Primitive schema definition for string fields. */ const StringSchemaSchema = object({ type: literal('string'), title: schemas_string().optional(), description: schemas_string().optional(), minLength: schemas_number().optional(), maxLength: schemas_number().optional(), format: schemas_enum(['email', 'uri', 'date', 'date-time']).optional(), default: schemas_string().optional() }); /** * Primitive schema definition for number fields. */ const NumberSchemaSchema = object({ type: schemas_enum(['number', 'integer']), title: schemas_string().optional(), description: schemas_string().optional(), minimum: schemas_number().optional(), maximum: schemas_number().optional(), default: schemas_number().optional() }); /** * Schema for single-selection enumeration without display titles for options. */ const UntitledSingleSelectEnumSchemaSchema = object({ type: literal('string'), title: schemas_string().optional(), description: schemas_string().optional(), enum: array(schemas_string()), default: schemas_string().optional() }); /** * Schema for single-selection enumeration with display titles for each option. */ const TitledSingleSelectEnumSchemaSchema = object({ type: literal('string'), title: schemas_string().optional(), description: schemas_string().optional(), oneOf: array(object({ const: schemas_string(), title: schemas_string() })), default: schemas_string().optional() }); /** * Use TitledSingleSelectEnumSchema instead. * This interface will be removed in a future version. */ const LegacyTitledEnumSchemaSchema = object({ type: literal('string'), title: schemas_string().optional(), description: schemas_string().optional(), enum: array(schemas_string()), enumNames: array(schemas_string()).optional(), default: schemas_string().optional() }); // Combined single selection enumeration const SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); /** * Schema for multiple-selection enumeration without display titles for options. */ const UntitledMultiSelectEnumSchemaSchema = object({ type: literal('array'), title: schemas_string().optional(), description: schemas_string().optional(), minItems: schemas_number().optional(), maxItems: schemas_number().optional(), items: object({ type: literal('string'), enum: array(schemas_string()) }), default: array(schemas_string()).optional() }); /** * Schema for multiple-selection enumeration with display titles for each option. */ const TitledMultiSelectEnumSchemaSchema = object({ type: literal('array'), title: schemas_string().optional(), description: schemas_string().optional(), minItems: schemas_number().optional(), maxItems: schemas_number().optional(), items: object({ anyOf: array(object({ const: schemas_string(), title: schemas_string() })) }), default: array(schemas_string()).optional() }); /** * Combined schema for multiple-selection enumeration */ const MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); /** * Primitive schema definition for enum fields. */ const EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); /** * Union of all primitive schema definitions. */ const PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); /** * Parameters for an `elicitation/create` request for form-based elicitation. */ const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. * * Optional for backward compatibility. Clients MUST treat missing mode as "form". */ mode: literal('form').optional(), /** * The message to present to the user describing what information is being requested. */ message: schemas_string(), /** * A restricted subset of JSON Schema. * Only top-level properties are allowed, without nesting. */ requestedSchema: object({ type: literal('object'), properties: record(schemas_string(), PrimitiveSchemaDefinitionSchema), required: array(schemas_string()).optional() }) }); /** * Parameters for an `elicitation/create` request for URL-based elicitation. */ const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. */ mode: literal('url'), /** * The message to present to the user explaining why the interaction is needed. */ message: schemas_string(), /** * The ID of the elicitation, which must be unique within the context of the server. * The client MUST treat this ID as an opaque value. */ elicitationId: schemas_string(), /** * The URL that the user should navigate to. */ url: schemas_string().url() }); /** * The parameters for a request to elicit additional information from the user via the client. */ const ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); /** * A request from the server to elicit user input via the client. * The client should present the message and form fields to the user (form mode) * or navigate to a URL (URL mode). */ const ElicitRequestSchema = RequestSchema.extend({ method: literal('elicitation/create'), params: ElicitRequestParamsSchema }); /** * Parameters for a `notifications/elicitation/complete` notification. * * @category notifications/elicitation/complete */ const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the elicitation that completed. */ elicitationId: schemas_string() }); /** * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. * * @category notifications/elicitation/complete */ const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ method: literal('notifications/elicitation/complete'), params: ElicitationCompleteNotificationParamsSchema }); /** * The client's response to an elicitation/create request from the server. */ const ElicitResultSchema = ResultSchema.extend({ /** * The user action in response to the elicitation. * - "accept": User submitted the form/confirmed the action * - "decline": User explicitly decline the action * - "cancel": User dismissed without making an explicit choice */ action: schemas_enum(['accept', 'decline', 'cancel']), /** * The submitted form data, only present when action is "accept". * Contains values matching the requested schema. * Per MCP spec, content is "typically omitted" for decline/cancel actions. * We normalize null to undefined for leniency while maintaining type compatibility. */ content: preprocess(val => (val === null ? undefined : val), record(schemas_string(), union([schemas_string(), schemas_number(), schemas_boolean(), array(schemas_string())])).optional()) }); /* Autocomplete */ /** * A reference to a resource or resource template definition. */ const ResourceTemplateReferenceSchema = object({ type: literal('ref/resource'), /** * The URI or URI template of the resource. */ uri: schemas_string() }); /** * @deprecated Use ResourceTemplateReferenceSchema instead */ const ResourceReferenceSchema = (/* unused pure expression or super */ null && (ResourceTemplateReferenceSchema)); /** * Identifies a prompt. */ const PromptReferenceSchema = object({ type: literal('ref/prompt'), /** * The name of the prompt or prompt template */ name: schemas_string() }); /** * Parameters for a `completion/complete` request. */ const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), /** * The argument's information */ argument: object({ /** * The name of the argument */ name: schemas_string(), /** * The value of the argument to use for completion matching. */ value: schemas_string() }), context: object({ /** * Previously-resolved variables in a URI template or prompt. */ arguments: record(schemas_string(), schemas_string()).optional() }) .optional() }); /** * A request from the client to the server, to ask for completion options. */ const CompleteRequestSchema = RequestSchema.extend({ method: literal('completion/complete'), params: CompleteRequestParamsSchema }); function assertCompleteRequestPrompt(request) { if (request.params.ref.type !== 'ref/prompt') { throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); } void request; } function assertCompleteRequestResourceTemplate(request) { if (request.params.ref.type !== 'ref/resource') { throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); } void request; } /** * The server's response to a completion/complete request */ const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ /** * An array of completion values. Must not exceed 100 items. */ values: array(schemas_string()).max(100), /** * The total number of completion options available. This can exceed the number of values actually sent in the response. */ total: optional(schemas_number().int()), /** * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. */ hasMore: optional(schemas_boolean()) }) }); /* Roots */ /** * Represents a root directory or file that the server can operate on. */ const RootSchema = object({ /** * The URI identifying the root. This *must* start with file:// for now. */ uri: schemas_string().startsWith('file://'), /** * An optional name for the root. */ name: schemas_string().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(schemas_string(), unknown()).optional() }); /** * Sent from the server to request a list of root URIs from the client. */ const ListRootsRequestSchema = RequestSchema.extend({ method: literal('roots/list'), params: BaseRequestParamsSchema.optional() }); /** * The client's response to a roots/list request from the server. */ const ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); /** * A notification from the client to the server, informing it that the list of roots has changed. */ const RootsListChangedNotificationSchema = NotificationSchema.extend({ method: literal('notifications/roots/list_changed'), params: NotificationsParamsSchema.optional() }); /* Client messages */ const ClientRequestSchema = union([ PingRequestSchema, InitializeRequestSchema, CompleteRequestSchema, SetLevelRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, CallToolRequestSchema, ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); const ClientNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, InitializedNotificationSchema, RootsListChangedNotificationSchema, TaskStatusNotificationSchema ]); const ClientResultSchema = union([ EmptyResultSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, ListRootsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); /* Server messages */ const ServerRequestSchema = union([ PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); const ServerNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, LoggingMessageNotificationSchema, ResourceUpdatedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, TaskStatusNotificationSchema, ElicitationCompleteNotificationSchema ]); const ServerResultSchema = union([ EmptyResultSchema, InitializeResultSchema, CompleteResultSchema, GetPromptResultSchema, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, CallToolResultSchema, ListToolsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); class McpError extends Error { constructor(code, message, data) { super(`MCP error ${code}: ${message}`); this.code = code; this.data = data; this.name = 'McpError'; } /** * Factory method to create the appropriate error type based on the error code and data */ static fromError(code, message, data) { // Check for specific error types if (code === ErrorCode.UrlElicitationRequired && data) { const errorData = data; if (errorData.elicitations) { return new UrlElicitationRequiredError(errorData.elicitations, message); } } // Default to generic McpError return new McpError(code, message, data); } } /** * Specialized error type when a tool requires a URL mode elicitation. * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. */ class UrlElicitationRequiredError extends McpError { constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { super(ErrorCode.UrlElicitationRequired, message, { elicitations: elicitations }); } get elicitations() { return this.data?.elicitations ?? []; } } //# sourceMappingURL=types.js.map ;// ./node_modules/@elementor/angie-sdk/dist/index.js const t={none:0,error:1,warn:2,info:3,debug:4},i={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},n=(e,i)=>t[e]<=t[i],s=e=>"string"==typeof e?e:JSON.stringify(e),r=(e,t)=>`${s(e)} > ${s(t)}`,o=(e,t)=>{let i=`[${s(e)}]`;return typeof window<"u"?{text:`%c${i}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:i}},a=(e,t,s,r)=>(...a)=>{if(!n(i[e],r()))return;if(!t)return void console[e](...a);let{text:c,style:d}=o(t,s);d?console[e](c,d,...a):console[e](c,...a)},c=(e,t)=>{let i=t.logLevel??"debug",n=()=>i;return{log:a("log",e,t,n),info:a("info",e,t,n),warn:a("warn",e,t,n),error:a("error",e,t,n),debug:a("debug",e,t,n),setLogLevel:e=>{i=e},extend:n=>c(e?r(e,n):n,{...t,logLevel:i})}},d=(e,t)=>c(e,{color:"#00bcd4",logLevel:"debug",...t}),l=d("angie-sdk",{color:"#00BCD4",logLevel:"error"}),g=e=>l.extend(e);var u,h,p,_,w,m,f,y;!function(e){e.POST_MESSAGE="postMessage"}(u||(u={})),function(e){e.POST_MESSAGE="postMessage"}(h||(h={})),function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(p||(p={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(_||(_={})),function(e){e.AGENT="agent",e.PLAN="plan",e.ASK="ask",e.SUPER_ADMIN="super-admin"}(w||(w={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response",e.ANGIE_SET_INTERACTION_MODE="angie/set-interaction-mode"}(m||(m={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(f||(f={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(y||(y={}));const S=g("angie-detector");class b{isAngieReady=!1;readyPromise;readyResolve;getInstanceId;constructor(e){if(this.getInstanceId=e,this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let t=0;const i=()=>{if(this.isAngieReady||t>=500)return void(!this.isAngieReady&&t>=500&&this.handleDetectionTimeout());const e=new MessageChannel;e.port1.onmessage=t=>{this.handleAngieReady(t.data),e.port1.close(),e.port2.close()};const n={type:m.SDK_ANGIE_READY_PING,payload:{instanceId:this.getInstanceId?.()},timestamp:Date.now()};window.postMessage(n,window.location.origin,[e.port2]),t++,setTimeout(i,500)};i()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),S.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}async waitUntilReady(e){return this.isAngieReady?this.readyPromise:Promise.race([this.readyPromise,new Promise(t=>{setTimeout(()=>t({isReady:!1}),e)})])}}class v{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(t){if(!t)throw new Error("MessagePort is required");this._port=t,this._port.onmessage=t=>{try{const i=JSONRPCMessageSchema.parse(t.data);this.onmessage?.(i)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,i)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),i(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class I{async requestClientCreation(e){const{config:t}=e,i={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||h.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(i.remote={url:t.url}),new Promise((e,t)=>{const n=new MessageChannel,s=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);n.port1.onmessage=t=>{clearTimeout(s),e(t.data)};const r={type:m.SDK_REQUEST_CLIENT_CREATION,payload:i,timestamp:Date.now()};window.postMessage(r,window.location.origin,[n.port2])})}}const E="angie-sidebar-container",k="angie-iframe",T=()=>({open:!1,iframe:null,iframeUrlObject:null,containerId:E,instanceId:"",appId:void 0,layout:"",iframeElementId:k}),R=T();class A extends Error{}A.prototype.name="InvalidTokenError";var C,x,P,O={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},U=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(U||{});(P=U||(U={})).reset=function(){C=3,x=O},P.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");C=e},P.setLogger=function(e){x=e};var L=class e{constructor(e){this._name=e}debug(...t){C>=4&&x.debug(e._format(this._name,this._method),...t)}info(...t){C>=3&&x.info(e._format(this._name,this._method),...t)}warn(...t){C>=2&&x.warn(e._format(this._name,this._method),...t)}error(...t){C>=1&&x.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,i){const n=new e(`${t}.${i}`);return n.debug("begin"),n}static _format(e,t){const i=`[${e}]`;return t?`${i} ${t}:`:i}static debug(t,...i){C>=4&&x.debug(e._format(t),...i)}static info(t,...i){C>=3&&x.info(e._format(t),...i)}static warn(t,...i){C>=2&&x.warn(e._format(t),...i)}static error(t,...i){C>=1&&x.error(e._format(t),...i)}};U.reset();var D=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new A("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,n=e.split(".")[i];if("string"!=typeof n)throw new A(`Invalid token specified: missing part #${i+1}`);let s;try{s=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i}))}(t)}catch(e){return atob(t)}}(n)}catch(e){throw new A(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new A(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e)}catch(e){throw L.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,i){const n=`${$.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${$.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},i,(new TextEncoder).encode(n));return`${n}.${$.encodeBase64Url(new Uint8Array(s))}`}static async generateSignedJwtWithHmac(e,t,i){const n=`${$.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${$.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign("HMAC",i,(new TextEncoder).encode(n));return`${n}.${$.encodeBase64Url(new Uint8Array(s))}`}},N=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),q=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){const t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16));return t.replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),i=await crypto.subtle.digest("SHA-256",t);return N(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw L.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const i=(new TextEncoder).encode([e,t].join(":"));return N(i)}static async hash(e,t){const i=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,i);return new Uint8Array(n)}static async customCalculateJwkThumbprint(t){let i;switch(t.kty){case"RSA":i={e:t.e,kty:t.kty,n:t.n};break;case"EC":i={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":i={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":i={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const n=await e.hash("SHA-256",JSON.stringify(i));return e.encodeBase64Url(n)}static async generateDPoPProof({url:t,accessToken:i,httpMethod:n,keyPair:s,nonce:r}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=n?n:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};i&&(o=await e.hash("SHA-256",i),a=e.encodeBase64Url(o),c.ath=a),r&&(c.nonce=r);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await D.generateSignedJwt(t,c,s.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const i=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(i)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,i,n,s="HS256"){const r=Math.floor(Date.now()/1e3),o={alg:s,typ:"JWT"},a={iss:t,sub:t,aud:n,jti:e.generateUUIDv4(),exp:r+300,iat:r},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[s];if(!c)throw new Error(`Unsupported algorithm: ${s}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,l=await crypto.subtle.importKey("raw",d.encode(i),{name:"HMAC",hash:c},!1,["sign"]);return await D.generateSignedJwtWithHmac(o,a,l)}};q.encodeBase64Url=e=>N(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var $=q,M=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new L(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},H=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},j=class e extends M{constructor(){super(...arguments),this._logger=new L(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const i=this._logger.create("init");t=Math.max(Math.floor(t),1);const n=e.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void i.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),i.debug("using duration",t),this._expiration=n;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},G=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(i.slice(1))}},z=";",W=class extends Error{constructor(e,t){var i,n,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw L.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(i=e.error_description)?i:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},B=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},F=class{constructor(e){this._logger=new L("AccessTokenEvents"),this._expiringTimer=new j("Access token expiring"),this._expiredTimer=new j("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const i=e.expires_in;if(t.debug("access token present, remaining duration:",i),i>0){let e=i-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const n=i+1;t.debug("registering expired timer, raising in",n,"seconds"),this._expiredTimer.init(n)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},K=class{constructor(e,t,i,n,s){this._callback=e,this._client_id=t,this._intervalInSeconds=n,this._stopOnError=s,this._logger=new L("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const r=new URL(i);this._frame_origin=r.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=r.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},J=class{constructor(){this._logger=new L("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},V=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},Q=class{constructor(e=[],t=null,i={}){this._jwtHandler=t,this._extraHeaders=i,this._logger=new L("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:i,...n}=t;if(!i)return await fetch(e,n);const s=new AbortController,r=setTimeout(()=>s.abort(),1e3*i);try{return await fetch(e,{...t,signal:s.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new B("Network timed out");throw e}finally{clearTimeout(r)}}async getJson(e,{token:t,credentials:i,timeoutInSeconds:n}={}){const s=this._logger.create("getJson"),r={Accept:this._contentTypes.join(", ")};let o;t&&(s.debug("token passed, setting Authorization header"),r.Authorization="Bearer "+t),this._appendExtraHeaders(r);try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:r,timeoutInSeconds:n,credentials:i})}catch(e){throw s.error("Network Error"),e}s.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(e=>a.startsWith(e))&&s.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(s.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(s.error("Error from server:",c),c.error)throw new W(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:i,timeoutInSeconds:n,initCredentials:s,extraHeaders:r}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...r};let c;void 0!==i&&(a.Authorization="Basic "+i),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:n,credentials:s})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let g={};if(l)try{g=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",g),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new V(e,`${JSON.stringify(g)}`)}if(g.error)throw new W(g,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(g)}`)}return g}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),i=Object.keys(this._extraHeaders),n=["accept","content-type"],s=["authorization"];0!==i.length&&i.forEach(i=>{if(n.includes(i.toLocaleLowerCase()))return void t.warn("Protected header could not be set",i,n);if(s.includes(i.toLocaleLowerCase())&&Object.keys(e).includes(i))return void t.warn("Header could not be overridden",i,s);const r="function"==typeof this._extraHeaders[i]?this._extraHeaders[i]():this._extraHeaders[i];r&&""!==r&&(e[i]=r)})}},X=class{constructor(e){this._settings=e,this._logger=new L("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Q(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const i=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(i.debug("resolved"),void 0===n[e]){if(!0===t)return void i.warn("Metadata does not contain optional property");i.throw(new Error("Metadata does not contain property "+e))}return n[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const i=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",i),!Array.isArray(i.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=i.keys,this._signingKeys}},Y=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new L("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let i=0;i<e;i++){const e=await this._store.key(i);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Z=class{constructor({authority:e,metadataUrl:t,metadata:i,signingKeys:n,metadataSeed:s,client_id:r,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:g="client_secret_post",token_endpoint_auth_signing_alg:u="HS256",prompt:h,display:p,max_age:_,ui_locales:w,acr_values:m,resource:f,response_mode:y,filterProtocolClaims:S=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:v,staleStateAgeInSeconds:I=900,mergeClaimsStrategy:E={array:"replace"},disablePKCE:k=!1,stateStore:T,revokeTokenAdditionalContentTypes:R,fetchRequestCredentials:A,refreshTokenAllowedScope:C,extraQueryParams:x={},extraTokenParams:P={},extraHeaders:O={},dpop:U,omitScopeWhenRequesting:L=!1}){var D;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=i,this.metadataSeed=s,this.signingKeys=n,this.client_id=r,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=g,this.token_endpoint_auth_signing_alg=u,this.prompt=h,this.display=p,this.max_age=_,this.ui_locales=w,this.acr_values=m,this.resource=f,this.response_mode=y,this.filterProtocolClaims=null==S||S,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=I,this.mergeClaimsStrategy=E,this.omitScopeWhenRequesting=L,this.disablePKCE=!!k,this.revokeTokenAdditionalContentTypes=R,this.fetchRequestCredentials=A||"same-origin",this.requestTimeoutInSeconds=v,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new J;this.stateStore=new Y({store:e})}if(this.refreshTokenAllowedScope=C,this.extraQueryParams=x,this.extraTokenParams=P,this.extraHeaders=O,this.dpop=U,this.dpop&&!(null==(D=this.dpop)?void 0:D.store))throw new Error("A DPoPStore is required when dpop is enabled")}},ee=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new L("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const i=D.decode(e);return t.debug("JWT decoding successful"),i}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new Q(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const i=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",i);const n=await this._jsonService.getJson(i,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},te=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new L("TokenClient"),this._jsonService=new Q(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:i=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:s,...r}){const o=this._logger.create("exchangeCode");i||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),r.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(r))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==n)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=$.generateBasicAuth(i,n);break;case"client_secret_post":a.append("client_id",i),n&&a.append("client_secret",n);break;case"client_secret_jwt":{const e=await $.generateClientAssertionJwt(i,n,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",i),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,scope:n=this._settings.scope,...s}){const r=this._logger.create("exchangeCredentials");t||r.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",n);for(const[e,t]of Object.entries(s))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw r.throw(new Error("A client_secret is required")),null;let a;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=$.generateBasicAuth(t,i);break;case"client_secret_post":o.append("client_id",t),i&&o.append("client_secret",i);break;case"client_secret_jwt":{const e=await $.generateClientAssertionJwt(t,i,c,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}r.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:i=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:s,...r}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),r.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(r))Array.isArray(t)?t.forEach(t=>a.append(e,t)):null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==i)throw o.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=$.generateBasicAuth(t,i);break;case"client_secret_post":a.append("client_id",t),i&&a.append("client_secret",i);break;case"client_secret_jwt":{const e=await $.generateClientAssertionJwt(t,i,d,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),l}async revoke(e){var t;const i=this._logger.create("revoke");e.token||i.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);i.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[t,i]of Object.entries(e))null!=i&&s.set(t,i);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),i.debug("got response")}},ie=class{constructor(e,t,i){this._settings=e,this._metadataService=t,this._claimsService=i,this._logger=new L("ResponseValidator"),this._userInfoService=new ee(this._settings,this._metadataService),this._tokenClient=new te(this._settings,this._metadataService)}async validateSigninResponse(e,t,i){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,i),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const i=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,t,n),i.debug("claims processed")}async validateRefreshResponse(e,t){const i=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),i.debug("claims processed")}validateSignoutResponse(e,t){const i=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&i.throw(new Error("State does not match")),i.debug("state validated"),e.userState=t.data,e.error)throw i.warn("Response was error",e.error),new W(e)}_processSigninState(e,t){const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new W(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,i=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),i&&s.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,i){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const s=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:i,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var i;const n=this._logger.create("_validateIdTokenAttributes");n.debug("decoding ID Token JWT");const s=D.decode(null!=(i=e.id_token)?i:"");if(s.sub||n.throw(new Error("ID Token is missing a subject claim")),t){const e=D.decode(t);s.sub!==e.sub&&n.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&n.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&n.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&n.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},ne=class e{constructor(e){this.id=e.id||$.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=j.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new L("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return L.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,i){const n=L.createStatic("State","clearStaleState"),s=j.getEpochTime()-i,r=await t.getAllKeys();n.debug("got keys",r);for(let i=0;i<r.length;i++){const o=r[i],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);n.debug("got item from key:",o,t.created),t.created<=s&&(c=!0)}catch(e){n.error("Error parsing state for key:",o,e),c=!0}else n.debug("no item in storage for key:",o),c=!0;c&&(n.debug("removed item for key:",o),t.remove(o))}}},se=class e extends ne{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const i=!0===t.code_verifier?$.generateCodeVerifier():t.code_verifier||void 0,n=i?await $.generateCodeChallenge(i):void 0;return new e({...t,code_verifier:i,code_challenge:n})}toStorageString(){return new L("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){L.createStatic("SigninState","fromStorageString");const i=JSON.parse(t);return e.create(i)}},re=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:i,client_id:n,redirect_uri:s,response_type:r,scope:o,state_data:a,response_mode:c,request_type:d,client_secret:l,nonce:g,url_state:u,resource:h,skipUserInfo:p,extraQueryParams:_,extraTokenParams:w,disablePKCE:m,dpopJkt:f,omitScopeWhenRequesting:y,...S}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!r)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!i)throw this._logger.error("create: No authority passed"),new Error("authority");const b=await se.create({data:a,request_type:d,url_state:u,code_verifier:!m,client_id:n,authority:i,redirect_uri:s,response_mode:c,client_secret:l,scope:o,extraTokenParams:w,skipUserInfo:p}),v=new URL(t);v.searchParams.append("client_id",n),v.searchParams.append("redirect_uri",s),v.searchParams.append("response_type",r),y||v.searchParams.append("scope",o),g&&v.searchParams.append("nonce",g),f&&v.searchParams.append("dpop_jkt",f);let I=b.id;u&&(I=`${I}${z}${u}`),v.searchParams.append("state",I),b.code_challenge&&(v.searchParams.append("code_challenge",b.code_challenge),v.searchParams.append("code_challenge_method","S256")),h&&(Array.isArray(h)?h:[h]).forEach(e=>v.searchParams.append("resource",e));for(const[e,t]of Object.entries({response_mode:c,...S,..._}))null!=t&&v.searchParams.append(e,t.toString());return new e({url:v.href,state:b})}};re._logger=new L("SigninRequest");var oe=re,ae=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(z);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(z))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-j.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+j.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},ce=class{constructor({url:e,state_data:t,id_token_hint:i,post_logout_redirect_uri:n,extraQueryParams:s,request_type:r,client_id:o,url_state:a}){if(this._logger=new L("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(i&&c.searchParams.append("id_token_hint",i),o&&c.searchParams.append("client_id",o),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||a)){this.state=new ne({data:t,request_type:r,url_state:a});let e=this.state.id;a&&(e=`${e}${z}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...s}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},de=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(z);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(z))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},le=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],ge=["sub","iss","aud","exp","iat"],ue=class{constructor(e){this._settings=e,this._logger=new L("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:le;for(const i of e)ge.includes(i)||delete t[i]}return t}mergeClaims(e,t){const i={...e};for(const[e,n]of Object.entries(t))if(i[e]!==n)if(Array.isArray(i[e])||Array.isArray(n))if("replace"==this._settings.mergeClaimsStrategy.array)i[e]=n;else{const t=Array.isArray(i[e])?i[e]:[i[e]];for(const e of Array.isArray(n)?n:[n])t.includes(e)||t.push(e);i[e]=t}else"object"==typeof i[e]&&"object"==typeof n?i[e]=this.mergeClaims(i[e],n):i[e]=n;return i}},he=class{constructor(e,t){this.keys=e,this.nonce=t}},pe=class{constructor(e,t){this._logger=new L("OidcClient"),this.settings=e instanceof Z?e:new Z(e),this.metadataService=null!=t?t:new X(this.settings),this._claimsService=new ue(this.settings),this._validator=new ie(this.settings,this.metadataService,this._claimsService),this._tokenClient=new te(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:i,request_type:n,id_token_hint:s,login_hint:r,skipUserInfo:o,nonce:a,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:g=this.settings.redirect_uri,prompt:u=this.settings.prompt,display:h=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:m=this.settings.resource,response_mode:f=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams,dpopJkt:b,omitScopeWhenRequesting:v=this.settings.omitScopeWhenRequesting}){const I=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const E=await this.metadataService.getAuthorizationEndpoint();I.debug("Received authorization endpoint",E);const k=await oe.create({url:E,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:g,response_type:d,scope:l,state_data:e,url_state:c,prompt:u,display:h,max_age:p,ui_locales:_,id_token_hint:s,login_hint:r,acr_values:w,dpopJkt:b,resource:m,request:t,request_uri:i,extraQueryParams:y,extraTokenParams:S,request_type:n,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:v});await this.clearStaleState();const T=k.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),k}async readSigninResponseState(e,t=!1){const i=this._logger.create("readSigninResponseState"),n=new ae(G.readParams(e,this.settings.response_mode));if(!n.state)throw i.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw i.throw(new Error("No matching state found in storage")),null;return{state:await se.fromStorageString(s),response:n}}async processSigninResponse(e,t,i=!0){const n=this._logger.create("processSigninResponse"),{state:s,response:r}=await this.readSigninResponseState(e,i);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(r,s,t)}catch(e){if(!(e instanceof V&&this.settings.dpop))throw e;{const i=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=i,await this._validator.validateSigninResponse(r,s,t)}}return r}async getDpopProof(e,t){let i,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(i=await $.generateDPoPKeys(),n=new he(i,t),await e.set(this.settings.client_id,n)),await $.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i=!1,extraTokenParams:n={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),r=new ae(new URLSearchParams);return Object.assign(r,s),await this._validator.validateCredentialsResponse(r,i),r}async useRefreshToken({state:e,redirect_uri:t,resource:i,timeoutInSeconds:n,extraHeaders:s,extraTokenParams:r}){var o;const a=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);s={...s,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:n,extraHeaders:s,...r})}catch(o){if(!(o instanceof V&&this.settings.dpop))throw o;s.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:i,timeoutInSeconds:n,extraHeaders:s,...r})}const l=new ae(new URLSearchParams);return Object.assign(l,d),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:i,request_type:n,url_state:s,post_logout_redirect_uri:r=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),i||!r||t||(i=this.settings.client_id);const d=new ce({url:c,id_token_hint:t,client_id:i,post_logout_redirect_uri:r,state_data:e,extraQueryParams:o,request_type:n,url_state:s});await this.clearStaleState();const l=d.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const i=this._logger.create("readSignoutResponseState"),n=new de(G.readParams(e,this.settings.response_mode));if(!n.state){if(i.debug("No state in response"),n.error)throw i.warn("Response was error:",n.error),new W(n);return{state:void 0,response:n}}const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw i.throw(new Error("No matching state found in storage")),null;return{state:await ne.fromStorageString(s),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:i,response:n}=await this.readSignoutResponseState(e,!0);return i?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,i)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),ne.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},_e=class{constructor(e){this._userManager=e,this._logger=new L("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const i=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,i.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,i.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){i.debug("initializing check session iframe");const n=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,r=this._userManager.settings.stopCheckSessionOnError,o=new K(this._callback,n,e,s,r);await o.load(),this._checkSessionIFrame=o,o.start(t)}else i.warn("no check session iframe found in the metadata")}catch(e){i.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let i=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(i=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),i?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},we=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-j.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+j.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new L("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return L.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},me="oidc-client",fe=class{constructor(){this._abort=new M("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:i,keepOpen:n}=await new Promise((i,n)=>{const s=s=>{var r;const o=s.data,a=null!=(r=e.scriptOrigin)?r:window.location.origin;if(s.origin===a&&(null==o?void 0:o.source)===me){try{const i=G.readParams(o.url,e.response_mode).get("state");if(i||t.warn("no state found in response url"),s.source!==this._window&&i!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}i(o)}};window.addEventListener("message",s,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",s,!1));const r=new BroadcastChannel(`oidc-client-popup-${e.state}`);r.addEventListener("message",s,!1),this._disposeHandlers.add(()=>r.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),n(e)}))});return t.debug("got response from window"),this._dispose(),n||this.close(),{url:i}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,i=!1,n=window.location.origin){const s={source:me,url:t,keepOpen:i},r=new L("_notifyParent");if(e)r.debug("With parent. Using parent.postMessage."),e.postMessage(s,n);else{r.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const i=new BroadcastChannel(`oidc-client-popup-${e}`);i.postMessage(s),i.close()}}},ye={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Se="_blank",be=60,ve=2,Ie=class extends Z{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:i=e.post_logout_redirect_uri,popupWindowFeatures:n=ye,popupWindowTarget:s=Se,redirectMethod:r="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:g,automaticSilentRenew:u=!0,validateSubOnSilentRenew:h=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:_=!1,monitorAnonymousSession:w=!1,checkSessionIntervalInSeconds:m=ve,query_status_response_type:f="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:S=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:v=!1,accessTokenExpiringNotificationTimeInSeconds:I=be,userStore:E}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=n,this.popupWindowTarget=s,this.redirectMethod=r,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=g||d||10,this.automaticSilentRenew=u,this.validateSubOnSilentRenew=h,this.includeIdTokenInSilentRenew=p,this.monitorSession=_,this.monitorAnonymousSession=w,this.checkSessionIntervalInSeconds=m,this.stopCheckSessionOnError=y,this.query_status_response_type=f,this.revokeTokenTypes=S,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=v,this.accessTokenExpiringNotificationTimeInSeconds=I,E)this.userStore=E;else{const e="undefined"!=typeof window?window.sessionStorage:new J;this.userStore=new Y({store:e})}}},Ee=class e extends fe{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new L("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new B("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const i=e.target;null==(t=i.parentNode)||t.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},ke=class{constructor(e){this._settings=e,this._logger=new L("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Ee({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Ee.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Te=class extends fe{constructor({popupWindowTarget:e=Se,popupWindowFeatures:t={},popupSignal:i,popupAbortOnClose:n}){super(),this._logger=new L("PopupWindow");const s=H.center({...ye,...t});this._window=window.open(void 0,e,H.serialize(s)),this.abortOnClose=Boolean(n),i&&i.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=i.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const i=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),n(),this._disposeHandlers.delete(n),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),n=()=>clearInterval(i);return this._disposeHandlers.add(n),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Re=class{constructor(e){this._settings=e,this._logger=new L("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:i,popupAbortOnClose:n}){return new Te({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:i,popupAbortOnClose:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Te.notifyOpener(e,t)}},Ae=class{constructor(e){this._settings=e,this._logger=new L("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var i;this._logger.create("prepare");let n=window.self;"top"===t&&(n=null!=(i=window.top)?i:window.self);const s=n.location[e].bind(n.location);let r;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,i)=>{r=i,window.addEventListener("pageshow",()=>t(window.location.href)),s(e.url)});return await t},close:()=>{this._logger.create("close"),null==r||r(new Error("Redirect aborted")),n.stop()}}}async callback(){}},Ce=class extends F{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new L("UserManagerEvents"),this._userLoaded=new M("User loaded"),this._userUnloaded=new M("User unloaded"),this._silentRenewError=new M("Silent renew error"),this._userSignedIn=new M("User signed in"),this._userSignedOut=new M("User signed out"),this._userSessionChanged=new M("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},xe=class{constructor(e){this._userManager=e,this._logger=new L("SilentRenewService"),this._isStarted=!1,this._retryTimer=new j("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof B)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Pe=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Oe=class{constructor(e,t,i,n){this._logger=new L("UserManager"),this.settings=new Ie(e),this._client=new pe(e),this._redirectNavigator=null!=t?t:new Ae(this.settings),this._popupNavigator=null!=i?i:new Re(this.settings),this._iframeNavigator=null!=n?n:new ke(this.settings),this._events=new Ce(this.settings),this._silentRenewService=new xe(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new _e(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),i=await this._loadUser();return i?(t.info("user loaded"),await this._events.load(i,e),i):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:i,...n}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const r=await this._redirectNavigator.prepare({redirectMethod:i});await this._signinStart({request_type:"si:r",dpopJkt:s,...n},r)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),i=await this._signinEnd(e);return i.profile&&i.profile.sub?t.info("success, signed in subject",i.profile.sub):t.info("no subject"),i}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:i=!1}){const n=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:i,extraTokenParams:this.settings.extraTokenParams});n.debug("got signin response");const r=await this._buildUser(s);return r.profile&&r.profile.sub?n.info("success, signed in subject",r.profile.sub):n.info("no subject"),r}async signinPopup(e={}){var t;const i=this._logger.create("signinPopup");let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:r,popupSignal:o,popupAbortOnClose:a,...c}=e,d=this.settings.popup_redirect_uri;d||i.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:r,popupSignal:o,popupAbortOnClose:a}),g=await this._signin({request_type:"si:p",redirect_uri:d,display:"popup",dpopJkt:n,...c},l);return g&&(g.profile&&g.profile.sub?i.info("success, signed in subject",g.profile.sub):i.info("no subject")),g}async signinPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async signinSilent(e={}){var t,i;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...r}=e;let o,a=await this._loadUser();if(!e.forceIframeAuth&&(null==a?void 0:a.refresh_token)){n.debug("using refresh token");const e=new Pe(a);return await this._useRefreshToken({state:e,redirect_uri:r.redirect_uri,resource:r.resource,extraTokenParams:r.extraTokenParams,timeoutInSeconds:s})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||n.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",a.profile.sub),d=a.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...r},l,d),a&&((null==(i=a.profile)?void 0:i.sub)?n.info("success, signed in subject",a.profile.sub):n.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),i=new we({...e.state,...t});return await this.storeUser(i),await this._events.load(i),i}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:i}=await this._client.readSignoutResponseState(e);if(i)switch(i.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:i,...n}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const r=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i}),a=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==r?void 0:r.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...n},o);try{const e={},i=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),i.session_state&&i.profile.sub?(t.info("success for subject",i.profile.sub),{session_state:i.session_state,sub:i.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof W)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,i){const n=await this._signinStart(e,t);return await this._signinEnd(n.url,i)}async _signinStart(e,t){const i=this._logger.create("_signinStart");try{const n=await this._client.createSigninRequest(e);return i.debug("got signin request"),await t.navigate({url:n.url,state:n.state.id,response_mode:n.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const i=this._logger.create("_signinEnd"),n=await this._client.processSigninResponse(e,{});return i.debug("got signin response"),await this._buildUser(n,t)}async _buildUser(e,t){const i=this._logger.create("_buildUser"),n=new we(e);if(t){if(t!==n.profile.sub)throw i.debug("current user does not match user returned from signin. sub from signin:",n.profile.sub),new W({...e,error:"login_required"});i.debug("current user matches user returned from signin")}return await this.storeUser(n),i.debug("user stored"),await this._events.load(n),n}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:i,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:i});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...n},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),i=await this._signoutEnd(e);return t.info("success"),i}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:i,popupWindowTarget:n,popupSignal:s,...r}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:i,popupWindowTarget:n,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...r},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const i=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),i.info("success")}async _signout(e,t){const i=await this._signoutStart(e,t);return await this._signoutEnd(i.url)}async _signoutStart(e={},t){var i;const n=this._logger.create("_signoutStart");try{const s=await this._loadUser();n.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const r=e.id_token_hint||s&&s.id_token;r&&(n.debug("setting id_token_hint in signout request"),e.id_token_hint=r),await this.removeUser(),n.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return n.debug("got signout request"),await t.navigate({url:o.url,state:null==(i=o.state)?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),i=await this._client.processSignoutResponse(e);return t.debug("got signout response"),i}async signoutSilent(e={}){var t;const i=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:n,...s}=e,r=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:r,...s},a),i.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const i=this._logger.create("_revokeInternal");if(!e)return;const n=t.filter(t=>"string"==typeof e[t]);if(n.length){for(const t of n)await this._client.revokeToken(e[t],t),i.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),i.debug("user stored"),await this._events.load(e)}else i.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),we.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const i=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,i)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,i,n){var s,r;const o=await(null==(r=null==(s=this.settings.dpop)?void 0:s.store)?void 0:r.get(this.settings.client_id));if(o)return await $.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:i,keyPair:o.keys,nonce:n})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const i=await $.generateDPoPKeys();t=new he(i),await e.store.set(this.settings.client_id,t)}return await $.generateDPoPJkt(t.keys)}};const Ue="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",Le="OAUTH_GET_TOP_URL",De="OAUTH_REDIRECT_TOP_WINDOW",Ne="OAUTH_UPDATE_URL",qe="OAUTH2_CHECK_PENDING",dist_$e="oauth2_top_origin",Me="oauth2_login_success",He="oauth2_state",je=60,Ge=Math.max(je-15,20),ze=d("oidc-auth",{color:"green"}),We=e=>ze.extend(e);d("oidc-auth-utils");const Be=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class Fe{static instance=null;settings=null;constructor(){}static getInstance(){return Fe.instance||(Fe.instance=new Fe),Fe.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:i}=this.getSettings(),n=this.getAuthOrigin(),s="undefined"!=typeof window?new Y({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:r=je}=this.getSettings();return{client_id:t,authority:n,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:r,stateStore:s,userStore:s,metadata:{issuer:n,authorization_endpoint:i,token_endpoint:`${n}/connect/api/v1/oauth2/token`,end_session_endpoint:`${n}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??je}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??Ge}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const Ke=Fe.getInstance(),Je=We("oidc-auth:host-api"),Ve=async e=>new Promise((t,i)=>{const n=new MessageChannel;let s=!1;const r=()=>{s=!0,n.port1.close()},o=setTimeout(()=>{s||(r(),i(new Error(`Host message timeout: ${e.type}`)))},1e4);n.port1.onmessage=e=>{clearTimeout(o),r(),"success"!==e.data.status?i(e.data.payload):t(e.data.payload)};const a=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=Ke.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(a))return clearTimeout(o),r(),void i(new Error("Origin not allowed"));Je.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},a,[n.port2])}),Qe=We("oidc-auth:OidcAuthTimer");class Xe{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,i){const n=e-this.getEpochTime(),s=Math.max(n-t,10);this.cancel(),this.expiration=s,this.callback=i,Qe.debug("OIDC: timer - using expiration",s,n,t,e,n-t),this.timerHandle=setTimeout(this.callback,1e3*s),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const Ye=We("oidc-auth:OidcAuthClient");class Ze{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return Ze.instance||(Ze.instance=new Ze),Ze.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,Ke.configure(e)),this.initialized)Ye.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(Ke.isConfigured())try{Ye.info("OIDC: initialize() - starting initialization");const e=Ke.getOidcSettings();this.userManager=new Oe(e),U.setLogger(Ye),U.setLevel(U.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw Ye.error("OIDC: initialize() - FAILED:",e),e}else Ye.warn("OIDC: initialize() - skipped, config not set");else Ye.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){Ke.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new Xe),this.accessTokenExpiringTimer.init(t,Ke.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{Ye.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{Ye.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):Ye.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(e){return Ye.error("OIDC: getUser - FAILED:",e),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return Ye.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return Ye.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{Ye.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=Ke.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,i=localStorage.getItem(t);if(!i)return null;const n=JSON.parse(i),s=n?.profile;return s?.sub?(Ye.info("OIDC: USER:",{profile:s}),{id:s.sub,email:s.email||"",first_name:s.given_name,last_name:s.family_name}):null}catch(e){return Ye.error("OIDC: getUserData - FAILED:",e),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw Ye.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(Ye.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const i=t??Ke.getAccessTokenFreshnessThresholdInSeconds(),n=Math.floor(Date.now()/1e3);return e.expires_at-n>i}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw Ye.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){Ye.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(Ke.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(Ye.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else Ye.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const i=new URL(function(e){return`${Ke.getAuthOrigin()}${e.logoutPath}`}(e));return t&&i.searchParams.set("redirect_to",t),i.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get("origin");if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await Ve({type:Le})).topUrl}async isOAuthFlowPending(){try{return(await Ve({type:qe})).isPending}catch(e){return Ye.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",e),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){Ye.info("OIDC: triggerLoginFlowViaParent() - starting");const i=await this.getTopUrl(),n=new URL(i).origin,s=`${n}${t}`,r=new URL(`${window.location.origin}${e}`);r.searchParams.set(dist_$e,n),r.searchParams.set("oauth2_top_wp_url",s),Ye.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",r.toString()),await Ve({type:De,payload:{url:r.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const i=this.getWindowOriginParam(),n=t.state,s=n?.data?.[dist_$e];if(i!==s)throw Ye.error("OIDC: handleLoginFlowComplete - origin mismatch:",i,"!==",s),new Error("Invalid origin in OAuth state");try{const e=new we(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){Ye.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const i=await this.getTopUrl(),n=new URL(i).origin,s=t?`${n}${e.windowPath}`:n;await this.removeUser();const r=this.getLogoutUrl(e,s);await Ve({type:De,payload:{url:r}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(Me),t.searchParams.delete(He),await Ve({type:Ne,payload:{url:t.toString()}})}catch(e){Ye.warn("Failed to clean OAuth params from URL:",e)}}setupLoginFlowMessageListener(e){let t=!1;const i=i=>{if(i.data?.type!==Ue)return;if(i.origin!==Be())return void Ye.error("OIDC: origin mismatch - expected:",Be(),"received:",i.origin);if(t)return void Ye.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const n=i.data.payload;n?.oauthState?(t=!0,this.handleLoginFlowComplete(e,n.oauthState).catch(e=>{Ye.error("OIDC: Failed to handle login flow complete:",e),t=!1})):Ye.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",i),()=>{window.removeEventListener("message",i)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),i=Date.now(),n=Math.floor((1e3*e.expires_at-i)/1e3);return{expiresAt:t,expiresInSeconds:n,isExpired:n<=0}}async forceTokenRefresh(){return Ye.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const et=Ze.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=et);const tt=We("oidc-auth:oidc-auth-redirect");function it(e,t){e.postMessage({status:"success",payload:t})}function nt(e,t){e.postMessage({status:"error",payload:t})}function st({targets:e,onSuccess:t,attempt:i=1}){const n=new URLSearchParams(window.location.search);if(!n.get(Me))return void tt.warn("OIDC: No login_success param found, skipping");const s=n.get(He);if(s){if(!e.window?.contentWindow||!e.windowURL)return tt.warn("Cannot forward OIDC state: iframe not available"),void(i<5?setTimeout(()=>{st({targets:e,onSuccess:t,attempt:i+1})},500):tt.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const i=JSON.parse(s),n=i.state?.data?.[dist_$e];if(n&&n!==window.location.origin)return void tt.error("Origin mismatch in OIDC state:",n,"vs",window.location.origin);!function(e,t){const i=t.window?.contentWindow,n=t.windowURL?.origin;i&&n?i.postMessage({type:Ue,payload:e},n):tt.warn("Cannot send OIDC state: window or origin not available")}({oauthState:i},e);const r=new URL(window.location.href);r.searchParams.delete(Me),r.searchParams.delete(He),history.replaceState({},"",r.toString()),t?.()}catch(e){tt.error("Failed to parse or forward OIDC state:",e)}}else tt.warn("OIDC login complete but no state found in URL")}const rt=g("iframe-utils");let ot=null;const at=e=>!!e&&document.contains(e),ct=e=>{try{return new URL(e.src).origin}catch(e){return rt.error("Error parsing iframe URL:",e),null}},dt=(e,t,i)=>!!e?.contentWindow&&(t?(e.contentWindow.postMessage(i,t),!0):(rt.error("Could not determine target origin for Angie iframe"),!1)),lt=e=>at(e.iframe)?e.iframe:null,gt=(e,t)=>dt(lt(e),(e=>{if(e.iframeUrlObject)return e.iframeUrlObject.origin;const t=lt(e);return t?ct(t):null})(e),t),ut=()=>lt(R)||(at(ot)||(ot=document.querySelector('iframe[src*="angie/"]')),ot),ht=(e,t)=>(rt.log("postMessageToAngieIframe",e,t),dt(ut(),t||(()=>{const e=ut();return e?ct(e):null})(),e)),pt=(e,t,i)=>{const n=document.getElementById(i??R.containerId);n&&n.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},_t=(e,t)=>{const i=t?.contentWindow;return!i||!e.source||e.source===i},wt=(e,t,i)=>e.origin===t&&_t(e,i),mt=()=>Math.random().toString(36).substring(2,8),ft=(e,t)=>{e.postMessage({status:"success",payload:t})},yt=(e,t)=>{e.postMessage({status:"error",payload:t})},St=()=>new Promise(e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e(null)}),bt=g("sidebar");let vt=!1;const It="open",Et="closed",kt="angie_sidebar_state",Tt="angie_sidebar_width";function Rt(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem(Tt);if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){bt.warn("localStorage not available")}return 370}function At(){return"undefined"==typeof window?null:localStorage.getItem(kt)}function Ct(e){try{localStorage.setItem(kt,e)}catch(e){bt.warn("localStorage not available")}}function xt(e){try{localStorage.setItem(Tt,e.toString())}catch(e){bt.warn("localStorage not available")}}function Pt(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function Ot(e=It){!function(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search);return e.has(Me)||e.has(He)||e.has(dist_$e)}()?Ut(At()||e):function(){Ut(Et);try{localStorage.setItem(kt,Et)}catch(e){bt.warn("localStorage not available")}}()}function Ut(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===It,!0)}function Lt(e=R){const t=document.getElementById(e.containerId);if(!t)return;let i=!1,n=0,s=0;t.addEventListener("mousedown",e=>{const r=t.getBoundingClientRect();("rtl"===document.documentElement.dir?e.clientX<=r.left+4:e.clientX>=r.right-4)&&(i=!0,n=e.clientX,s=r.width,t.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",e.preventDefault(),e.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!i)return;let t;t="rtl"===document.documentElement.dir?n-e.clientX:e.clientX-n,Pt(Math.max(350,Math.min(590,s+t))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",n=>{if(i){i=!1,t.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const r=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);xt(r),gt(e,{type:m.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:s,width:r}}),n.preventDefault(),n.stopPropagation()}}),Pt(Rt())}let Dt=!1;function Nt(e){e?.skipDefaultCss||function(){if("undefined"==typeof document||vt)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(vt=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const i=document.head||document.getElementsByTagName("head")[0];i.insertBefore(t,i.firstChild),vt=!0}();const t=e?.instance??R;"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e,t=R){return function(i,n){const s=document.body,r=document.getElementById(t.containerId);if(!r)return void bt.warn("Required elements not found!");const o=s.classList.contains("angie-sidebar-active"),a=void 0!==i?i:!o;n||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),a?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),t.iframe&&pt(t.iframe,a,t.containerId),function(e,t,i=R){e&&setTimeout(function(){gt(i,{type:"focusInput"})},t)}(a,n?0:300,t),e&&e(a,r,n),Ct(a?It:Et);const c=new CustomEvent("angieSidebarToggle",{detail:{isOpen:a,sidebar:r,skipTransition:n}});document.dispatchEvent(c),gt(t,{type:m.ANGIE_SIDEBAR_TOGGLED,payload:{state:a?"opened":"closed"}})}}(e?.onToggle,t),function(e=R){Dt||(Dt=!0,window.addEventListener("message",function(t){if("toggleAngieSidebar"!==t.data?.type)return;const i=e.iframeUrlObject?.origin;if(!(i?wt(t,i,e.iframe):_t(t,e.iframe)))return;const{force:n,skipTransition:s}=t.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(n,s);const r=t.ports?.[0];r&&ft(r)}))}(t))}const qt="angie_return_url",$t=g("referrer-redirect");function Mt(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function Ht(e,t){if(!Mt(e))return $t.warn("Invalid redirect URL rejected:",e),!1;try{const i={url:e};return t&&(i.prompt=t),localStorage.setItem(qt,JSON.stringify(i)),!0}catch(e){return $t.warn("localStorage not available"),!1}}function jt(){try{const e=localStorage.getItem(qt);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return $t.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?Mt(t.url)?t:($t.warn("Stored redirect URL is invalid, returning null:",t.url),null):($t.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return $t.warn("localStorage not available"),null}}function Gt(){try{localStorage.removeItem(qt)}catch(e){$t.warn("localStorage not available")}}function zt(e,t){return t?`${e}#angie-prompt=${encodeURIComponent(t)}`:e}function Wt(){const e=jt();return!!e&&(Gt(),window.location.href=zt(e.url,e.prompt),!0)}const Bt=g("oauth"),Ft=[];let Kt=!1,Jt=!1;const Vt=()=>{(()=>{try{const e=new URL(window.location.href,window.location.origin).searchParams;return e.has("start-oauth")&&"angie-app"===e.get("page")}catch{return!1}})()&&(Bt.log("Post-consent flow detected, checking for referrer redirect"),Wt())};function Qt(){const e=jt();if(e)return Gt(),void(window.location.href=zt(e.url,e.prompt));try{localStorage.setItem(kt,"open")}catch(e){Bt.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const Xt=e=>{Ft.includes(e)||Ft.push(e)},Yt=()=>{for(const e of Ft.flatMap(e=>e.iframe&&e.iframeUrlObject?[{window:e.iframe,windowURL:e.iframeUrlObject}]:[]))st({targets:e,onSuccess:Qt})},Zt="sidebar",ei="floatingChat",ti=[],ii=()=>ti.length,ni=e=>ti.find(t=>t.instanceId===e)??null,si=()=>ti.some(e=>e.layout===Zt),ri=g("sdk");var oi;(oi||(oi={})).POST_MESSAGE="postMessage";const ai=new Map,ci=[];let di=null;const li=()=>{0===ci.length||di||(di=e=>{const t=(e=>{if(e.origin===window.location.origin)return ci.find(t=>((e,t)=>!((!t||t!==e.instanceId)&&(t&&ni(t)||t&&null===ni(t)&&ii()>=1||(()=>{const e=ti.find(e=>null!==e.iframe);return e||(0===ti.length&&R.iframe?R:null)})()!==e)))(t,e?.data?.payload?.instanceId))??null;const t=ci.find(t=>t.iframe?.contentWindow===e.source);return t&&wt(e,t.iframeUrlObject?.origin,t.iframe)?t:null})(e);if(t)switch(e?.data?.type){case m.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case m.SDK_ANGIE_READY_PING:{const t=e.ports[0];ri.log("Angie is ready",e),ft(t,{message:"Angie is ready"});break}case m.SDK_REQUEST_CLIENT_CREATION:{const i=e.data.payload,n=e.ports[0];((e,t)=>{if(e.iframe)return void t();let i=ai.get(e);i||(i=[],ai.set(e,i)),i.push(t)})(t,()=>{try{const s=new MessageChannel;s.port1.onmessage=e=>{n.postMessage({success:!0,data:e.data})};const r={type:m.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...i,clientId:`dynamic-client-${i.serverName}-${i.serverVersion}`,requestId:e.data.payload.requestId},timestamp:Date.now()};t.iframe?.contentWindow?.postMessage(r,t.iframeUrlObject?.origin||"",[s.port2])}catch(e){ri.error(`Failed to create client for SDK server "${i.serverName}":`,e)}});break}case m.SDK_TRIGGER_ANGIE:ri.log("SDK Trigger Angie received",e.data);try{const{requestId:i,prompt:n,context:s,contextAttachment:r,suggestions:o,options:a}=e.data.payload;if(!t.iframe)throw new Error("Iframe not found");t.iframe.contentWindow?.postMessage({type:m.SDK_TRIGGER_ANGIE,payload:{requestId:i,prompt:n,context:s,contextAttachment:r,suggestions:o,options:a}},t.iframeUrlObject?.origin||""),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:i,response:"Angie triggered successfully"}},window.location.origin)}catch(t){ri.error("Failed to trigger Angie:",t),window.postMessage({type:m.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:e.data.payload?.requestId,error:t instanceof Error?t.message:"Unknown error"}},window.location.origin)}}},window.addEventListener("message",di))},gi=e=>{ci.includes(e)||ci.push(e)},ui=g("iframe"),hi=[];let pi=null;const _i=e=>{if(e.includes("://")||e.startsWith("//"))return!1;try{const t="https://test.com";return new URL(e,t).origin===t}catch{return!1}},wi=async(e=R)=>{if(e.iframe?.contentWindow&&e.iframeUrlObject)try{ui.log("Disabling navigation prevention in Angie iframe"),e.iframe.contentWindow.postMessage({type:m.ANGIE_DISABLE_NAVIGATION_PREVENTION},e.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw ui.error("Failed to disable navigation prevention:",e),e}else ui.warn("Cannot disable navigation prevention: iframe or origin not available")},mi=e=>{hi.push(e),pi||(pi=e=>{const t=hi.find(t=>_t(e,t.instance.iframe));t&&t.trustedOrigins.includes(e.origin)&&(async(e,t)=>{if(e?.data?.type===m.ANGIE_CHAT_TOGGLE)t.open=e.data.open,t.iframe&&pt(t.iframe,t.open,t.containerId);else if(e?.data?.type===m.ANGIE_STUDIO_TOGGLE){const i=e.data.isStudioOpen;if(!t.iframe)return;if(i)document.documentElement.classList.add("angie-studio-active");else{const e=Rt();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(e?.data?.type===m.ANGIE_NAVIGATE_TO_URL){const{url:i="",confirmed:n=!1}=e.data.payload||{};if(!n)return void ui.log("Navigation requires user confirmation");((e,t=[])=>{const i=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return i.includes(t.origin)}catch{return!1}})(i)?(await wi(t),window.location.assign(i)):ui.error("Navigation blocked: Invalid or unsafe URL",{url:i})}else if(e?.data?.type===m.ANGIE_PAGE_RELOAD){const{confirmed:i=!1}=e.data.payload||{};if(!i)return void ui.log("Page reload requires user confirmation");ui.log("Page reload confirmed - disabling navigation prevention and reloading"),await wi(t),setTimeout(()=>{window.location.reload()},50)}else e?.data?.type===y.RESET_HASH&&(window.location.hash="",ft(e.ports[0],{message:"Hash reset successfully"}))})(e,t.instance)},window.addEventListener("message",pi))},fi=async(e,t=R)=>{if(window.screen.availWidth<=768)return void ui.log("Mobile detected, skipping iframe injection");const i=t.containerId;let n=document.getElementById(i);if(!n){const e=performance.now();if(ui.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let t=0;const s=setInterval(()=>{n=document.getElementById(i),t++,(n||t>20)&&(clearInterval(s),n&&e())},100);setTimeout(()=>{if(clearInterval(s),n)return void e();const t=new MutationObserver(()=>{n=document.getElementById(i),n&&(t.disconnect(),e())});t.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{t.disconnect(),e()},8e3)},2e3)}),ui.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!n)return void ui.error("Sidebar container not found")}const{iframe:s,iframeUrlObject:r}=await(async e=>{const t=e.origin,i=new URL(e.path,t),n=e.instanceId||mt(),s=i.pathname.slice(1).replace(/\//,"--")+"-"+n;return new Promise(n=>{const r=new URL(t);r.pathname=i.pathname;const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(r.searchParams.append("colorScheme",e.uiTheme||o||"light"),r.searchParams.append("sdkVersion",e.sdkVersion),r.searchParams.append("instanceId",s),r.searchParams.append("origin",window.location.origin),e.isRTL&&r.searchParams.append("isRTL",e.isRTL?"true":"false"),e.appId&&r.searchParams.append("appId",e.appId),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&r.searchParams.append("debug_error",e)}i.searchParams.forEach((e,t)=>{r.searchParams.set(t,e)}),r.searchParams.set("ver",(new Date).getTime().toString());const a=e.parent||document,c=a.createElement("iframe"),d={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async t=>{if(wt(t,r.origin,c))switch(t.data.type){case y.ANGIE_READY:n({iframe:c,iframeUrlObject:r});break;case y.ANGIE_LOADED:c.contentWindow?.postMessage({type:y.HOST_READY,instanceId:s,...e.embeddedConfig?{embedded:e.embeddedConfig}:{}},r.origin)}}),c.setAttribute("src",r.href),c.id=e.iframeElementId||"angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(d).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):a.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:e.path&&_i(e.path)?e.path:"angie/wp-admin",insertCallback:e=>{ui.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const t=document.getElementById("angie-sidebar-loading");t&&(t.textContent=""),n?.appendChild(e)},embeddedConfig:e.embeddedConfig,css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.7.7",iframeElementId:t.iframeElementId,instanceId:t.instanceId,appId:t.appId});return t.iframe=s,t.iframeUrlObject=r,(e=>{li();const t=ai.get(e);t?.length&&(ai.delete(e),t.forEach(e=>e()))})(t),gi(t),li(),((e=R)=>{Xt(e),Kt||(Kt=!0,function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",i=>{if(i.origin!==e)return;const n=i.ports?.[0];switch(i.data.type){case Le:if(!n)return;it(n,{topUrl:window.location.href});break;case De:window.location.href=i.data.payload.url;break;case Ne:{if(!n)return;const e=i.data.payload.url;if(!history?.replaceState)return void nt(n,{message:"URL update not supported in this browser"});try{const i=window.location.href;history.replaceState({},"",e),function(e,t){const i=new URL(e).searchParams,n=new URL(t).searchParams,s=[Me,He,dist_$e];return s.some(e=>i.has(e))&&!s.some(e=>n.has(e))}(i,e)&&t?.(),it(n,{message:"URL updated successfully"})}catch(e){nt(n,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case qe:if(!n)return;it(n,{isPending:"true"===new URLSearchParams(window.location.search).get(Me)})}})}({trustedOrigin:e.iframeUrlObject?.origin??"",onOAuthParamsCleared:Qt}))})(t),((e=R)=>{Xt(e),Yt(),Jt||(Jt=!0,window.addEventListener("load",()=>{Bt.log("OIDC: Window load event fired, forwarding OIDC state if present"),Yt()}))})(t),mi({instance:t,trustedOrigins:[window.location.origin,e.origin||"https://angie.elementor.com"]}),{iframe:s,iframeOrigin:r.origin}},yi=g("registration-queue");class Si{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),yi.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,i){const n=this.queue.find(t=>t.id===e);n&&(n.status=t,i?n.error=i:"pending"!==t&&"registered"!==t||delete n.error,yi.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void yi.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();yi.log(`Processing ${t.length} pending registrations`);try{for(const i of t)try{await e(i),this.updateStatus(i.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(i.id,"failed",t),yi.error(`Failed to process registration ${i.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],yi.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return yi.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),yi.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),yi.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}const bi={layout:Zt,styleTheme:"",create:!0,skipDefaultCss:!1,persistOpenState:!0,resizable:!0,chatToggleButtonEnabled:!1},vi="#angie-widget-toggle",Ii={boot:{allowInIframe:!1},container:{layout:bi.layout,styleTheme:bi.styleTheme,create:bi.create,skipDefaultCss:bi.skipDefaultCss,persistOpenState:bi.persistOpenState,resizable:bi.resizable,chatToggleButtonSelector:vi},iframe:{origin:"https://angie.elementor.com",path:"angie/embedded",uiTheme:"light"}},Ei=new Map;let ki=!1;const Ti=async(e,t,i)=>{if(t)try{ft(e,{payload:await t()})}catch(t){yt(e,{message:t instanceof Error?t.message:String(t)})}else ft(e,i())},Ri=(e,t)=>e&&t?`${e}::__angie::${t}`:e,Ai=(e,t)=>{const i=Ri(e,t);try{const t=window.localStorage.getItem(i);return null!==t?t:i===e?null:window.localStorage.getItem(e)}catch{return null}},Ci=async e=>{const t=(e=>{const t=[...Ei.values()].filter(t=>t.iframeOrigin===e.origin);return t.length<=1?t[0]??null:t.find(t=>t.instance.iframe?.contentWindow===e.source)??null})(e);if(!t)return;const i=e.data?.type,n=e.ports?.[0];switch(i){case"GET_EXTERNAL_HEADERS":if(!n)return;await(async(e,t)=>{try{const i=t?await t():{};ft(e,(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(i))}catch(t){yt(e,{message:t instanceof Error?t.message:String(t)})}})(n,t.getExternalHeaders);break;case"angie/context/get-website-context":if(!n)return;await Ti(n,t.getWebsiteContext,()=>{return e=t.host,{payload:{name:document.title,tagline:"",homeUrl:window.location.origin,siteLang:document.documentElement.lang,docTitle:document.title,platform:"frontend",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,today:(new Date).toISOString().split("T")[0],...e?.website}};// removed by dead control flow var e; });break;case"angie/context/get-analytics-context":if(!n)return;await Ti(n,t.getAnalyticsContext,()=>{return e=t.host,{payload:{screenPath:window.location.pathname,...e?.analytics}};// removed by dead control flow var e; });break;case f.GET:if(!n)return;n.postMessage({value:Ai(e.data.key,t.host?.instanceId)});break;case f.SET:((e,t,i)=>{try{window.localStorage.setItem(Ri(e,i),t)}catch{}})(e.data.key,e.data.value,t.host?.instanceId)}},xi="data-angie-toggle-wired",Pi=(e,t)=>{const i=document.querySelector(e);i&&(i.setAttribute("aria-expanded",t?"true":"false"),i.setAttribute("aria-label",t?"Close Angie":"Open Angie"))},Oi=e=>{const t=document.querySelector(e.toggleButtonSelector);t&&"true"!==t.getAttribute(xi)&&(t.setAttribute(xi,"true"),t.addEventListener("click",e.onClick))},Ui=new Set;let Li=!1;const Di=e=>{for(const t of Ui)t(e)},Ni="angie-widget-toggle",qi="angie-widget-hidden",$i="angie-widget-fullscreen",Mi="angie-widget-container",Hi="angie-chat-widget-styles",ji=/^#([^\s#.[:]+)$/,Gi=/^\[([^\]=]+)(?:="([^"]*)")?\]$/,zi=e=>document.querySelector(e),Wi=new Map,Bi=e=>{const t=document.getElementById(e.containerId);t&&(e.isOpen?t.classList.remove(qi):t.classList.add(qi),e.instance.iframe&&pt(e.instance.iframe,e.isOpen,e.containerId),Pi(e.toggleButtonSelector,e.isOpen))},Fi=(e,t)=>{Bi({containerId:e.containerId,toggleButtonSelector:e.toggleButtonSelector,isOpen:t,instance:e.instance})},Ki=(e,t)=>{const i=t?.force;if(void 0!==i)return Fi(e,i),void(i||e.onClose?.());const n=(e=>{const t=document.getElementById(e);return!!t&&!t.classList.contains(qi)})(e.containerId);Fi(e,!n),n&&e.onClose?.()},Ji=e=>{const{instance:t}=e;var i;Wi.get(t)?.(),Wi.set(t,(i=i=>{if(!wt(i,e.iframeOrigin,t.iframe))return;const n=i.ports?.[0],{type:s,payload:r}=i.data||{};switch(s){case m.ANGIE_SIDEBAR_TOGGLED:case"toggleAngieSidebar":Ki(e,r),n&&ft(n);break;case m.ANGIE_STUDIO_TOGGLE:{const t=!!i.data.isStudioOpen;((e,t)=>{const i=document.getElementById(e);i&&(t?i.classList.add($i):i.classList.remove($i))})(e.containerId,t),t&&Fi(e,!0),n&&ft(n);break}}},Ui.add(i),Li||(Li=!0,window.addEventListener("message",Di)),()=>{Ui.delete(i)}))},Vi=e=>{const t=(e=>e===E?Hi:`${Hi}-${e}`)(e);if(document.getElementById(t))return;const i=document.createElement("style");i.id=t,i.textContent=(e=>`\n#${e}.${Mi} {\n\t--angie-widget-width: 400px;\n\t--angie-widget-height: 600px;\n\t--angie-widget-z-index: 99999;\n\n\tposition: fixed !important;\n\ttop: auto !important;\n\tbottom: 20px !important;\n\tinset-inline-start: auto !important;\n\tinset-inline-end: 20px !important;\n\twidth: var(--angie-widget-width) !important;\n\theight: var(--angie-widget-height) !important;\n\tmax-height: calc(100vh - 40px) !important;\n\tmax-width: calc(100vw - 40px) !important;\n\tz-index: var(--angie-widget-z-index) !important;\n\ttransform: none !important;\n\tborder-radius: 12px !important;\n\toverflow: hidden !important;\n\tbox-shadow: 0 4px 24px rgba(0, 0, 0, 0.15) !important;\n\ttransition: opacity 0.2s ease, transform 0.2s ease !important;\n}\n\n#${e}.${Mi}.${qi} {\n\tdisplay: none !important;\n}\n\n#${e}.${Mi} iframe {\n\twidth: 100% !important;\n\theight: 100% !important;\n\tborder: none !important;\n\tborder-radius: 12px !important;\n}\n\n\n.${Ni} {\n\t--angie-toggle-size: 56px;\n\t--angie-widget-z-index: 99999;\n\n\tposition: fixed;\n\tbottom: 20px;\n\tinset-inline-end: 20px;\n\twidth: var(--angie-toggle-size);\n\theight: var(--angie-toggle-size);\n\tborder-radius: 50%;\n\tborder: none;\n\tbackground: #EB8EFB;\n\tcolor: white;\n\tcursor: pointer;\n\tz-index: var(--angie-widget-z-index);\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tbox-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);\n\ttransition: background 0.2s ease, transform 0.15s ease;\n\tpadding: 0;\n}\n\n.${Ni}:hover {\n\tbackground: #E070F5;\n\ttransform: scale(1.05);\n}\n\n.${Ni}:active {\n\ttransform: scale(0.95);\n}\n\n.${Ni}[aria-expanded="true"] {\n\tdisplay: none;\n}\n\n\n#${e}.${Mi}.${$i} {\n\tbottom: 0 !important;\n\tinset-inline-end: 0 !important;\n\twidth: 100vw !important;\n\theight: 100vh !important;\n\tmax-height: 100vh !important;\n\tmax-width: 100vw !important;\n\tborder-radius: 0 !important;\n}\n\n#${e}.${Mi}.${$i} iframe {\n\tborder-radius: 0 !important;\n}\n\n@media (max-width: 480px) {\n\t#${e}.${Mi} {\n\t\tbottom: 0 !important;\n\t\tinset-inline-end: 0 !important;\n\t\twidth: 100vw !important;\n\t\theight: 100vh !important;\n\t\tmax-height: 100vh !important;\n\t\tmax-width: 100vw !important;\n\t\tborder-radius: 0 !important;\n\t}\n\n\t#${e}.${Mi} iframe {\n\t\tborder-radius: 0 !important;\n\t}\n}\n`)(e),document.head.appendChild(i)},Qi=e=>{const t=document.getElementById(e);t&&(t.classList.add(Mi,qi),t.setAttribute("role","complementary"),t.setAttribute("aria-label","Angie"),t.setAttribute("aria-hidden","true"),t.setAttribute("tabindex","-1"))};let Xi=!1;const Yi={initShell:({config:e,instance:t})=>{((e,t,i=R)=>{const n=e.chatToggleButton.enabled?e.chatToggleButton.selector:void 0;Nt({instance:i,skipDefaultCss:e.skipDefaultCss,onToggle:e=>{n&&Pi(n,e),t.onToggle?.(e),!e&&t.onClose&&t.onClose()}}),(e=>{if("wordpress"!==e||"undefined"==typeof document)return;const t="angie-sidebar-wordpress-styles";if(document.getElementById(t)||(Xi=!1),Xi)return;const i=document.createElement("style");i.id=t,i.textContent="body.admin-bar {\n --angie-sidebar-z-index: 99999;\n}\n\n#angie-body-top-padding {\n height: 0;\n transition: height 0.3s ease-in-out;\n}\n\nbody.angie-sidebar-transitioning #wpadminbar {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n@media (min-width: 768px) {\n body.angie-sidebar-active #angie-body-top-padding {\n width: 100%;\n height: 0;\n }\n\n body.angie-sidebar-active #wpadminbar {\n inset-inline-start: var(--angie-sidebar-width) !important;\n inset-inline-end: 0 !important;\n width: calc(100% - var(--angie-sidebar-width)) !important;\n margin-top: 0;\n }\n}\n\n@media (max-width: 768px) {\n body.angie-sidebar-active #wpadminbar {\n inset-inline-start: 0 !important;\n inset-inline-end: 0 !important;\n width: 100% !important;\n }\n}\n\nbody:not(.wp-admin) #angie-sidebar-container {\n margin-top: 3px;\n}\n",(document.head||document.getElementsByTagName("head")[0]).appendChild(i),Xi=!0})(e.styleTheme),n&&Oi({toggleButtonSelector:n,onClick:e=>{e.preventDefault(),window.toggleAngieSidebar?.()}})})(e.container,e.callbacks,t)},beforeOpenIframe:({config:e})=>{var t;(t=e.container).chatToggleButton.enabled&&(t.persistOpenState&&At()===It||Ut(Et))},afterOpenIframe:({config:e,instance:t})=>{((e,t=R)=>{e.persistOpenState&&Ot(e.chatToggleButton.enabled?Et:It),e.resizable&&Lt(t)})(e.container,t)}},Zi={initShell:({config:e,instance:t})=>{const{chatToggleButton:i}=e.container;var n;n={containerId:e.container.id,iframeOrigin:e.iframe.origin,onClose:e.callbacks.onClose,toggleButtonSelector:i.selector,injectToggleButton:i.enabled,instance:t},Vi(n.containerId),Qi(n.containerId),n.injectToggleButton&&(e=>{if(zi(e))return;const t=document.createElement("button");((e,t)=>{const i=t.match(ji);if(i)return void(e.id=i[1]);const n=t.match(Gi);n&&e.setAttribute(n[1],n[2]??"")})(t,e),t.className=Ni,t.setAttribute("aria-label","Open Angie"),t.setAttribute("aria-expanded","false"),t.type="button",t.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 16 16" fill="none">\n\t<path d="M15.0998 8.00414L14.622 8.18282C13.4991 8.60516 12.8142 9.50669 12.4001 10.6519L12.2249 11.1392L12.0497 10.6519C11.6356 9.50669 10.9109 8.60516 9.78801 8.18282L9.31018 8.00414L9.78801 7.82546C10.9109 7.40312 11.6356 6.50159 12.0497 5.3564L12.2249 4.86909L12.4001 5.3564C12.8142 6.50159 13.4991 7.40312 14.622 7.82546L15.0998 8.00414Z" fill="white"/>\n\t<path d="M2 8.42721C5.5608 8.42721 8.44479 11.3685 8.44479 15" stroke="white" stroke-width="2.05092" stroke-miterlimit="10"/>\n\t<path d="M2 7.57275C5.5608 7.57275 8.44479 4.6315 8.44479 0.999991" stroke="white" stroke-width="2.05092" stroke-miterlimit="10"/>\n</svg>',document.body.appendChild(t)})(n.toggleButtonSelector),(e=>{(e=>{Oi({toggleButtonSelector:e.toggleButtonSelector,onClick:()=>{const t=zi(e.toggleButtonSelector),i="true"===t?.getAttribute("aria-expanded");Fi(e,!i),i&&e.onClose?.()}})})(e),Ji(e),si()||(window.toggleAngieSidebar=t=>{Ki(e,{force:t})})})({containerId:n.containerId,iframeOrigin:n.iframeOrigin,onClose:n.onClose,toggleButtonSelector:n.toggleButtonSelector,instance:n.instance})},afterOpenIframe:({config:e})=>{Qi(e.container.id)}},en={[Zt]:Yi,[ei]:Zi},tn={layout:ei,styleTheme:"",create:!0,skipDefaultCss:!1,persistOpenState:!1,resizable:!1,chatToggleButtonEnabled:!0},nn={closeButton:"collapse"},sn=(e,t)=>e===ei?{closeButton:"close",...t}:t?{...nn,...t}:nn,rn=async e=>{Vt();const t={browserUiTheme:"undefined"!=typeof window&&"function"==typeof window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":Ii.iframe.uiTheme,isInIframe:"undefined"!=typeof window&&window!==window.top,isRTL:"undefined"!=typeof document&&"rtl"===document.documentElement.dir},i=((e,t)=>{const i=e.boot??{},n=e.container??{},s=e.iframe??{},r=e.callbacks??{},o=n.layout??Ii.container.layout,a=(e=>e===ei?tn:bi)(o),c=n.chatToggleButton?.enabled??a.chatToggleButtonEnabled;return{host:{appId:e.host.appId,instanceId:e.host.instanceId,aiContext:e.host.aiContext,website:e.host.website,analytics:e.host.analytics},boot:{allowInIframe:i.allowInIframe??Ii.boot.allowInIframe},container:{id:n.id?.trim()||E,layout:o,styleTheme:n.styleTheme??a.styleTheme,create:n.create??a.create,skipDefaultCss:n.skipDefaultCss??a.skipDefaultCss,persistOpenState:n.persistOpenState??a.persistOpenState,resizable:n.resizable??a.resizable,chatToggleButton:{enabled:c,selector:n.chatToggleButton?.selector?.trim()||Ii.container.chatToggleButtonSelector}},iframe:{origin:s.origin?.trim()||Ii.iframe.origin,path:s.path?.trim()||Ii.iframe.path,uiTheme:s.uiTheme??t.browserUiTheme,isRTL:s.isRTL??t.isRTL},callbacks:{onClose:r.onClose,onToggle:r.onToggle,getExternalHeaders:r.getExternalHeaders,getWebsiteContext:r.getWebsiteContext,getAnalyticsContext:r.getAnalyticsContext},widgetConfig:sn(o,e.widgetConfig)}})(e,t);if(!((e,t)=>!(!e.boot.allowInIframe&&t.isInIframe))(i,t))return;if(i.container.layout===Zt&&si())throw new Error('Angie SDK: only one sidebar layout instance is supported on a page. Use container.layout "floatingChat" for the extra instance.');if(n=i.container.id,ti.find(e=>e.containerId===n))throw new Error(`Angie SDK: container id "${i.container.id}" is already used by another Angie instance. Give this instance its own container.id.`);var n;const s=i.host.instanceId||e.sdkInstanceId||mt();if(ni(s))throw new Error(`Angie SDK: instance id "${s}" is already used by another Angie instance. Give this instance its own host.instanceId.`);ti[0]&&i.container.chatToggleButton.selector===vi&&(i.container.chatToggleButton.selector=`${vi}-${s}`);const r=(e=>{const t=0===ti.length,i={...T(),...e,iframeElementId:t?k:`${k}-${e.instanceId}`},n=t?Object.assign(R,i):i;return ti.push(n),n})({containerId:i.container.id,instanceId:s,appId:e.appId,layout:i.container.layout});var o;gi(r),li(),o={iframeOrigin:i.iframe.origin,host:i.host,getExternalHeaders:i.callbacks.getExternalHeaders,getWebsiteContext:i.callbacks.getWebsiteContext,getAnalyticsContext:i.callbacks.getAnalyticsContext,instance:r},Ei.set(o.instance,o),ki||(ki=!0,window.addEventListener("message",e=>{Ci(e)})),i.container.create&&((e,t)=>{if(document.getElementById(e))return;const i=document.createElement("div");i.id=e,i.dir=t?"rtl":"ltr";const n=document.createElement("div");n.id="angie-sidebar-loading",n.setAttribute("aria-live","polite"),n.className="angie-sr-only",i.appendChild(n),document.body.appendChild(i)})(i.container.id,t.isRTL);const a=en[i.container.layout],c={config:i,env:t,instance:r};a.initShell(c),a.beforeOpenIframe?.(c);const d={aiContext:(l=i.host).aiContext,appId:l.appId,configVersion:2,telemetry:{screenPath:window.location.pathname},website:{docTitle:document.title,homeUrl:window.location.origin,name:document.title,platform:"frontend",siteLang:document.documentElement.lang,tagline:"",...l.website}};var l;const g=await(async e=>{const t=e.instance??R;return!!await fi({isRTL:e.iframe.isRTL,origin:e.iframe.origin,path:e.iframe.path,uiTheme:e.iframe.uiTheme,embeddedConfig:e.embeddedConfig},t)&&(e.container.layout===ei&&e.container.chatToggleButton.enabled?(Bi({containerId:e.container.id,toggleButtonSelector:e.container.chatToggleButton.selector,isOpen:!1,instance:t}),!0):(t.iframe&&pt(t.iframe,!1,t.containerId),e.container.chatToggleButton.enabled&&Pi(e.container.chatToggleButton.selector,!1),!0))})({container:i.container,iframe:i.iframe,embeddedConfig:d,instance:r});a.afterOpenIframe?.(c),g&&(((e,t=R)=>{gt(t,{payload:e,type:"sdk-embedded-config"})})(d,r),i.widgetConfig&&((e,t=R)=>{gt(t,{payload:e,type:"sdk-widget-config"})})(i.widgetConfig,r))},on="angie-prompt",an=[],cn={origin:"https://angie.elementor.com",uiTheme:"light",isRTL:!1,containerId:E,skipDefaultCss:!1,path:"angie/wp-admin"};class dn{appId;angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;sidebarV2BootPromise=null;promptHashListenerAttached=!1;constructor(e){this.appId=e?.appId?.trim()||void 0,this.instanceId=mt(),this.logger=g({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new b(()=>this.instanceId),this.registrationQueue=new Si,this.clientManager=new I,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){Vt();const{widgetConfig:t,...i}=e||{},n={...cn,...i};R.containerId=n.containerId,R.instanceId=this.instanceId,R.appId=this.appId,Nt({skipDefaultCss:n.skipDefaultCss});const s=await fi(n);s&&window.addEventListener("message",e=>{if(e.origin===R.iframeUrlObject?.origin)switch(e.data.type){case f.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case f.GET:{const t=e.ports[0],i=window.localStorage.getItem(e.data.key);t.postMessage({value:i});break}}}),s&&t&&s.iframe.contentWindow?.postMessage({type:"sdk-widget-config",payload:t},s.iframeOrigin),this.setupPromptHashDetection()}loadSidebarV2(e){return e.host.instanceId&&(this.instanceId=e.host.instanceId),this.sidebarV2BootPromise=rn({...e,sdkInstanceId:this.instanceId,appId:this.appId}),this.setupPromptHashDetection(),this.sidebarV2BootPromise}isRefreshPingForThisInstance(e,t){const i=e.data?.payload?.instanceId;if(i)return i===this.instanceId;const n=t?.iframe?.contentWindow;return n&&e.source?e.source===n:ii()<2}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===m.SDK_ANGIE_REFRESH_PING){const t=ni(this.instanceId),i=t?.iframeUrlObject?.origin;if(i&&e.origin!==i)return void this.logger.log(`Ignoring refresh ping from unexpected origin. Event origin: ${e.origin}, iframe origin: ${i}`);if(!this.isRefreshPingForThisInstance(e,t))return;if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")}})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=_.LOCAL,e.transport=h.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=_.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===_.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===_.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const i=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",i),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(this.sidebarV2BootPromise)await this.sidebarV2BootPromise;else for(;!R.iframe;)await new Promise(e=>setTimeout(e,100));if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),i=e.options?.timeout||3e4;return new Promise((n,s)=>{const r=setTimeout(()=>{s(new Error("Angie trigger request timed out"))},i),o=e=>{e.data?.type===m.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(r),window.removeEventListener("message",o),n(e.data.payload))};window.addEventListener("message",o);const a={type:m.SDK_TRIGGER_ANGIE,payload:{requestId:t,instanceId:this.instanceId,prompt:e.prompt,options:e.options,contextAttachment:e.contextAttachment,suggestions:e.suggestions,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(a,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===m.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:i,instanceId:n}=e.data.payload||{};if(t&&i)if(this.logger.log(`Server init request received - Request instanceId: ${n}, This instanceId: ${this.instanceId}`),n&&n!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${n}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${i}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===i);if(!t)return void this.logger.log(`No registration found for serverId: ${i} (likely belongs to another instance)`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const n=e.ports[0];if(!n)return void this.logger.error("No port provided in server init request");const s=t.config.server;this.migrateInstructionsCompat(s);const r=new v(n);s.connect(r),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,i=t._serverInfo,n=t._instructions;i?.instructions&&!n&&(t._instructions=i.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}parseHashParams(e){const t=e.startsWith("#")?e.substring(1):e;return new URLSearchParams(t)}shouldHandlePromptHash(e){const t=e.get("angie-instance");return t?t===this.instanceId:0===an.length||an[0]===this}async handlePromptHash(){const e=window.location.hash;if(e.includes(`${on}=`))try{const t=this.parseHashParams(e);if(!this.shouldHandlePromptHash(t))return;const i=t.get(on)||"";if(!i)return void this.logger.warn("Empty prompt detected in hash");const n="true"===t.get("angie-new-chat");this.logger.log("Detected prompt in hash:",{prompt:i,newChat:n}),await this.waitForReady();const s=await this.triggerAngie({prompt:i,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()},options:{newChat:n}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.promptHashListenerAttached||(this.promptHashListenerAttached=!0,an.push(this),window.addEventListener("hashchange",()=>this.handlePromptHash())),this.handlePromptHash()}}let ln=null;const gn=e=>new Promise(t=>setTimeout(t,e)),un=()=>(ln||(ln=new b),ln),hn=()=>"undefined"!=typeof window&&!0===window.angiePlugin?.available,pn=()=>!!hn()&&un().isReady(),_n=async(e=3e3)=>"undefined"!=typeof window&&(async(e,t,i=50)=>{for(;Date.now()<e;){if(t())return!0;await gn(i)}return t()})(Date.now()+e,hn),wn=async(e=3e3)=>{if("undefined"==typeof window)return!1;const t=Date.now();if(!await _n(e))return!1;const i=Math.max(0,e-(Date.now()-t));return(await un().waitUntilReady(i)).isReady},mn=g("navigation"),fn=(e,t,i)=>{if(i?.iframe??ut()){t.isOpen&&window.toggleAngieSidebar&&window.toggleAngieSidebar(!0);const n={type:"angie-route-navigation",path:e,payload:t},s=i?gt(i,n):ht(n);return s||mn.error("Failed to post navigation message to Angie iframe"),s}return mn.error("Angie iframe not found"),!1},yn=g("interaction-mode"),Sn=e=>ut()?!!ht({type:m.ANGIE_SET_INTERACTION_MODE,payload:{mode:e}})||(yn.error("Failed to post interaction mode message to Angie iframe"),!1):(yn.error("Angie iframe not found"),!1),bn="angie/requiredResources",vn="angie/modelPreferences",In="angie/extendedTimeout",En="readOnlyHint";var kn;!function(e){e.Inline="inline",e.EndOfTurn="end-of-turn"}(kn||(kn={})); ;// ./node_modules/zod/v3/helpers/util.js var util_util; (function (util) { util.assertEqual = (_) => { }; function assertIs(_arg) { } util.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util.assertNever = assertNever; util.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util.getValidEnumValues = (obj) => { const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util.objectValues(filtered); }; util.objectValues = (obj) => { return util.objectKeys(obj).map(function (e) { return obj[e]; }); }; util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return undefined; }; util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); } util.joinValues = joinValues; util.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util_util || (util_util = {})); var objectUtil; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { return { ...first, ...second, // second overwrites first }; }; })(objectUtil || (objectUtil = {})); const ZodParsedType = util_util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set", ]); const util_getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; ;// ./node_modules/zod/v3/ZodError.js const ZodIssueCode = util_util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite", ]); const quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; class ZodError_ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { // eslint-disable-next-line ban/ban Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function (issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; // if (typeof el === "string") { // curr[el] = curr[el] || { _errors: [] }; // } else if (typeof el === "number") { // const errorArray: any = []; // errorArray._errors = []; // curr[el] = curr[el] || errorArray; // } } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof ZodError_ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util_util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { const firstEl = sub.path[0]; fieldErrors[firstEl] = fieldErrors[firstEl] || []; fieldErrors[firstEl].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } ZodError_ZodError.create = (issues) => { const error = new ZodError_ZodError(issues); return error; }; ;// ./node_modules/zod/v3/locales/en.js const errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util_util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util_util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util_util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util_util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util_util.assertNever(issue); } return { message }; }; /* harmony default export */ const locales_en = (errorMap); ;// ./node_modules/zod/v3/errors.js let overrideErrorMap = locales_en; function setErrorMap(map) { overrideErrorMap = map; } function getErrorMap() { return overrideErrorMap; } ;// ./node_modules/zod/v3/helpers/errorUtil.js var errorUtil; (function (errorUtil) { errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; // biome-ignore lint: errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); ;// ./node_modules/zod/v3/helpers/parseUtil.js const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; const fullIssue = { ...issueData, path: fullPath, }; if (issueData.message !== undefined) { return { ...issueData, path: fullPath, message: issueData.message, }; } let errorMessage = ""; const maps = errorMaps .filter((m) => !!m) .slice() .reverse(); for (const map of maps) { errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage, }; }; const EMPTY_PATH = (/* unused pure expression or super */ null && ([])); function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData: issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === locales_en ? undefined : locales_en, // then global default map ].filter((x) => !!x), }); ctx.common.issues.push(issue); } class ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } } const INVALID = Object.freeze({ status: "aborted", }); const DIRTY = (value) => ({ status: "dirty", value }); const OK = (value) => ({ status: "valid", value }); const isAborted = (x) => x.status === "aborted"; const isDirty = (x) => x.status === "dirty"; const isValid = (x) => x.status === "valid"; const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; ;// ./node_modules/zod/v3/types.js /* unused harmony import specifier */ var types_INVALID; class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } } const handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError_ZodError(ctx.common.issues); this._error = error; return this._error; }, }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap, invalid_type_error, required_error, description } = params; if (errorMap && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap) return { errorMap: errorMap, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } class types_ZodType { get description() { return this._def.description; } _getType(input) { return util_getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return (ctx || { common: input.parent.common, data: input.data, parsedType: util_getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }); } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: util_getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }, }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { const ctx = { common: { issues: [], async: params?.async ?? false, contextualErrorMap: params?.errorMap, }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: util_getParsedType(data), }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } "~validate"(data) { const ctx = { common: { issues: [], async: !!this["~standard"].async, }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: util_getParsedType(data), }; if (!this["~standard"].async) { try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value, } : { issues: ctx.common.issues, }; } catch (err) { if (err?.message?.toLowerCase()?.includes("encountered")) { this["~standard"].async = true; } ctx.common = { issues: [], async: true, }; } } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value, } : { issues: ctx.common.issues, }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params?.errorMap, async: true, }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: util_getParsedType(data), }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val), }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement }, }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { /** Alias of safeParseAsync */ this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data), }; } optional() { return types_ZodOptional.create(this, this._def); } nullable() { return types_ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return types_ZodArray.create(this); } promise() { return types_ZodPromise.create(this, this._def); } or(option) { return types_ZodUnion.create([this, option], this._def); } and(incoming) { return types_ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform }, }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new types_ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault, }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def), }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new types_ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch, }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description, }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return types_ZodReadonly.create(this); } isOptional() { return this.safeParse(undefined).success; } isNullable() { return this.safeParse(null).success; } } const cuidRegex = /^c[^\s-]{8,}$/i; const cuid2Regex = /^[0-9a-z]+$/; const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; // const uuidRegex = // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; const 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; const nanoidRegex = /^[a-z0-9_-]{21}$/i; const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; const 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)?)??$/; // from https://stackoverflow.com/a/46181/1550155 // old version: too slow, didn't support unicode // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; //old email regex // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; // eslint-disable-next-line // const emailRegex = // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((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}))\])|(\[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})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; // const emailRegex = // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; // const emailRegex = // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; // const emailRegex = // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; let emojiRegex; // faster, simpler, safer const 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])$/; const 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])$/; // const ipv6Regex = // /^(([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})))$/; const 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]))$/; const 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])$/; // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; // https://base64.guru/standards/base64url const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; // simple // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; // no leap year validation // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; // with leap year validation const 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])))`; const dateRegex = new RegExp(`^${dateRegexSource}$`); function timeRegexSource(args) { let secondsRegexSource = `[0-5]\\d`; if (args.precision) { secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } else if (args.precision == null) { secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } // Adapted from https://stackoverflow.com/a/3143231 function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } function isValidIP(ip, version) { if ((version === "v4" || !version) && ipv4Regex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6Regex.test(ip)) { return true; } return false; } function types_isValidJWT(jwt, alg) { if (!jwtRegex.test(jwt)) return false; try { const [header] = jwt.split("."); if (!header) return false; // Convert base64url to base64 const base64 = header .replace(/-/g, "+") .replace(/_/g, "/") .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); const decoded = JSON.parse(atob(base64)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && decoded?.typ !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version) { if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { return true; } return false; } class types_ZodString extends types_ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx.parsedType, }); return INVALID; } const status = new ParseStatus(); let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message, }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check.message, }); status.dirty(); } } else if (check.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "date", message: check.message, }); status.dirty(); } } else if (check.kind === "time") { const regex = timeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "time", message: check.message, }); status.dirty(); } } else if (check.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "jwt") { if (!types_isValidJWT(input.data, check.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cidr") { if (!isValidCidr(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else { util_util.assertNever(check); } } return { status: status.value, value: input.data }; } _regex(regex, validation, message) { return this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message), }); } _addCheck(check) { return new types_ZodString({ ...this._def, checks: [...this._def.checks, check], }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } nanoid(message) { return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } base64(message) { return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } base64url(message) { // base64url encoding is a modification of base64 that can safely be used in URLs and filenames return this._addCheck({ kind: "base64url", ...errorUtil.errToObj(message), }); } jwt(options) { return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } cidr(options) { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options, }); } return this._addCheck({ kind: "datetime", precision: typeof options?.precision === "undefined" ? null : options?.precision, offset: options?.offset ?? false, local: options?.local ?? false, ...errorUtil.errToObj(options?.message), }); } date(message) { return this._addCheck({ kind: "date", message }); } time(options) { if (typeof options === "string") { return this._addCheck({ kind: "time", precision: null, message: options, }); } return this._addCheck({ kind: "time", precision: typeof options?.precision === "undefined" ? null : options?.precision, ...errorUtil.errToObj(options?.message), }); } duration(message) { return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex: regex, ...errorUtil.errToObj(message), }); } includes(value, options) { return this._addCheck({ kind: "includes", value: value, position: options?.position, ...errorUtil.errToObj(options?.message), }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value: value, ...errorUtil.errToObj(message), }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value: value, ...errorUtil.errToObj(message), }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message), }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message), }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message), }); } /** * Equivalent to `.min(1)` */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new types_ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }], }); } toLowerCase() { return new types_ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }], }); } toUpperCase() { return new types_ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }], }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isCIDR() { return !!this._def.checks.find((ch) => ch.kind === "cidr"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get isBase64url() { // base64url encoding is a modification of base64 that can safely be used in URLs and filenames return !!this._def.checks.find((ch) => ch.kind === "base64url"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } types_ZodString.create = (params) => { return new types_ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: params?.coerce ?? false, ...processCreateParams(params), }); }; // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 function types_floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return (valInt % stepInt) / 10 ** decCount; } class types_ZodNumber extends types_ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx.parsedType, }); return INVALID; } let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util_util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message, }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (types_floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check.message, }); status.dirty(); } } else { util_util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new types_ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message), }, ], }); } _addCheck(check) { return new types_ZodNumber({ ...this._def, checks: [...this._def.checks, check], }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message), }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value: value, message: errorUtil.toString(message), }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message), }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message), })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util_util.isInteger(ch.value))); } get isFinite() { let max = null; let min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } } types_ZodNumber.create = (params) => { return new types_ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: params?.coerce || false, ...processCreateParams(params), }); }; class types_ZodBigInt extends types_ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { try { input.data = BigInt(input.data); } catch { return this._getInvalidInput(input); } } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else { util_util.assertNever(check); } } return { status: status.value, value: input.data }; } _getInvalidInput(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType, }); return INVALID; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new types_ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message), }, ], }); } _addCheck(check) { return new types_ZodBigInt({ ...this._def, checks: [...this._def.checks, check], }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } types_ZodBigInt.create = (params) => { return new types_ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: params?.coerce ?? false, ...processCreateParams(params), }); }; class types_ZodBoolean extends types_ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } types_ZodBoolean.create = (params) => { return new types_ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: params?.coerce || false, ...processCreateParams(params), }); }; class types_ZodDate extends types_ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx.parsedType, }); return INVALID; } if (Number.isNaN(input.data.getTime())) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_date, }); return INVALID; } const status = new ParseStatus(); let ctx = undefined; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date", }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date", }); status.dirty(); } } else { util_util.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()), }; } _addCheck(check) { return new types_ZodDate({ ...this._def, checks: [...this._def.checks, check], }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message), }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message), }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } } types_ZodDate.create = (params) => { return new types_ZodDate({ checks: [], coerce: params?.coerce || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params), }); }; class types_ZodSymbol extends types_ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } types_ZodSymbol.create = (params) => { return new types_ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params), }); }; class types_ZodUndefined extends types_ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } types_ZodUndefined.create = (params) => { return new types_ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params), }); }; class types_ZodNull extends types_ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } types_ZodNull.create = (params) => { return new types_ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params), }); }; class types_ZodAny extends types_ZodType { constructor() { super(...arguments); // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. this._any = true; } _parse(input) { return OK(input.data); } } types_ZodAny.create = (params) => { return new types_ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params), }); }; class types_ZodUnknown extends types_ZodType { constructor() { super(...arguments); // required this._unknown = true; } _parse(input) { return OK(input.data); } } types_ZodUnknown.create = (params) => { return new types_ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params), }); }; class types_ZodNever extends types_ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType, }); return INVALID; } } types_ZodNever.create = (params) => { return new types_ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params), }); }; class types_ZodVoid extends types_ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } types_ZodVoid.create = (params) => { return new types_ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params), }); }; class types_ZodArray extends types_ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: (tooSmall ? def.exactLength.value : undefined), maximum: (tooBig ? def.exactLength.value : undefined), type: "array", inclusive: true, exact: true, message: def.exactLength.message, }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message, }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message, }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result) => { return ParseStatus.mergeArray(status, result); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new types_ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) }, }); } max(maxLength, message) { return new types_ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) }, }); } length(len, message) { return new types_ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) }, }); } nonempty(message) { return this.min(1, message); } } types_ZodArray.create = (schema, params) => { return new types_ZodArray({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params), }); }; function deepPartialify(schema) { if (schema instanceof types_ZodObject) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = types_ZodOptional.create(deepPartialify(fieldSchema)); } return new types_ZodObject({ ...schema._def, shape: () => newShape, }); } else if (schema instanceof types_ZodArray) { return new types_ZodArray({ ...schema._def, type: deepPartialify(schema.element), }); } else if (schema instanceof types_ZodOptional) { return types_ZodOptional.create(deepPartialify(schema.unwrap())); } else if (schema instanceof types_ZodNullable) { return types_ZodNullable.create(deepPartialify(schema.unwrap())); } else if (schema instanceof types_ZodTuple) { return types_ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } class types_ZodObject extends types_ZodType { constructor() { super(...arguments); this._cached = null; /** * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. * If you want to pass through unknown properties, use `.passthrough()` instead. */ this.nonstrict = this.passthrough; // extend< // Augmentation extends ZodRawShape, // NewOutput extends util.flatten<{ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }>, // NewInput extends util.flatten<{ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // }> // >( // augmentation: Augmentation // ): ZodObject< // extendShape<T, Augmentation>, // UnknownKeys, // Catchall, // NewOutput, // NewInput // > { // return new ZodObject({ // ...this._def, // shape: () => ({ // ...this._def.shape(), // ...augmentation, // }), // }) as any; // } /** * @deprecated Use `.extend` instead * */ this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util_util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof types_ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data, }); } if (this._def.catchall instanceof types_ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] }, }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys, }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { // run catchall validation const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data, }); } } if (ctx.common.async) { return Promise.resolve() .then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet, }); } return syncPairs; }) .then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new types_ZodObject({ ...this._def, unknownKeys: "strict", ...(message !== undefined ? { errorMap: (issue, ctx) => { const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError, }; return { message: defaultError, }; }, } : {}), }); } strip() { return new types_ZodObject({ ...this._def, unknownKeys: "strip", }); } passthrough() { return new types_ZodObject({ ...this._def, unknownKeys: "passthrough", }); } // const AugmentFactory = // <Def extends ZodObjectDef>(def: Def) => // <Augmentation extends ZodRawShape>( // augmentation: Augmentation // ): ZodObject< // extendShape<ReturnType<Def["shape"]>, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new types_ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation, }), }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new types_ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape(), }), typeName: ZodFirstPartyTypeKind.ZodObject, }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema) { return this.augment({ [key]: schema }); } // merge<Incoming extends AnyZodObject>( // merging: Incoming // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => { // ZodObject< // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index) { return new types_ZodObject({ ...this._def, catchall: index, }); } pick(mask) { const shape = {}; for (const key of util_util.objectKeys(mask)) { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } } return new types_ZodObject({ ...this._def, shape: () => shape, }); } omit(mask) { const shape = {}; for (const key of util_util.objectKeys(this.shape)) { if (!mask[key]) { shape[key] = this.shape[key]; } } return new types_ZodObject({ ...this._def, shape: () => shape, }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util_util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new types_ZodObject({ ...this._def, shape: () => newShape, }); } required(mask) { const newShape = {}; for (const key of util_util.objectKeys(this.shape)) { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof types_ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } } return new types_ZodObject({ ...this._def, shape: () => newShape, }); } keyof() { return createZodEnum(util_util.objectKeys(this.shape)); } } types_ZodObject.create = (shape, params) => { return new types_ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: types_ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; types_ZodObject.strictCreate = (shape, params) => { return new types_ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: types_ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; types_ZodObject.lazycreate = (shape, params) => { return new types_ZodObject({ shape, unknownKeys: "strip", catchall: types_ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; class types_ZodUnion extends types_ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { // return first issue-free validation if it exists for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { // add issues from dirty option ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } // return invalid const unionErrors = results.map((result) => new ZodError_ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx, }), ctx: childCtx, }; })).then(handleResults); } else { let dirty = undefined; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx, }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues) => new ZodError_ZodError(issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID; } } get options() { return this._def.options; } } types_ZodUnion.create = (types, params) => { return new types_ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params), }); }; ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ////////// ////////// ////////// ZodDiscriminatedUnion ////////// ////////// ////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// const getDiscriminator = (type) => { if (type instanceof types_ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof types_ZodLiteral) { return [type.value]; } else if (type instanceof types_ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { // eslint-disable-next-line ban/ban return util_util.objectValues(type.enum); } else if (type instanceof types_ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof types_ZodUndefined) { return [undefined]; } else if (type instanceof types_ZodNull) { return [null]; } else if (type instanceof types_ZodOptional) { return [undefined, ...getDiscriminator(type.unwrap())]; } else if (type instanceof types_ZodNullable) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof types_ZodReadonly) { return getDiscriminator(type.unwrap()); } else if (type instanceof types_ZodCatch) { return getDiscriminator(type._def.innerType); } else { return []; } }; class types_ZodDiscriminatedUnion extends types_ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator], }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { // Get all the valid discriminator values const optionsMap = new Map(); // try { for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new types_ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params), }); } } function types_mergeValues(a, b) { const aType = util_getParsedType(a); const bType = util_getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util_util.objectKeys(b); const sharedKeys = util_util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = types_mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = types_mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } class types_ZodIntersection extends types_ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = types_mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types, }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, })); } } } types_ZodIntersection.create = (left, right, params) => { return new types_ZodIntersection({ left: left, right: right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params), }); }; // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; class types_ZodTuple extends types_ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array", }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array", }); status.dirty(); } const items = [...ctx.data] .map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }) .filter((x) => !!x); // filter nulls if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new types_ZodTuple({ ...this._def, rest, }); } } types_ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new types_ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params), }); }; class types_ZodRecord extends types_ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data, }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof types_ZodType) { return new types_ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third), }); } return new types_ZodRecord({ keyType: types_ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second), }); } } class types_ZodMap extends types_ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType, }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), }; }); if (ctx.common.async) { const finalMap = new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } } types_ZodMap.create = (keyType, valueType, params) => { return new types_ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params), }); }; class types_ZodSet extends types_ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType, }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message, }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message, }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements) { const parsedSet = new Set(); for (const element of elements) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements) => finalizeSet(elements)); } else { return finalizeSet(elements); } } min(minSize, message) { return new types_ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) }, }); } max(maxSize, message) { return new types_ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) }, }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } } types_ZodSet.create = (valueType, params) => { return new types_ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params), }); }; class ZodFunction extends types_ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType, }); return INVALID; } function makeArgsIssue(args, error) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), locales_en].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error, }, }); } function makeReturnsIssue(returns, error) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), locales_en].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error, }, }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof types_ZodPromise) { // Would love a way to avoid disabling this rule, but we need // an alias (using an arrow function was what caused 2651). // eslint-disable-next-line @typescript-eslint/no-this-alias const me = this; return OK(async function (...args) { const error = new ZodError_ZodError([]); const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { error.addIssue(makeArgsIssue(args, e)); throw error; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type .parseAsync(result, params) .catch((e) => { error.addIssue(makeReturnsIssue(result, e)); throw error; }); return parsedReturns; }); } else { // Would love a way to avoid disabling this rule, but we need // an alias (using an arrow function was what caused 2651). // eslint-disable-next-line @typescript-eslint/no-this-alias const me = this; return OK(function (...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError_ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError_ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: types_ZodTuple.create(items).rest(types_ZodUnknown.create()), }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType, }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new ZodFunction({ args: (args ? args : types_ZodTuple.create([]).rest(types_ZodUnknown.create())), returns: returns || types_ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params), }); } } class types_ZodLazy extends types_ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } } types_ZodLazy.create = (getter, params) => { return new types_ZodLazy({ getter: getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params), }); }; class types_ZodLiteral extends types_ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value, }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } } types_ZodLiteral.create = (value, params) => { return new types_ZodLiteral({ value: value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params), }); }; function createZodEnum(values, params) { return new types_ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params), }); } class types_ZodEnum extends types_ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util_util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type, }); return INVALID; } if (!this._cache) { this._cache = new Set(this._def.values); } if (!this._cache.has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues, }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values, newDef = this._def) { return types_ZodEnum.create(values, { ...this._def, ...newDef, }); } exclude(values, newDef = this._def) { return types_ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef, }); } } types_ZodEnum.create = createZodEnum; class ZodNativeEnum extends types_ZodType { _parse(input) { const nativeEnumValues = util_util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util_util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util_util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type, }); return INVALID; } if (!this._cache) { this._cache = new Set(util_util.getValidEnumValues(this._def.values)); } if (!this._cache.has(input.data)) { const expectedValues = util_util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues, }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } } ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values: values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params), }); }; class types_ZodPromise extends types_ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType, }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap, }); })); } } types_ZodPromise.create = (schema, params) => { return new types_ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params), }); }; class ZodEffects extends types_ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; }, }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed, path: ctx.path, parent: ctx, }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx, }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); // return value is ignored executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (!isValid(base)) return INVALID; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return INVALID; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result, })); }); } } util_util.assertNever(effect); } } ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params), }); }; ZodEffects.createWithPreprocess = (preprocess, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params), }); }; class types_ZodOptional extends types_ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(undefined); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } types_ZodOptional.create = (type, params) => { return new types_ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params), }); }; class types_ZodNullable extends types_ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } types_ZodNullable.create = (type, params) => { return new types_ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params), }); }; class types_ZodDefault extends types_ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx, }); } removeDefault() { return this._def.innerType; } } types_ZodDefault.create = (type, params) => { return new types_ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params), }); }; class types_ZodCatch extends types_ZodType { _parse(input) { const { ctx } = this._processInputParams(input); // newCtx is used to not collect issues from inner types in ctx const newCtx = { ...ctx, common: { ...ctx.common, issues: [], }, }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx, }, }); if (isAsync(result)) { return result.then((result) => { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError_ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError_ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; } } removeCatch() { return this._def.innerType; } } types_ZodCatch.create = (type, params) => { return new types_ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params), }); }; class types_ZodNaN extends types_ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType, }); return INVALID; } return { status: "valid", value: input.data }; } } types_ZodNaN.create = (params) => { return new types_ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params), }); }; const BRAND = Symbol("zod_brand"); class ZodBranded extends types_ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx, }); } unwrap() { return this._def.type; } } class ZodPipeline extends types_ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx, }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value, }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx, }); } } } static create(a, b) { return new ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline, }); } } class types_ZodReadonly extends types_ZodType { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } } types_ZodReadonly.create = (type, params) => { return new types_ZodReadonly({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params), }); }; //////////////////////////////////////// //////////////////////////////////////// ////////// ////////// ////////// z.custom ////////// ////////// ////////// //////////////////////////////////////// //////////////////////////////////////// function cleanParams(params, data) { const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const p2 = typeof p === "string" ? { message: p } : p; return p2; } function types_custom(check, _params = {}, /** * @deprecated * * Pass `fatal` into the params object instead: * * ```ts * z.string().custom((val) => val.length > 5, { fatal: false }) * ``` * */ fatal) { if (check) return types_ZodAny.create().superRefine((data, ctx) => { const r = check(data); if (r instanceof Promise) { return r.then((r) => { if (!r) { const params = cleanParams(_params, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } }); } if (!r) { const params = cleanParams(_params, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } return; }); return types_ZodAny.create(); } const late = { object: types_ZodObject.lazycreate, }; var ZodFirstPartyTypeKind; (function (ZodFirstPartyTypeKind) { ZodFirstPartyTypeKind["ZodString"] = "ZodString"; ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); // requires TS 4.4+ class types_Class { constructor(..._) { } } const instanceOfType = ( // const instanceOfType = <T extends new (...args: any[]) => any>( cls, params = { message: `Input not instance of ${cls.name}`, }) => types_custom((data) => data instanceof cls, params); const stringType = types_ZodString.create; const numberType = types_ZodNumber.create; const nanType = types_ZodNaN.create; const bigIntType = types_ZodBigInt.create; const booleanType = types_ZodBoolean.create; const dateType = types_ZodDate.create; const symbolType = types_ZodSymbol.create; const undefinedType = types_ZodUndefined.create; const nullType = types_ZodNull.create; const anyType = types_ZodAny.create; const unknownType = types_ZodUnknown.create; const neverType = types_ZodNever.create; const voidType = types_ZodVoid.create; const arrayType = types_ZodArray.create; const objectType = types_ZodObject.create; const strictObjectType = types_ZodObject.strictCreate; const unionType = types_ZodUnion.create; const discriminatedUnionType = types_ZodDiscriminatedUnion.create; const intersectionType = types_ZodIntersection.create; const tupleType = types_ZodTuple.create; const recordType = types_ZodRecord.create; const mapType = types_ZodMap.create; const setType = types_ZodSet.create; const functionType = ZodFunction.create; const lazyType = types_ZodLazy.create; const literalType = types_ZodLiteral.create; const enumType = types_ZodEnum.create; const nativeEnumType = ZodNativeEnum.create; const promiseType = types_ZodPromise.create; const effectsType = ZodEffects.create; const optionalType = types_ZodOptional.create; const nullableType = types_ZodNullable.create; const preprocessType = ZodEffects.createWithPreprocess; const pipelineType = ZodPipeline.create; const ostring = () => stringType().optional(); const onumber = () => numberType().optional(); const oboolean = () => booleanType().optional(); const coerce = (/* unused pure expression or super */ null && ({ string: ((arg) => types_ZodString.create({ ...arg, coerce: true })), number: ((arg) => types_ZodNumber.create({ ...arg, coerce: true })), boolean: ((arg) => types_ZodBoolean.create({ ...arg, coerce: true, })), bigint: ((arg) => types_ZodBigInt.create({ ...arg, coerce: true })), date: ((arg) => types_ZodDate.create({ ...arg, coerce: true })), })); const types_NEVER = (/* unused pure expression or super */ null && (types_INVALID)); ;// ./node_modules/zod/v4/mini/schemas.js /* unused harmony import specifier */ var mini_schemas_core; /* unused harmony import specifier */ var mini_schemas_util; const ZodMiniType = /*@__PURE__*/ $constructor("ZodMiniType", (inst, def) => { if (!inst._zod) throw new Error("Uninitialized schema in ZodMiniType."); $ZodType.init(inst, def); inst.def = def; inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse(inst, data, params); inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); inst.check = (...checks) => { return inst.clone({ ...def, checks: [ ...(def.checks ?? []), ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), ], } // { parent: true } ); }; inst.clone = (_def, params) => clone(inst, _def, params); inst.brand = () => inst; inst.register = ((reg, meta) => { reg.add(inst, meta); return inst; }); }); const ZodMiniString = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniString", (inst, def) => { mini_schemas_core.$ZodString.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_string(params) { return mini_schemas_core._string(ZodMiniString, params); } const ZodMiniStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniStringFormat", (inst, def) => { mini_schemas_core.$ZodStringFormat.init(inst, def); ZodMiniString.init(inst, def); }))); const ZodMiniEmail = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniEmail", (inst, def) => { mini_schemas_core.$ZodEmail.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_email(params) { return mini_schemas_core._email(ZodMiniEmail, params); } const ZodMiniGUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniGUID", (inst, def) => { mini_schemas_core.$ZodGUID.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_guid(params) { return mini_schemas_core._guid(ZodMiniGUID, params); } const ZodMiniUUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniUUID", (inst, def) => { mini_schemas_core.$ZodUUID.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_uuid(params) { return mini_schemas_core._uuid(ZodMiniUUID, params); } function schemas_uuidv4(params) { return mini_schemas_core._uuidv4(ZodMiniUUID, params); } // ZodMiniUUIDv6 function schemas_uuidv6(params) { return mini_schemas_core._uuidv6(ZodMiniUUID, params); } // ZodMiniUUIDv7 function schemas_uuidv7(params) { return mini_schemas_core._uuidv7(ZodMiniUUID, params); } const ZodMiniURL = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniURL", (inst, def) => { mini_schemas_core.$ZodURL.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function schemas_url(params) { return mini_schemas_core._url(ZodMiniURL, params); } const ZodMiniEmoji = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniEmoji", (inst, def) => { mini_schemas_core.$ZodEmoji.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_emoji(params) { return mini_schemas_core._emoji(ZodMiniEmoji, params); } const ZodMiniNanoID = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNanoID", (inst, def) => { mini_schemas_core.$ZodNanoID.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_nanoid(params) { return mini_schemas_core._nanoid(ZodMiniNanoID, params); } const ZodMiniCUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniCUID", (inst, def) => { mini_schemas_core.$ZodCUID.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_cuid(params) { return mini_schemas_core._cuid(ZodMiniCUID, params); } const ZodMiniCUID2 = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniCUID2", (inst, def) => { mini_schemas_core.$ZodCUID2.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_cuid2(params) { return mini_schemas_core._cuid2(ZodMiniCUID2, params); } const ZodMiniULID = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniULID", (inst, def) => { mini_schemas_core.$ZodULID.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_ulid(params) { return mini_schemas_core._ulid(ZodMiniULID, params); } const ZodMiniXID = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniXID", (inst, def) => { mini_schemas_core.$ZodXID.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_xid(params) { return mini_schemas_core._xid(ZodMiniXID, params); } const ZodMiniKSUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniKSUID", (inst, def) => { mini_schemas_core.$ZodKSUID.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_ksuid(params) { return mini_schemas_core._ksuid(ZodMiniKSUID, params); } const ZodMiniIPv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniIPv4", (inst, def) => { mini_schemas_core.$ZodIPv4.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_ipv4(params) { return mini_schemas_core._ipv4(ZodMiniIPv4, params); } const ZodMiniIPv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniIPv6", (inst, def) => { mini_schemas_core.$ZodIPv6.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_ipv6(params) { return mini_schemas_core._ipv6(ZodMiniIPv6, params); } const ZodMiniCIDRv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniCIDRv4", (inst, def) => { mini_schemas_core.$ZodCIDRv4.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_cidrv4(params) { return mini_schemas_core._cidrv4(ZodMiniCIDRv4, params); } const ZodMiniCIDRv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniCIDRv6", (inst, def) => { mini_schemas_core.$ZodCIDRv6.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_cidrv6(params) { return mini_schemas_core._cidrv6(ZodMiniCIDRv6, params); } const ZodMiniBase64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniBase64", (inst, def) => { mini_schemas_core.$ZodBase64.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_base64(params) { return mini_schemas_core._base64(ZodMiniBase64, params); } const ZodMiniBase64URL = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniBase64URL", (inst, def) => { mini_schemas_core.$ZodBase64URL.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_base64url(params) { return mini_schemas_core._base64url(ZodMiniBase64URL, params); } const ZodMiniE164 = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniE164", (inst, def) => { mini_schemas_core.$ZodE164.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function mini_schemas_e164(params) { return mini_schemas_core._e164(ZodMiniE164, params); } const ZodMiniJWT = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniJWT", (inst, def) => { mini_schemas_core.$ZodJWT.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function schemas_jwt(params) { return mini_schemas_core._jwt(ZodMiniJWT, params); } const ZodMiniCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniCustomStringFormat", (inst, def) => { mini_schemas_core.$ZodCustomStringFormat.init(inst, def); ZodMiniStringFormat.init(inst, def); }))); function schemas_stringFormat(format, fnOrRegex, _params = {}) { return mini_schemas_core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params); } const ZodMiniNumber = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNumber", (inst, def) => { mini_schemas_core.$ZodNumber.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_number(params) { return mini_schemas_core._number(ZodMiniNumber, params); } const ZodMiniNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNumberFormat", (inst, def) => { mini_schemas_core.$ZodNumberFormat.init(inst, def); ZodMiniNumber.init(inst, def); }))); // int function mini_schemas_int(params) { return mini_schemas_core._int(ZodMiniNumberFormat, params); } // float32 function schemas_float32(params) { return mini_schemas_core._float32(ZodMiniNumberFormat, params); } // float64 function schemas_float64(params) { return mini_schemas_core._float64(ZodMiniNumberFormat, params); } // int32 function schemas_int32(params) { return mini_schemas_core._int32(ZodMiniNumberFormat, params); } // uint32 function schemas_uint32(params) { return mini_schemas_core._uint32(ZodMiniNumberFormat, params); } const ZodMiniBoolean = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniBoolean", (inst, def) => { mini_schemas_core.$ZodBoolean.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_boolean(params) { return mini_schemas_core._boolean(ZodMiniBoolean, params); } const ZodMiniBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniBigInt", (inst, def) => { mini_schemas_core.$ZodBigInt.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_bigint(params) { return mini_schemas_core._bigint(ZodMiniBigInt, params); } const ZodMiniBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniBigIntFormat", (inst, def) => { mini_schemas_core.$ZodBigIntFormat.init(inst, def); ZodMiniBigInt.init(inst, def); }))); // int64 function schemas_int64(params) { return mini_schemas_core._int64(ZodMiniBigIntFormat, params); } // uint64 function schemas_uint64(params) { return mini_schemas_core._uint64(ZodMiniBigIntFormat, params); } const ZodMiniSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniSymbol", (inst, def) => { mini_schemas_core.$ZodSymbol.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_symbol(params) { return mini_schemas_core._symbol(ZodMiniSymbol, params); } const ZodMiniUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniUndefined", (inst, def) => { mini_schemas_core.$ZodUndefined.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_undefined(params) { return mini_schemas_core._undefined(ZodMiniUndefined, params); } const ZodMiniNull = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNull", (inst, def) => { mini_schemas_core.$ZodNull.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_null(params) { return mini_schemas_core._null(ZodMiniNull, params); } const ZodMiniAny = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniAny", (inst, def) => { mini_schemas_core.$ZodAny.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_any() { return mini_schemas_core._any(ZodMiniAny); } const ZodMiniUnknown = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniUnknown", (inst, def) => { mini_schemas_core.$ZodUnknown.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_unknown() { return mini_schemas_core._unknown(ZodMiniUnknown); } const ZodMiniNever = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNever", (inst, def) => { mini_schemas_core.$ZodNever.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_never(params) { return mini_schemas_core._never(ZodMiniNever, params); } const ZodMiniVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniVoid", (inst, def) => { mini_schemas_core.$ZodVoid.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_void(params) { return mini_schemas_core._void(ZodMiniVoid, params); } const ZodMiniDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniDate", (inst, def) => { mini_schemas_core.$ZodDate.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_date(params) { return mini_schemas_core._date(ZodMiniDate, params); } const ZodMiniArray = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniArray", (inst, def) => { mini_schemas_core.$ZodArray.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_array(element, params) { return new ZodMiniArray({ type: "array", element: element, ...mini_schemas_util.normalizeParams(params), }); } // .keyof function schemas_keyof(schema) { const shape = schema._zod.def.shape; return schemas_literal(Object.keys(shape)); } const ZodMiniObject = /*@__PURE__*/ $constructor("ZodMiniObject", (inst, def) => { $ZodObject.init(inst, def); ZodMiniType.init(inst, def); defineLazy(inst, "shape", () => def.shape); }); function schemas_object(shape, params) { const def = { type: "object", get shape() { assignProp(this, "shape", { ...shape }); return this.shape; }, ...normalizeParams(params), }; return new ZodMiniObject(def); } // strictObject function schemas_strictObject(shape, params) { return new ZodMiniObject({ type: "object", // shape: shape as core.$ZodLooseShape, get shape() { mini_schemas_util.assignProp(this, "shape", { ...shape }); return this.shape; }, catchall: schemas_never(), ...mini_schemas_util.normalizeParams(params), }); } // looseObject function schemas_looseObject(shape, params) { return new ZodMiniObject({ type: "object", // shape: shape as core.$ZodLooseShape, get shape() { mini_schemas_util.assignProp(this, "shape", { ...shape }); return this.shape; }, // get optional() { // return util.optionalKeys(shape); // }, catchall: schemas_unknown(), ...mini_schemas_util.normalizeParams(params), }); } // object methods function schemas_extend(schema, shape) { return mini_schemas_util.extend(schema, shape); } function schemas_merge(schema, shape) { return mini_schemas_util.extend(schema, shape); } function schemas_pick(schema, mask) { return mini_schemas_util.pick(schema, mask); } // .omit function schemas_omit(schema, mask) { return mini_schemas_util.omit(schema, mask); } function schemas_partial(schema, mask) { return mini_schemas_util.partial(ZodMiniOptional, schema, mask); } function schemas_required(schema, mask) { return mini_schemas_util.required(ZodMiniNonOptional, schema, mask); } function catchall(inst, catchall) { return inst.clone({ ...inst._zod.def, catchall: catchall }); } const ZodMiniUnion = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniUnion", (inst, def) => { mini_schemas_core.$ZodUnion.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_union(options, params) { return new ZodMiniUnion({ type: "union", options: options, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniDiscriminatedUnion = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniDiscriminatedUnion", (inst, def) => { mini_schemas_core.$ZodDiscriminatedUnion.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_discriminatedUnion(discriminator, options, params) { return new ZodMiniDiscriminatedUnion({ type: "union", options, discriminator, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniIntersection = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniIntersection", (inst, def) => { mini_schemas_core.$ZodIntersection.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_intersection(left, right) { return new ZodMiniIntersection({ type: "intersection", left: left, right: right, }); } const ZodMiniTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniTuple", (inst, def) => { mini_schemas_core.$ZodTuple.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof mini_schemas_core.$ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new ZodMiniTuple({ type: "tuple", items: items, rest, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniRecord = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniRecord", (inst, def) => { mini_schemas_core.$ZodRecord.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_record(keyType, valueType, params) { return new ZodMiniRecord({ type: "record", keyType, valueType: valueType, ...mini_schemas_util.normalizeParams(params), }); } function schemas_partialRecord(keyType, valueType, params) { return new ZodMiniRecord({ type: "record", keyType: schemas_union([keyType, schemas_never()]), valueType: valueType, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniMap", (inst, def) => { mini_schemas_core.$ZodMap.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_map(keyType, valueType, params) { return new ZodMiniMap({ type: "map", keyType: keyType, valueType: valueType, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniSet", (inst, def) => { mini_schemas_core.$ZodSet.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_set(valueType, params) { return new ZodMiniSet({ type: "set", valueType: valueType, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniEnum = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniEnum", (inst, def) => { mini_schemas_core.$ZodEnum.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_enum(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new ZodMiniEnum({ type: "enum", entries, ...mini_schemas_util.normalizeParams(params), }); } /** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. * * ```ts * enum Colors { red, green, blue } * z.enum(Colors); * ``` */ function schemas_nativeEnum(entries, params) { return new ZodMiniEnum({ type: "enum", entries, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniLiteral", (inst, def) => { mini_schemas_core.$ZodLiteral.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_literal(value, params) { return new ZodMiniLiteral({ type: "literal", values: Array.isArray(value) ? value : [value], ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniFile", (inst, def) => { mini_schemas_core.$ZodFile.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_file(params) { return mini_schemas_core._file(ZodMiniFile, params); } const ZodMiniTransform = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniTransform", (inst, def) => { mini_schemas_core.$ZodTransform.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_transform(fn) { return new ZodMiniTransform({ type: "transform", transform: fn, }); } const ZodMiniOptional = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniOptional", (inst, def) => { mini_schemas_core.$ZodOptional.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_optional(innerType) { return new ZodMiniOptional({ type: "optional", innerType: innerType, }); } const ZodMiniNullable = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNullable", (inst, def) => { mini_schemas_core.$ZodNullable.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_nullable(innerType) { return new ZodMiniNullable({ type: "nullable", innerType: innerType, }); } // nullish function mini_schemas_nullish(innerType) { return schemas_optional(schemas_nullable(innerType)); } const ZodMiniDefault = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniDefault", (inst, def) => { mini_schemas_core.$ZodDefault.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_default(innerType, defaultValue) { return new ZodMiniDefault({ type: "default", innerType: innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; }, }); } const ZodMiniPrefault = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniPrefault", (inst, def) => { mini_schemas_core.$ZodPrefault.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_prefault(innerType, defaultValue) { return new ZodMiniPrefault({ type: "prefault", innerType: innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; }, }); } const ZodMiniNonOptional = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNonOptional", (inst, def) => { mini_schemas_core.$ZodNonOptional.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_nonoptional(innerType, params) { return new ZodMiniNonOptional({ type: "nonoptional", innerType: innerType, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniSuccess", (inst, def) => { mini_schemas_core.$ZodSuccess.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_success(innerType) { return new ZodMiniSuccess({ type: "success", innerType: innerType, }); } const ZodMiniCatch = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniCatch", (inst, def) => { mini_schemas_core.$ZodCatch.init(inst, def); ZodMiniType.init(inst, def); }))); function mini_schemas_catch(innerType, catchValue) { return new ZodMiniCatch({ type: "catch", innerType: innerType, catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), }); } const ZodMiniNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniNaN", (inst, def) => { mini_schemas_core.$ZodNaN.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_nan(params) { return mini_schemas_core._nan(ZodMiniNaN, params); } const ZodMiniPipe = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniPipe", (inst, def) => { mini_schemas_core.$ZodPipe.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_pipe(in_, out) { return new ZodMiniPipe({ type: "pipe", in: in_, out: out, }); } const ZodMiniReadonly = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniReadonly", (inst, def) => { mini_schemas_core.$ZodReadonly.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_readonly(innerType) { return new ZodMiniReadonly({ type: "readonly", innerType: innerType, }); } const ZodMiniTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniTemplateLiteral", (inst, def) => { mini_schemas_core.$ZodTemplateLiteral.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_templateLiteral(parts, params) { return new ZodMiniTemplateLiteral({ type: "template_literal", parts, ...mini_schemas_util.normalizeParams(params), }); } const ZodMiniLazy = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniLazy", (inst, def) => { mini_schemas_core.$ZodLazy.init(inst, def); ZodMiniType.init(inst, def); }))); // export function lazy<T extends object>(getter: () => T): T { // return util.createTransparentProxy<T>(getter); // } function schemas_lazy(getter) { return new ZodMiniLazy({ type: "lazy", getter: getter, }); } const ZodMiniPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniPromise", (inst, def) => { mini_schemas_core.$ZodPromise.init(inst, def); ZodMiniType.init(inst, def); }))); function schemas_promise(innerType) { return new ZodMiniPromise({ type: "promise", innerType: innerType, }); } const ZodMiniCustom = /*@__PURE__*/ (/* unused pure expression or super */ null && (mini_schemas_core.$constructor("ZodMiniCustom", (inst, def) => { mini_schemas_core.$ZodCustom.init(inst, def); ZodMiniType.init(inst, def); }))); // custom checks function schemas_check(fn, params) { const ch = new mini_schemas_core.$ZodCheck({ check: "custom", ...mini_schemas_util.normalizeParams(params), }); ch._zod.check = fn; return ch; } // ZodCustom // custom schema function schemas_custom(fn, _params) { return mini_schemas_core._custom(ZodMiniCustom, fn ?? (() => true), _params); } // refine function schemas_refine(fn, _params = {}) { return mini_schemas_core._refine(ZodMiniCustom, fn, _params); } // instanceof class schemas_Class { constructor(..._args) { } } function schemas_instanceof(cls, params = { error: `Input not instance of ${cls.name}`, }) { const inst = schemas_custom((data) => data instanceof cls, params); inst._zod.bag.Class = cls; return inst; } // stringbool const schemas_stringbool = (...args) => mini_schemas_core._stringbool({ Pipe: ZodMiniPipe, Boolean: ZodMiniBoolean, String: ZodMiniString, Transform: ZodMiniTransform, }, ...args); function schemas_json() { const jsonSchema = schemas_lazy(() => { return schemas_union([mini_schemas_string(), mini_schemas_number(), mini_schemas_boolean(), mini_schemas_null(), schemas_array(jsonSchema), schemas_record(mini_schemas_string(), jsonSchema)]); }); return jsonSchema; } ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js // zod-compat.ts // ---------------------------------------------------- // Unified types + helpers to accept Zod v3 and v4 (Mini) // ---------------------------------------------------- // --- Runtime detection --- function isZ4Schema(s) { // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 const schema = s; return !!schema._zod; } // --- Schema construction --- function objectFromShape(shape) { const values = Object.values(shape); if (values.length === 0) return schemas_object({}); // default to v4 Mini const allV4 = values.every(isZ4Schema); const allV3 = values.every(s => !isZ4Schema(s)); if (allV4) return schemas_object(shape); if (allV3) return objectType(shape); throw new Error('Mixed Zod versions detected in object shape.'); } // --- Unified parsing --- function zod_compat_safeParse(schema, data) { if (isZ4Schema(schema)) { // Mini exposes top-level safeParse const result = safeParse(schema, data); return result; } const v3Schema = schema; const result = v3Schema.safeParse(data); return result; } async function zod_compat_safeParseAsync(schema, data) { if (isZ4Schema(schema)) { // Mini exposes top-level safeParseAsync const result = await safeParseAsync(schema, data); return result; } const v3Schema = schema; const result = await v3Schema.safeParseAsync(data); return result; } // --- Shape extraction --- function getObjectShape(schema) { if (!schema) return undefined; // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` let rawShape; if (isZ4Schema(schema)) { const v4Schema = schema; rawShape = v4Schema._zod?.def?.shape; } else { const v3Schema = schema; rawShape = v3Schema.shape; } if (!rawShape) return undefined; if (typeof rawShape === 'function') { try { return rawShape(); } catch { return undefined; } } return rawShape; } // --- Schema normalization --- /** * Normalizes a schema to an object schema. Handles both: * - Already-constructed object schemas (v3 or v4) * - Raw shapes that need to be wrapped into object schemas */ function normalizeObjectSchema(schema) { if (!schema) return undefined; // First check if it's a raw shape (Record<string, AnySchema>) // Raw shapes don't have _def or _zod properties and aren't schemas themselves if (typeof schema === 'object') { // Check if it's actually a ZodRawShapeCompat (not a schema instance) // by checking if it lacks schema-like internal properties const asV3 = schema; const asV4 = schema; // If it's not a schema instance (no _def or _zod), it might be a raw shape if (!asV3._def && !asV4._zod) { // Check if all values are schemas (heuristic to confirm it's a raw shape) const values = Object.values(schema); if (values.length > 0 && values.every(v => typeof v === 'object' && v !== null && (v._def !== undefined || v._zod !== undefined || typeof v.parse === 'function'))) { return objectFromShape(schema); } } } // If we get here, it should be an AnySchema (not a raw shape) // Check if it's already an object schema if (isZ4Schema(schema)) { // Check if it's a v4 object const v4Schema = schema; const def = v4Schema._zod?.def; if (def && (def.type === 'object' || def.shape !== undefined)) { return schema; } } else { // Check if it's a v3 object const v3Schema = schema; if (v3Schema.shape !== undefined) { return schema; } } return undefined; } function getDotPath(path) { if (path.length === 0) { return 'object root'; } return path.reduce((acc, seg, index) => { if (index === 0) { return String(seg); } if (typeof seg === 'number') { return `${acc}[${seg}]`; } return `${acc}.${seg}`; }, ''); } // --- Error message extraction --- /** * Safely extracts an error message from a parse result error. * Zod errors can have different structures, so we handle various cases. */ function getParseErrorMessage(error) { if (error && typeof error === 'object') { // When present, prioritize zod issues and format as a message and path if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { return error.issues .map((i) => { if (!i.path?.length) { return i.message; } return `${i.message} at ${getDotPath(i.path)}`; }) .join('\n'); } // Try common error structures if ('message' in error && typeof error.message === 'string') { return error.message; } // Fallback: try to stringify the error try { return JSON.stringify(error); } catch { return String(error); } } return String(error); } // --- Schema metadata access --- /** * Gets the description from a schema, if available. * Works with both Zod v3 and v4. * * Both versions expose a `.description` getter that returns the description * from their respective internal storage (v3: _def, v4: globalRegistry). */ function getSchemaDescription(schema) { return schema.description; } /** * Checks if a schema is optional. * Works with both Zod v3 and v4. */ function isSchemaOptional(schema) { if (isZ4Schema(schema)) { const v4Schema = schema; return v4Schema._zod?.def?.type === 'optional'; } const v3Schema = schema; // v3 has isOptional() method if (typeof schema.isOptional === 'function') { return schema.isOptional(); } return v3Schema._def?.typeName === 'ZodOptional'; } /** * Gets the literal value from a schema, if it's a literal schema. * Works with both Zod v3 and v4. * Returns undefined if the schema is not a literal or the value cannot be determined. */ function getLiteralValue(schema) { if (isZ4Schema(schema)) { const v4Schema = schema; const def = v4Schema._zod?.def; if (def) { // Try various ways to get the literal value if (def.value !== undefined) return def.value; if (Array.isArray(def.values) && def.values.length > 0) { return def.values[0]; } } } const v3Schema = schema; const def = v3Schema._def; if (def) { if (def.value !== undefined) return def.value; if (Array.isArray(def.values) && def.values.length > 0) { return def.values[0]; } } // Fallback: check for direct value property (some Zod versions) const directValue = schema.value; if (directValue !== undefined) return directValue; return undefined; } //# sourceMappingURL=zod-compat.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js /** * Experimental task interfaces for MCP SDK. * WARNING: These APIs are experimental and may change without notice. */ /** * Checks if a task status represents a terminal state. * Terminal states are those where the task has finished and will not change. * * @param status - The task status to check * @returns True if the status is terminal (completed, failed, or cancelled) * @experimental */ function isTerminal(status) { return status === 'completed' || status === 'failed' || status === 'cancelled'; } //# sourceMappingURL=interfaces.js.map ;// ./node_modules/zod/v4/core/to-json-schema.js class JSONSchemaGenerator { constructor(params) { this.counter = 0; this.metadataRegistry = params?.metadata ?? globalRegistry; this.target = params?.target ?? "draft-2020-12"; this.unrepresentable = params?.unrepresentable ?? "throw"; this.override = params?.override ?? (() => { }); this.io = params?.io ?? "output"; this.seen = new Map(); } process(schema, _params = { path: [], schemaPath: [] }) { var _a; const def = schema._zod.def; const formatMap = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "", // do not set }; // check for schema in seens const seen = this.seen.get(schema); if (seen) { seen.count++; // check if cycle const isCycle = _params.schemaPath.includes(schema); if (isCycle) { seen.cycle = _params.path; } return seen.schema; } // initialize const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; this.seen.set(schema, result); // custom method overrides default behavior const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; } else { const params = { ..._params, schemaPath: [..._params.schemaPath, schema], path: _params.path, }; const parent = schema._zod.parent; if (parent) { // schema was cloned from another schema result.ref = parent; this.process(parent, params); this.seen.get(parent).isParent = true; } else { const _json = result.schema; switch (def.type) { case "string": { const json = _json; json.type = "string"; const { minimum, maximum, format, patterns, contentEncoding } = schema._zod .bag; if (typeof minimum === "number") json.minLength = minimum; if (typeof maximum === "number") json.maxLength = maximum; // custom pattern overrides format if (format) { json.format = formatMap[format] ?? format; if (json.format === "") delete json.format; // empty format is not valid } if (contentEncoding) json.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { const regexes = [...patterns]; if (regexes.length === 1) json.pattern = regexes[0].source; else if (regexes.length > 1) { result.schema.allOf = [ ...regexes.map((regex) => ({ ...(this.target === "draft-7" ? { type: "string" } : {}), pattern: regex.source, })), ]; } } break; } case "number": { const json = _json; const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; if (typeof format === "string" && format.includes("int")) json.type = "integer"; else json.type = "number"; if (typeof exclusiveMinimum === "number") json.exclusiveMinimum = exclusiveMinimum; if (typeof minimum === "number") { json.minimum = minimum; if (typeof exclusiveMinimum === "number") { if (exclusiveMinimum >= minimum) delete json.minimum; else delete json.exclusiveMinimum; } } if (typeof exclusiveMaximum === "number") json.exclusiveMaximum = exclusiveMaximum; if (typeof maximum === "number") { json.maximum = maximum; if (typeof exclusiveMaximum === "number") { if (exclusiveMaximum <= maximum) delete json.maximum; else delete json.exclusiveMaximum; } } if (typeof multipleOf === "number") json.multipleOf = multipleOf; break; } case "boolean": { const json = _json; json.type = "boolean"; break; } case "bigint": { if (this.unrepresentable === "throw") { throw new Error("BigInt cannot be represented in JSON Schema"); } break; } case "symbol": { if (this.unrepresentable === "throw") { throw new Error("Symbols cannot be represented in JSON Schema"); } break; } case "null": { _json.type = "null"; break; } case "any": { break; } case "unknown": { break; } case "undefined": { if (this.unrepresentable === "throw") { throw new Error("Undefined cannot be represented in JSON Schema"); } break; } case "void": { if (this.unrepresentable === "throw") { throw new Error("Void cannot be represented in JSON Schema"); } break; } case "never": { _json.not = {}; break; } case "date": { if (this.unrepresentable === "throw") { throw new Error("Date cannot be represented in JSON Schema"); } break; } case "array": { const json = _json; const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json.minItems = minimum; if (typeof maximum === "number") json.maxItems = maximum; json.type = "array"; json.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); break; } case "object": { const json = _json; json.type = "object"; json.properties = {}; const shape = def.shape; // params.shapeCache.get(schema)!; for (const key in shape) { json.properties[key] = this.process(shape[key], { ...params, path: [...params.path, "properties", key], }); } // required keys const allKeys = new Set(Object.keys(shape)); // const optionalKeys = new Set(def.optional); const requiredKeys = new Set([...allKeys].filter((key) => { const v = def.shape[key]._zod; if (this.io === "input") { return v.optin === undefined; } else { return v.optout === undefined; } })); if (requiredKeys.size > 0) { json.required = Array.from(requiredKeys); } // catchall if (def.catchall?._zod.def.type === "never") { // strict json.additionalProperties = false; } else if (!def.catchall) { // regular if (this.io === "output") json.additionalProperties = false; } else if (def.catchall) { json.additionalProperties = this.process(def.catchall, { ...params, path: [...params.path, "additionalProperties"], }); } break; } case "union": { const json = _json; json.anyOf = def.options.map((x, i) => this.process(x, { ...params, path: [...params.path, "anyOf", i], })); break; } case "intersection": { const json = _json; const a = this.process(def.left, { ...params, path: [...params.path, "allOf", 0], }); const b = this.process(def.right, { ...params, path: [...params.path, "allOf", 1], }); const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; const allOf = [ ...(isSimpleIntersection(a) ? a.allOf : [a]), ...(isSimpleIntersection(b) ? b.allOf : [b]), ]; json.allOf = allOf; break; } case "tuple": { const json = _json; json.type = "array"; const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); if (this.target === "draft-2020-12") { json.prefixItems = prefixItems; } else { json.items = prefixItems; } if (def.rest) { const rest = this.process(def.rest, { ...params, path: [...params.path, "items"], }); if (this.target === "draft-2020-12") { json.items = rest; } else { json.additionalItems = rest; } } // additionalItems if (def.rest) { json.items = this.process(def.rest, { ...params, path: [...params.path, "items"], }); } // length const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json.minItems = minimum; if (typeof maximum === "number") json.maxItems = maximum; break; } case "record": { const json = _json; json.type = "object"; json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); json.additionalProperties = this.process(def.valueType, { ...params, path: [...params.path, "additionalProperties"], }); break; } case "map": { if (this.unrepresentable === "throw") { throw new Error("Map cannot be represented in JSON Schema"); } break; } case "set": { if (this.unrepresentable === "throw") { throw new Error("Set cannot be represented in JSON Schema"); } break; } case "enum": { const json = _json; const values = getEnumValues(def.entries); // Number enums can have both string and number values if (values.every((v) => typeof v === "number")) json.type = "number"; if (values.every((v) => typeof v === "string")) json.type = "string"; json.enum = values; break; } case "literal": { const json = _json; const vals = []; for (const val of def.values) { if (val === undefined) { if (this.unrepresentable === "throw") { throw new Error("Literal `undefined` cannot be represented in JSON Schema"); } else { // do not add to vals } } else if (typeof val === "bigint") { if (this.unrepresentable === "throw") { throw new Error("BigInt literals cannot be represented in JSON Schema"); } else { vals.push(Number(val)); } } else { vals.push(val); } } if (vals.length === 0) { // do nothing (an undefined literal was stripped) } else if (vals.length === 1) { const val = vals[0]; json.type = val === null ? "null" : typeof val; json.const = val; } else { if (vals.every((v) => typeof v === "number")) json.type = "number"; if (vals.every((v) => typeof v === "string")) json.type = "string"; if (vals.every((v) => typeof v === "boolean")) json.type = "string"; if (vals.every((v) => v === null)) json.type = "null"; json.enum = vals; } break; } case "file": { const json = _json; const file = { type: "string", format: "binary", contentEncoding: "binary", }; const { minimum, maximum, mime } = schema._zod.bag; if (minimum !== undefined) file.minLength = minimum; if (maximum !== undefined) file.maxLength = maximum; if (mime) { if (mime.length === 1) { file.contentMediaType = mime[0]; Object.assign(json, file); } else { json.anyOf = mime.map((m) => { const mFile = { ...file, contentMediaType: m }; return mFile; }); } } else { Object.assign(json, file); } // if (this.unrepresentable === "throw") { // throw new Error("File cannot be represented in JSON Schema"); // } break; } case "transform": { if (this.unrepresentable === "throw") { throw new Error("Transforms cannot be represented in JSON Schema"); } break; } case "nullable": { const inner = this.process(def.innerType, params); _json.anyOf = [inner, { type: "null" }]; break; } case "nonoptional": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "success": { const json = _json; json.type = "boolean"; break; } case "default": { this.process(def.innerType, params); result.ref = def.innerType; _json.default = JSON.parse(JSON.stringify(def.defaultValue)); break; } case "prefault": { this.process(def.innerType, params); result.ref = def.innerType; if (this.io === "input") _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); break; } case "catch": { // use conditionals this.process(def.innerType, params); result.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(undefined); } catch { throw new Error("Dynamic catch values are not supported in JSON Schema"); } _json.default = catchValue; break; } case "nan": { if (this.unrepresentable === "throw") { throw new Error("NaN cannot be represented in JSON Schema"); } break; } case "template_literal": { const json = _json; const pattern = schema._zod.pattern; if (!pattern) throw new Error("Pattern not found in template literal"); json.type = "string"; json.pattern = pattern.source; break; } case "pipe": { const innerType = this.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out; this.process(innerType, params); result.ref = innerType; break; } case "readonly": { this.process(def.innerType, params); result.ref = def.innerType; _json.readOnly = true; break; } // passthrough types case "promise": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "optional": { this.process(def.innerType, params); result.ref = def.innerType; break; } case "lazy": { const innerType = schema._zod.innerType; this.process(innerType, params); result.ref = innerType; break; } case "custom": { if (this.unrepresentable === "throw") { throw new Error("Custom types cannot be represented in JSON Schema"); } break; } default: { def; } } } } // metadata const meta = this.metadataRegistry.get(schema); if (meta) Object.assign(result.schema, meta); if (this.io === "input" && isTransforming(schema)) { // examples/defaults only apply to output type of pipe delete result.schema.examples; delete result.schema.default; } // set prefault as default if (this.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault); delete result.schema._prefault; // pulling fresh from this.seen in case it was overwritten const _result = this.seen.get(schema); return _result.schema; } emit(schema, _params) { const params = { cycles: _params?.cycles ?? "ref", reused: _params?.reused ?? "inline", // unrepresentable: _params?.unrepresentable ?? "throw", // uri: _params?.uri ?? ((id) => `${id}`), external: _params?.external ?? undefined, }; // iterate over seen map; const root = this.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); // initialize result with root schema fields // Object.assign(result, seen.cached); // returns a ref to the schema // defId will be empty if the ref points to an external schema (or #) const makeURI = (entry) => { // comparing the seen objects because sometimes // multiple schemas map to the same seen object. // e.g. lazy // external is configured const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; if (params.external) { const externalId = params.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${this.counter++}`; // check if schema is in the external registry const uriGenerator = params.external.uri ?? ((id) => id); if (externalId) { return { ref: uriGenerator(externalId) }; } // otherwise, add to __shared const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; entry[1].defId = id; // set defId so it will be reused if needed return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } if (entry[1] === root) { return { ref: "#" }; } // self-contained schema const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; const defId = entry[1].schema.id ?? `__schema${this.counter++}`; return { defId, ref: defUriPrefix + defId }; }; // stored cached version in `def` property // remove all properties, set $ref const extractToDef = (entry) => { // if the schema is already a reference, do not extract it if (entry[1].schema.$ref) { return; } const seen = entry[1]; const { ref, defId } = makeURI(entry); seen.def = { ...seen.schema }; // defId won't be set if the schema is a reference to an external schema if (defId) seen.defId = defId; // wipe away all properties except $ref const schema = seen.schema; for (const key in schema) { delete schema[key]; } schema.$ref = ref; }; // throw on cycles // break cycles if (params.cycles === "throw") { for (const entry of this.seen.entries()) { const seen = entry[1]; if (seen.cycle) { throw new Error("Cycle detected: " + `#/${seen.cycle?.join("/")}/<root>` + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); } } } // extract schemas into $defs for (const entry of this.seen.entries()) { const seen = entry[1]; // convert root schema to # $ref if (schema === entry[0]) { extractToDef(entry); // this has special handling for the root schema continue; } // extract schemas that are in the external registry if (params.external) { const ext = params.external.registry.get(entry[0])?.id; if (schema !== entry[0] && ext) { extractToDef(entry); continue; } } // extract schemas with `id` meta const id = this.metadataRegistry.get(entry[0])?.id; if (id) { extractToDef(entry); continue; } // break cycles if (seen.cycle) { // any extractToDef(entry); continue; } // extract reused schemas if (seen.count > 1) { if (params.reused === "ref") { extractToDef(entry); // biome-ignore lint: continue; } } } // flatten _refs const flattenRef = (zodSchema, params) => { const seen = this.seen.get(zodSchema); const schema = seen.def ?? seen.schema; const _cached = { ...schema }; // already seen if (seen.ref === null) { return; } // flatten ref if defined const ref = seen.ref; seen.ref = null; // prevent recursion if (ref) { flattenRef(ref, params); // merge referenced schema into current const refSchema = this.seen.get(ref).schema; if (refSchema.$ref && params.target === "draft-7") { schema.allOf = schema.allOf ?? []; schema.allOf.push(refSchema); } else { Object.assign(schema, refSchema); Object.assign(schema, _cached); // prevent overwriting any fields in the original schema } } // execute overrides if (!seen.isParent) this.override({ zodSchema: zodSchema, jsonSchema: schema, path: seen.path ?? [], }); }; for (const entry of [...this.seen.entries()].reverse()) { flattenRef(entry[0], { target: this.target }); } const result = {}; if (this.target === "draft-2020-12") { result.$schema = "https://json-schema.org/draft/2020-12/schema"; } else if (this.target === "draft-7") { result.$schema = "http://json-schema.org/draft-07/schema#"; } else { console.warn(`Invalid target: ${this.target}`); } if (params.external?.uri) { const id = params.external.registry.get(schema)?.id; if (!id) throw new Error("Schema is missing an `id` property"); result.$id = params.external.uri(id); } Object.assign(result, root.def); // build defs object const defs = params.external?.defs ?? {}; for (const entry of this.seen.entries()) { const seen = entry[1]; if (seen.def && seen.defId) { defs[seen.defId] = seen.def; } } // set definitions in result if (params.external) { } else { if (Object.keys(defs).length > 0) { if (this.target === "draft-2020-12") { result.$defs = defs; } else { result.definitions = defs; } } } try { // this "finalizes" this schema and ensures all cycles are removed // each call to .emit() is functionally independent // though the seen map is shared return JSON.parse(JSON.stringify(result)); } catch (_err) { throw new Error("Error converting schema to JSON."); } } } function toJSONSchema(input, _params) { if (input instanceof $ZodRegistry) { const gen = new JSONSchemaGenerator(_params); const defs = {}; for (const entry of input._idmap.entries()) { const [_, schema] = entry; gen.process(schema); } const schemas = {}; const external = { registry: input, uri: _params?.uri, defs, }; for (const entry of input._idmap.entries()) { const [key, schema] = entry; schemas[key] = gen.emit(schema, { ..._params, external, }); } if (Object.keys(defs).length > 0) { const defsSegment = gen.target === "draft-2020-12" ? "$defs" : "definitions"; schemas.__shared = { [defsSegment]: defs, }; } return { schemas }; } const gen = new JSONSchemaGenerator(_params); gen.process(input); return gen.emit(input, _params); } function isTransforming(_schema, _ctx) { const ctx = _ctx ?? { seen: new Set() }; if (ctx.seen.has(_schema)) return false; ctx.seen.add(_schema); const schema = _schema; const def = schema._zod.def; switch (def.type) { case "string": case "number": case "bigint": case "boolean": case "date": case "symbol": case "undefined": case "null": case "any": case "unknown": case "never": case "void": case "literal": case "enum": case "nan": case "file": case "template_literal": return false; case "array": { return isTransforming(def.element, ctx); } case "object": { for (const key in def.shape) { if (isTransforming(def.shape[key], ctx)) return true; } return false; } case "union": { for (const option of def.options) { if (isTransforming(option, ctx)) return true; } return false; } case "intersection": { return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); } case "tuple": { for (const item of def.items) { if (isTransforming(item, ctx)) return true; } if (def.rest && isTransforming(def.rest, ctx)) return true; return false; } case "record": { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } case "map": { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } case "set": { return isTransforming(def.valueType, ctx); } // inner types case "promise": case "optional": case "nonoptional": case "nullable": case "readonly": return isTransforming(def.innerType, ctx); case "lazy": return isTransforming(def.getter(), ctx); case "default": { return isTransforming(def.innerType, ctx); } case "prefault": { return isTransforming(def.innerType, ctx); } case "custom": { return false; } case "transform": { return true; } case "pipe": { return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); } case "success": { return false; } case "catch": { return false; } default: def; } throw new Error(`Unknown schema type: ${def.type}`); } ;// ./node_modules/zod-to-json-schema/dist/esm/Options.js const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); const jsonDescription = (jsonSchema, def) => { if (def.description) { try { return { ...jsonSchema, ...JSON.parse(def.description), }; } catch { } } return jsonSchema; }; const defaultOptions = { name: undefined, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", target: "jsonSchema7", strictUnions: false, definitions: {}, errorMessages: false, markdownDescription: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref", openAiAnyTypeName: "OpenAiAnyType" }; const getDefaultOptions = (options) => (typeof options === "string" ? { ...defaultOptions, name: options, } : { ...defaultOptions, ...options, }); ;// ./node_modules/zod-to-json-schema/dist/esm/Refs.js const getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, flags: { hasReferencedOpenAiAnyType: false }, currentPath: currentPath, propertyPath: undefined, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: undefined, }, ])), }; }; ;// ./node_modules/zod-to-json-schema/dist/esm/getRelativePath.js const getRelativePath = (pathA, pathB) => { let i = 0; for (; i < pathA.length && i < pathB.length; i++) { if (pathA[i] !== pathB[i]) break; } return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); }; ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/any.js function parseAnyDef(refs) { if (refs.target !== "openAi") { return {}; } const anyDefinitionPath = [ ...refs.basePath, refs.definitionPath, refs.openAiAnyTypeName, ]; refs.flags.hasReferencedOpenAiAnyType = true; return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/"), }; } ;// ./node_modules/zod-to-json-schema/dist/esm/errorMessages.js function addErrorMessage(res, key, errorMessage, refs) { if (!refs?.errorMessages) return; if (errorMessage) { res.errorMessage = { ...res.errorMessage, [key]: errorMessage, }; } } function setResponseValueAndErrors(res, key, value, errorMessage, refs) { res[key] = value; addErrorMessage(res, key, errorMessage, refs); } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/array.js function parseArrayDef(def, refs) { const res = { type: "array", }; if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"], }); } if (def.minLength) { setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); } if (def.maxLength) { setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); } if (def.exactLength) { setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); } return res; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js function parseBigintDef(def, refs) { const res = { type: "integer", format: "int64", }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "min": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); break; } } return res; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js function parseBooleanDef() { return { type: "boolean", }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js const parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/date.js function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy ?? refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time", }; case "format:date": return { type: "string", format: "date", }; case "integer": return integerDateParser(def, refs); } } const integerDateParser = (def, refs) => { const res = { type: "integer", format: "unix-time", }; if (refs.target === "openApi3") { return res; } for (const check of def.checks) { switch (check.kind) { case "min": setResponseValueAndErrors(res, "minimum", check.value, // This is in milliseconds check.message, refs); break; case "max": setResponseValueAndErrors(res, "maximum", check.value, // This is in milliseconds check.message, refs); break; } } return res; }; ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/default.js function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue(), }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values), }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js const isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef(def, refs) { const allOf = [ parseDef(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"], }), parseDef(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"], }), ].filter((x) => !!x); let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : undefined; const mergedAllOf = []; // If either of the schemas is an allOf, merge them into a single allOf allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); if (schema.unevaluatedProperties === undefined) { // If one of the schemas has no unevaluatedProperties set, // the merged schema should also have no unevaluatedProperties set unevaluatedProperties = undefined; } } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } else { // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties unevaluatedProperties = undefined; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf, ...unevaluatedProperties, } : undefined; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js function parseLiteralDef(def, refs) { const parsedType = typeof def.value; if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { return { type: Array.isArray(def.value) ? "array" : "object", }; } if (refs.target === "openApi3") { return { type: parsedType === "bigint" ? "integer" : parsedType, enum: [def.value], }; } return { type: parsedType === "bigint" ? "integer" : parsedType, const: def.value, }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/string.js let string_emojiRegex = undefined; /** * Generated from the regular expressions found here as of 2024-05-22: * https://github.com/colinhacks/zod/blob/master/src/types.ts. * * Expressions with /i flag have been changed accordingly. */ const zodPatterns = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (string_emojiRegex === undefined) { string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); } return string_emojiRegex; }, /** * Unused */ 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}$/, /** * Unused */ 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])$/, 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])$/, /** * Unused */ 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})))$/, 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])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/, }; function parseStringDef(def, refs) { const res = { type: "string", }; if (def.checks) { for (const check of def.checks) { switch (check.kind) { case "min": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); break; case "max": setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check.message, refs); break; } break; case "url": addFormat(res, "uri", check.message, refs); break; case "uuid": addFormat(res, "uuid", check.message, refs); break; case "regex": addPattern(res, check.regex, check.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check.message, refs); break; case "startsWith": addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); break; case "endsWith": addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); break; case "datetime": addFormat(res, "date-time", check.message, refs); break; case "date": addFormat(res, "date", check.message, refs); break; case "time": addFormat(res, "time", check.message, refs); break; case "duration": addFormat(res, "duration", check.message, refs); break; case "length": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); break; case "includes": { addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); break; } case "ip": { if (check.version !== "v6") { addFormat(res, "ipv4", check.message, refs); } if (check.version !== "v4") { addFormat(res, "ipv6", check.message, refs); } break; } case "base64url": addPattern(res, zodPatterns.base64url, check.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check.message, refs); break; case "cidr": { if (check.version !== "v6") { addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); } if (check.version !== "v4") { addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji(), check.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check.message, refs); break; } case "contentEncoding:base64": { setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check.message, refs); } case "toLowerCase": case "toUpperCase": case "trim": break; default: ((_) => { })(check); } } } return res; } function escapeLiteralCheckValue(literal, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; } const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); function escapeNonAlphaNumeric(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC.has(source[i])) { result += "\\"; } result += source[i]; } return result; } // Adds a "format" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones. function addFormat(schema, value, message, refs) { if (schema.format || schema.anyOf?.some((x) => x.format)) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format, ...(schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format }, }), }); delete schema.format; if (schema.errorMessage) { delete schema.errorMessage.format; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.anyOf.push({ format: value, ...(message && refs.errorMessages && { errorMessage: { format: message } }), }); } else { setResponseValueAndErrors(schema, "format", value, message, refs); } } // Adds a "pattern" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones. function addPattern(schema, regex, message, refs) { if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern, ...(schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern }, }), }); delete schema.pattern; if (schema.errorMessage) { delete schema.errorMessage.pattern; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.allOf.push({ pattern: stringifyRegExpWithFlags(regex, refs), ...(message && refs.errorMessages && { errorMessage: { pattern: message } }), }); } else { setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); } } // Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true function stringifyRegExpWithFlags(regex, refs) { if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } // Currently handled flags const flags = { i: regex.flags.includes("i"), m: regex.flags.includes("m"), s: regex.flags.includes("s"), // `.` matches newlines }; // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0; i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r\n]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r\n]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } try { new RegExp(pattern); } catch { console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); return regex.source; } return pattern; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/record.js function parseRecordDef(def, refs) { if (refs.target === "openAi") { console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); } if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { return { type: "object", required: def.keyType._def.values, properties: def.keyType._def.values.reduce((acc, key) => ({ ...acc, [key]: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "properties", key], }) ?? parseAnyDef(refs), }), {}), additionalProperties: refs.rejectedAdditionalProperties, }; } const schema = { type: "object", additionalProperties: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"], }) ?? refs.allowedAdditionalProperties, }; if (refs.target === "openApi3") { return schema; } if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { const { type, ...keyType } = parseStringDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType, }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values, }, }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType, }; } return schema; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/map.js function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); } const keys = parseDef(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"], }) || parseAnyDef(refs); const values = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"], }) || parseAnyDef(refs); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2, }, }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js function parseNativeEnumDef(def) { const object = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object[object[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object[key]); const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues, }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/never.js function parseNeverDef(refs) { return refs.target === "openAi" ? undefined : { not: parseAnyDef({ ...refs, currentPath: [...refs.currentPath, "not"], }), }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/null.js function parseNullDef(refs) { return refs.target === "openApi3" ? { enum: ["null"], nullable: true, } : { type: "null", }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/union.js const primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null", }; function parseUnionDef(def, refs) { if (refs.target === "openApi3") return asAnyOf(def, refs); const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { // all types in union are primitive and lack checks, so might as well squash into {type: [...]} const types = options.reduce((types, x) => { const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 return type && !types.includes(type) ? [...types, type] : types; }, []); return { type: types.length > 1 ? types : types[0], }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { // all options literals const types = options.reduce((acc, x) => { const type = typeof x._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, []); if (types.length === options.length) { // all the literals are primitive, as far as null can be considered primitive const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce((acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, []), }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce((acc, x) => [ ...acc, ...x._def.values.filter((x) => !acc.includes(x)), ], []), }; } return asAnyOf(def, refs); } const asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options) .map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i}`], })) .filter((x) => !!x && (!refs.strictUnions || (typeof x === "object" && Object.keys(x).length > 0))); return anyOf.length ? { anyOf } : undefined; }; ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js function parseNullableDef(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { if (refs.target === "openApi3") { return { type: primitiveMappings[def.innerType._def.typeName], nullable: true, }; } return { type: [ primitiveMappings[def.innerType._def.typeName], "null", ], }; } if (refs.target === "openApi3") { const base = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath], }); if (base && "$ref" in base) return { allOf: [base], nullable: true }; return base && { ...base, nullable: true }; } const base = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"], }); return base && { anyOf: [base, { type: "null" }] }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/number.js function parseNumberDef(def, refs) { const res = { type: "number", }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "int": res.type = "integer"; addErrorMessage(res, "type", check.message, refs); break; case "min": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check.inclusive) { setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); break; } } return res; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/object.js function parseObjectDef(def, refs) { const forceOptionalIntoNullable = refs.target === "openAi"; const result = { type: "object", properties: {}, }; const required = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === undefined || propDef._def === undefined) { continue; } let propOptional = safeIsOptional(propDef); if (propOptional && forceOptionalIntoNullable) { if (propDef._def.typeName === "ZodOptional") { propDef = propDef._def.innerType; } if (!propDef.isNullable()) { propDef = propDef.nullable(); } propOptional = false; } const parsedDef = parseDef(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName], }); if (parsedDef === undefined) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required.push(propName); } } if (required.length) { result.required = required; } const additionalProperties = decideAdditionalProperties(def, refs); if (additionalProperties !== undefined) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"], }); } switch (def.unknownKeys) { case "passthrough": return refs.allowedAdditionalProperties; case "strict": return refs.rejectedAdditionalProperties; case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } } function safeIsOptional(schema) { try { return schema.isOptional(); } catch { return true; } } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js const parseOptionalDef = (def, refs) => { if (refs.currentPath.toString() === refs.propertyPath?.toString()) { return parseDef(def.innerType._def, refs); } const innerSchema = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"], }); return innerSchema ? { anyOf: [ { not: parseAnyDef(refs), }, innerSchema, ], } : parseAnyDef(refs); }; ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js const parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef(def.out._def, refs); } const a = parseDef(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"], }); const b = parseDef(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"], }); return { allOf: [a, b].filter((x) => x !== undefined), }; }; ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/set.js function parseSetDef(def, refs) { const items = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"], }); const schema = { type: "array", uniqueItems: true, items, }; if (def.minSize) { setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); } if (def.maxSize) { setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); } return schema; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js function parseTupleDef(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items .map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`], })) .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), additionalItems: parseDef(def.rest._def, { ...refs, currentPath: [...refs.currentPath, "additionalItems"], }), }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items .map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`], })) .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), }; } } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js function parseUndefinedDef(refs) { return { not: parseAnyDef(refs), }; } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js function parseUnknownDef(refs) { return parseAnyDef(refs); } ;// ./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js const parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; ;// ./node_modules/zod-to-json-schema/dist/esm/selectParser.js const selectParser = (def, typeName, refs) => { switch (typeName) { case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs); case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs); case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs); case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); case ZodFirstPartyTypeKind.ZodUnion: case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); case ZodFirstPartyTypeKind.ZodNaN: case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs); case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs); case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs); case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); case ZodFirstPartyTypeKind.ZodFunction: case ZodFirstPartyTypeKind.ZodVoid: case ZodFirstPartyTypeKind.ZodSymbol: return undefined; default: return ((_) => undefined)(typeName); } }; ;// ./node_modules/zod-to-json-schema/dist/esm/parseDef.js function parseDef(def, refs, forceResolution = false) { const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); if (overrideResult !== ignoreOverride) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref(seenItem, refs); if (seenSchema !== undefined) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive) const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema) { addMeta(def, refs, jsonSchema); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema, def, refs); newItem.jsonSchema = jsonSchema; return postProcessResult; } newItem.jsonSchema = jsonSchema; return jsonSchema; } const get$ref = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; case "none": case "seen": { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); return parseAnyDef(refs); } return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined; } } }; const addMeta = (def, refs, jsonSchema) => { if (def.description) { jsonSchema.description = def.description; if (refs.markdownDescription) { jsonSchema.markdownDescription = def.description; } } return jsonSchema; }; ;// ./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js const zodToJsonSchema = (schema, options) => { const refs = getRefs(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ ...acc, [name]: parseDef(schema._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name], }, true) ?? parseAnyDef(refs), }), {}) : undefined; const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name; const main = parseDef(schema._def, name === undefined ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name], }, false) ?? parseAnyDef(refs); const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined; if (title !== undefined) { main.title = title; } if (refs.flags.hasReferencedOpenAiAnyType) { if (!definitions) { definitions = {}; } if (!definitions[refs.openAiAnyTypeName]) { definitions[refs.openAiAnyTypeName] = { // Skipping "object" as no properties can be defined and additionalProperties must be "false" type: ["string", "number", "integer", "boolean", "array", "null"], items: { $ref: refs.$refStrategy === "relative" ? "1" : [ ...refs.basePath, refs.definitionPath, refs.openAiAnyTypeName, ].join("/"), }, }; } } const combined = name === undefined ? definitions ? { ...main, [refs.definitionPath]: definitions, } : main : { $ref: [ ...(refs.$refStrategy === "relative" ? [] : refs.basePath), refs.definitionPath, name, ].join("/"), [refs.definitionPath]: { ...definitions, [name]: main, }, }; if (refs.target === "jsonSchema7") { combined.$schema = "http://json-schema.org/draft-07/schema#"; } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; } if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || ("type" in combined && Array.isArray(combined.type)))) { console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); } return combined; }; ;// ./node_modules/zod-to-json-schema/dist/esm/index.js /* unused harmony import specifier */ var esm_zodToJsonSchema; /* harmony default export */ const esm = ((/* unused pure expression or super */ null && (esm_zodToJsonSchema))); ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js // zod-json-schema-compat.ts // ---------------------------------------------------- // JSON Schema conversion for both Zod v3 and Zod v4 (Mini) // v3 uses your vendored converter; v4 uses Mini's toJSONSchema // ---------------------------------------------------- function mapMiniTarget(t) { if (!t) return 'draft-7'; if (t === 'jsonSchema7' || t === 'draft-7') return 'draft-7'; if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') return 'draft-2020-12'; return 'draft-7'; // fallback } function toJsonSchemaCompat(schema, opts) { if (isZ4Schema(schema)) { // v4 branch — use Mini's built-in toJSONSchema return toJSONSchema(schema, { target: mapMiniTarget(opts?.target), io: opts?.pipeStrategy ?? 'input' }); } // v3 branch — use vendored converter return zodToJsonSchema(schema, { strictUnions: opts?.strictUnions ?? true, pipeStrategy: opts?.pipeStrategy ?? 'input' }); } function getMethodLiteral(schema) { const shape = getObjectShape(schema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error('Schema is missing a method literal'); } const value = getLiteralValue(methodSchema); if (typeof value !== 'string') { throw new Error('Schema method literal must be a string'); } return value; } function parseWithCompat(schema, data) { const result = zod_compat_safeParse(schema, data); if (!result.success) { throw result.error; } return result.data; } //# sourceMappingURL=zod-json-schema-compat.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js /** * The default request timeout, in miliseconds. */ const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; /** * Implements MCP protocol framing on top of a pluggable transport, including * features like request/response linking, notifications, and progress. */ class Protocol { constructor(_options) { this._options = _options; this._requestMessageId = 0; this._requestHandlers = new Map(); this._requestHandlerAbortControllers = new Map(); this._notificationHandlers = new Map(); this._responseHandlers = new Map(); this._progressHandlers = new Map(); this._timeoutInfo = new Map(); this._pendingDebouncedNotifications = new Set(); // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult this._taskProgressTokens = new Map(); this._requestResolvers = new Map(); this.setNotificationHandler(CancelledNotificationSchema, notification => { this._oncancel(notification); }); this.setNotificationHandler(ProgressNotificationSchema, notification => { this._onprogress(notification); }); this.setRequestHandler(PingRequestSchema, // Automatic pong by default. _request => ({})); // Install task handlers if TaskStore is provided this._taskStore = _options?.taskStore; this._taskMessageQueue = _options?.taskMessageQueue; if (this._taskStore) { this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); } // Per spec: tasks/get responses SHALL NOT include related-task metadata // as the taskId parameter is the source of truth // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else return { ...task }; }); this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { const handleTaskResult = async () => { const taskId = request.params.taskId; // Look the task up for this session first; queued messages are only delivered for a task it can see. if (!(await this._taskStore.getTask(taskId, extra.sessionId))) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); } // Deliver queued messages if (this._taskMessageQueue) { let queuedMessage; while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) { // Handle response and error messages by routing them to the appropriate resolver if (queuedMessage.type === 'response' || queuedMessage.type === 'error') { const message = queuedMessage.message; const requestId = message.id; // Lookup resolver in _requestResolvers map const resolver = this._requestResolvers.get(requestId); if (resolver) { // Remove resolver from map after invocation this._requestResolvers.delete(requestId); // Invoke resolver with response or error if (queuedMessage.type === 'response') { resolver(message); } else { // Convert JSONRPCError to McpError const errorMessage = message; const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); resolver(error); } } else { // Handle missing resolver gracefully with error logging const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error'; this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); } // Continue to next message continue; } // Send the message on the response stream by passing the relatedRequestId // This tells the transport to write the message to the tasks/result response stream await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); } } // Now check task status const task = await this._taskStore.getTask(taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); } // Block if task is not terminal (we've already delivered all queued messages above) if (!isTerminal(task.status)) { // Wait for status change or new messages await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId); // After waking up, recursively call to deliver any new messages or result return await handleTaskResult(); } // If task is terminal, return the result if (isTerminal(task.status)) { const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); this._clearTaskQueue(taskId, extra.sessionId); return { ...result, _meta: { ...result._meta, [RELATED_TASK_META_KEY]: { taskId: taskId } } }; } return await handleTaskResult(); }; return await handleTaskResult(); }); this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { try { const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else return { tasks, nextCursor, _meta: {} }; } catch (error) { throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`); } }); this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { try { // Get the current task to check if it's in a terminal state, in case the implementation is not atomic const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); } // Reject cancellation of terminal tasks if (isTerminal(task.status)) { throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); } await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId); this._clearTaskQueue(request.params.taskId, extra.sessionId); const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!cancelledTask) { // Task was deleted during cancellation (e.g., cleanup happened) throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); } return { _meta: {}, ...cancelledTask }; } catch (error) { // Re-throw McpError as-is if (error instanceof McpError) { throw error; } throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`); } }); } } async _oncancel(notification) { if (!notification.params.requestId) { return; } // Handle request cancellation const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); controller?.abort(notification.params.reason); } _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { this._timeoutInfo.set(messageId, { timeoutId: setTimeout(onTimeout, timeout), startTime: Date.now(), timeout, maxTotalTimeout, resetTimeoutOnProgress, onTimeout }); } _resetTimeout(messageId) { const info = this._timeoutInfo.get(messageId); if (!info) return false; const totalElapsed = Date.now() - info.startTime; if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { this._timeoutInfo.delete(messageId); throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { maxTotalTimeout: info.maxTotalTimeout, totalElapsed }); } clearTimeout(info.timeoutId); info.timeoutId = setTimeout(info.onTimeout, info.timeout); return true; } _cleanupTimeout(messageId) { const info = this._timeoutInfo.get(messageId); if (info) { clearTimeout(info.timeoutId); this._timeoutInfo.delete(messageId); } } /** * Attaches to the given transport, starts it, and starts listening for messages. * * The 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. */ async connect(transport) { if (this._transport) { throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.'); } this._transport = transport; const _onclose = this.transport?.onclose; this._transport.onclose = () => { _onclose?.(); this._onclose(); }; const _onerror = this.transport?.onerror; this._transport.onerror = (error) => { _onerror?.(error); this._onerror(error); }; const _onmessage = this._transport?.onmessage; this._transport.onmessage = (message, extra) => { _onmessage?.(message, extra); if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { this._onresponse(message); } else if (isJSONRPCRequest(message)) { this._onrequest(message, extra); } else if (isJSONRPCNotification(message)) { this._onnotification(message); } else { this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); } }; await this._transport.start(); } _onclose() { const responseHandlers = this._responseHandlers; this._responseHandlers = new Map(); this._progressHandlers.clear(); this._taskProgressTokens.clear(); this._pendingDebouncedNotifications.clear(); for (const info of this._timeoutInfo.values()) { clearTimeout(info.timeoutId); } this._timeoutInfo.clear(); // Abort all in-flight request handlers so they stop sending messages for (const controller of this._requestHandlerAbortControllers.values()) { controller.abort(); } this._requestHandlerAbortControllers.clear(); const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'); this._transport = undefined; this.onclose?.(); for (const handler of responseHandlers.values()) { handler(error); } } _onerror(error) { this.onerror?.(error); } _onnotification(notification) { const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; // Ignore notifications not being subscribed to. if (handler === undefined) { return; } // Starting with Promise.resolve() puts any synchronous errors into the monad as well. Promise.resolve() .then(() => handler(notification)) .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); } _onrequest(request, extra) { const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; // Capture the current transport at request time to ensure responses go to the correct client const capturedTransport = this._transport; // Extract taskId from request metadata if present (needed early for method not found case) const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; // With a session, the related task is looked up for that session first; replies are queued for it only if it is found. const sessionId = capturedTransport?.sessionId; const store = this._taskStore; let relatedTaskFound = true; let relatedTaskLookup; if (relatedTaskId && store && this._taskMessageQueue && sessionId !== undefined) { relatedTaskFound = false; relatedTaskLookup = (async () => { if (!(await store.getTask(relatedTaskId, sessionId))) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`); } relatedTaskFound = true; })(); } if (handler === undefined) { const errorResponse = { jsonrpc: '2.0', id: request.id, error: { code: ErrorCode.MethodNotFound, message: 'Method not found' } }; // Queue or send the error response based on whether this is a task-related request if (relatedTaskId && relatedTaskLookup) { const queuedError = { type: 'error', message: errorResponse, timestamp: Date.now() }; relatedTaskLookup .then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)) .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); } else if (relatedTaskId && this._taskMessageQueue) { this._enqueueTaskMessage(relatedTaskId, { type: 'error', message: errorResponse, timestamp: Date.now() }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`))); } else { capturedTransport ?.send(errorResponse) .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); } return; } const abortController = new AbortController(); this._requestHandlerAbortControllers.set(request.id, abortController); const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined; const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined; const fullExtra = { signal: abortController.signal, sessionId: capturedTransport?.sessionId, _meta: request.params?._meta, sendNotification: async (notification) => { if (abortController.signal.aborted) return; // Include related-task metadata if this request is part of a task const notificationOptions = { relatedRequestId: request.id }; if (relatedTaskId) { notificationOptions.relatedTask = { taskId: relatedTaskId }; } await this.notification(notification, notificationOptions); }, sendRequest: async (r, resultSchema, options) => { if (abortController.signal.aborted) { throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled'); } // Include related-task metadata if this request is part of a task const requestOptions = { ...options, relatedRequestId: request.id }; if (relatedTaskId && !requestOptions.relatedTask) { requestOptions.relatedTask = { taskId: relatedTaskId }; } // Set task status to input_required when sending a request within a task context // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited) const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; if (effectiveTaskId && taskStore) { await taskStore.updateTaskStatus(effectiveTaskId, 'input_required'); } return await this.request(r, resultSchema, requestOptions); }, authInfo: extra?.authInfo, requestId: request.id, requestInfo: extra?.requestInfo, taskId: relatedTaskId, taskStore: taskStore, taskRequestedTtl: taskCreationParams?.ttl, closeSSEStream: extra?.closeSSEStream, closeStandaloneSSEStream: extra?.closeStandaloneSSEStream }; // Starting with Promise.resolve() puts any synchronous errors into the monad as well. (relatedTaskLookup ?? Promise.resolve()) .then(() => { // A request cancelled while its related task was looked up does not start its handler; nothing is replied. if (relatedTaskLookup && abortController.signal.aborted) { throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled'); } // If this request asked for task creation, check capability first if (taskCreationParams) { // Check if the request method supports task creation this.assertTaskHandlerCapability(request.method); } }) .then(() => handler(request, fullExtra)) .then(async (result) => { if (abortController.signal.aborted) { // Request was cancelled return; } const response = { result, jsonrpc: '2.0', id: request.id }; // Queue or send the response based on whether this is a task-related request if (relatedTaskId && this._taskMessageQueue) { await this._enqueueTaskMessage(relatedTaskId, { type: 'response', message: response, timestamp: Date.now() }, capturedTransport?.sessionId); } else { await capturedTransport?.send(response); } }, async (error) => { if (abortController.signal.aborted) { // Request was cancelled return; } const errorResponse = { jsonrpc: '2.0', id: request.id, error: { code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, message: error.message ?? 'Internal error', ...(error['data'] !== undefined && { data: error['data'] }) } }; // Queue or send the error response based on whether this is a task-related request if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) { await this._enqueueTaskMessage(relatedTaskId, { type: 'error', message: errorResponse, timestamp: Date.now() }, capturedTransport?.sessionId); } else { await capturedTransport?.send(errorResponse); } }) .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) .finally(() => { // Only delete if the stored controller is still ours; after close()+connect(), // a new connection may have reused the same request ID with a different controller. if (this._requestHandlerAbortControllers.get(request.id) === abortController) { this._requestHandlerAbortControllers.delete(request.id); } }); } _onprogress(notification) { const { progressToken, ...params } = notification.params; const messageId = Number(progressToken); const handler = this._progressHandlers.get(messageId); if (!handler) { this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); return; } const responseHandler = this._responseHandlers.get(messageId); const timeoutInfo = this._timeoutInfo.get(messageId); if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { try { this._resetTimeout(messageId); } catch (error) { // Clean up if maxTotalTimeout was exceeded this._responseHandlers.delete(messageId); this._progressHandlers.delete(messageId); this._cleanupTimeout(messageId); responseHandler(error); return; } } handler(params); } _onresponse(response) { const messageId = Number(response.id); // Check if this is a response to a queued request const resolver = this._requestResolvers.get(messageId); if (resolver) { this._requestResolvers.delete(messageId); if (isJSONRPCResultResponse(response)) { resolver(response); } else { const error = new McpError(response.error.code, response.error.message, response.error.data); resolver(error); } return; } const handler = this._responseHandlers.get(messageId); if (handler === undefined) { this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); return; } this._responseHandlers.delete(messageId); this._cleanupTimeout(messageId); // Keep progress handler alive for CreateTaskResult responses let isTaskResponse = false; if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') { const result = response.result; if (result.task && typeof result.task === 'object') { const task = result.task; if (typeof task.taskId === 'string') { isTaskResponse = true; this._taskProgressTokens.set(task.taskId, messageId); } } } if (!isTaskResponse) { this._progressHandlers.delete(messageId); } if (isJSONRPCResultResponse(response)) { handler(response); } else { const error = McpError.fromError(response.error.code, response.error.message, response.error.data); handler(error); } } get transport() { return this._transport; } /** * Closes the connection. */ async close() { await this._transport?.close(); } /** * Sends a request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * @example * ```typescript * const stream = protocol.requestStream(request, resultSchema, options); * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('Final result:', message.result); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @experimental Use `client.experimental.tasks.requestStream()` to access this method. */ async *requestStream(request, resultSchema, options) { const { task } = options ?? {}; // For non-task requests, just yield the result if (!task) { try { const result = await this.request(request, resultSchema, options); yield { type: 'result', result }; } catch (error) { yield { type: 'error', error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) }; } return; } // For task-augmented requests, we need to poll for status // First, make the request to create the task let taskId; try { // Send the request and get the CreateTaskResult const createResult = await this.request(request, CreateTaskResultSchema, options); // Extract taskId from the result if (createResult.task) { taskId = createResult.task.taskId; yield { type: 'taskCreated', task: createResult.task }; } else { throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task'); } // Poll for task completion while (true) { // Get current task status const task = await this.getTask({ taskId }, options); yield { type: 'taskStatus', task }; // Check if task is terminal if (isTerminal(task.status)) { if (task.status === 'completed') { // Get the final result const result = await this.getTaskResult({ taskId }, resultSchema, options); yield { type: 'result', result }; } else if (task.status === 'failed') { yield { type: 'error', error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) }; } else if (task.status === 'cancelled') { yield { type: 'error', error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) }; } return; } // When input_required, call tasks/result to deliver queued messages // (elicitation, sampling) via SSE and block until terminal if (task.status === 'input_required') { const result = await this.getTaskResult({ taskId }, resultSchema, options); yield { type: 'result', result }; return; } // Wait before polling again const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000; await new Promise(resolve => setTimeout(resolve, pollInterval)); // Check if cancelled options?.signal?.throwIfAborted(); } } catch (error) { yield { type: 'error', error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) }; } } /** * Sends a request and waits for a response. * * Do not use this method to emit notifications! Use notification() instead. */ request(request, resultSchema, options) { const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; // Send the request return new Promise((resolve, reject) => { const earlyReject = (error) => { reject(error); }; if (!this._transport) { earlyReject(new Error('Not connected')); return; } if (this._options?.enforceStrictCapabilities === true) { try { this.assertCapabilityForMethod(request.method); // If task creation is requested, also check task capabilities if (task) { this.assertTaskCapability(request.method); } } catch (e) { earlyReject(e); return; } } options?.signal?.throwIfAborted(); const messageId = this._requestMessageId++; const jsonrpcRequest = { ...request, jsonrpc: '2.0', id: messageId }; if (options?.onprogress) { this._progressHandlers.set(messageId, options.onprogress); jsonrpcRequest.params = { ...request.params, _meta: { ...(request.params?._meta || {}), progressToken: messageId } }; } // Augment with task creation parameters if provided if (task) { jsonrpcRequest.params = { ...jsonrpcRequest.params, task: task }; } // Augment with related task metadata if relatedTask is provided if (relatedTask) { jsonrpcRequest.params = { ...jsonrpcRequest.params, _meta: { ...(jsonrpcRequest.params?._meta || {}), [RELATED_TASK_META_KEY]: relatedTask } }; } const cancel = (reason) => { this._responseHandlers.delete(messageId); this._progressHandlers.delete(messageId); this._cleanupTimeout(messageId); this._transport ?.send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: messageId, reason: String(reason) } }, { relatedRequestId, resumptionToken, onresumptiontoken }) .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); // Wrap the reason in an McpError if it isn't already const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); reject(error); }; this._responseHandlers.set(messageId, response => { if (options?.signal?.aborted) { return; } if (response instanceof Error) { return reject(response); } try { const parseResult = zod_compat_safeParse(resultSchema, response.result); if (!parseResult.success) { // Type guard: if success is false, error is guaranteed to exist reject(parseResult.error); } else { resolve(parseResult.data); } } catch (error) { reject(error); } }); options?.signal?.addEventListener('abort', () => { cancel(options?.signal?.reason); }); const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); // Queue request if related to a task const relatedTaskId = relatedTask?.taskId; if (relatedTaskId) { // Store the response resolver for this request so responses can be routed back const responseResolver = (response) => { const handler = this._responseHandlers.get(messageId); if (handler) { handler(response); } else { // Log error when resolver is missing, but don't fail this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); } }; this._requestResolvers.set(messageId, responseResolver); this._enqueueTaskMessage(relatedTaskId, { type: 'request', message: jsonrpcRequest, timestamp: Date.now() }).catch(error => { this._cleanupTimeout(messageId); reject(error); }); // Don't send through transport - queued messages are delivered via tasks/result only // This prevents duplicate delivery for bidirectional transports } else { // No related task - send through transport normally this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { this._cleanupTimeout(messageId); reject(error); }); } }); } /** * Gets the current status of a task. * * @experimental Use `client.experimental.tasks.getTask()` to access this method. */ async getTask(params, options) { // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options); } /** * Retrieves the result of a completed task. * * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. */ async getTaskResult(params, resultSchema, options) { // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways return this.request({ method: 'tasks/result', params }, resultSchema, options); } /** * Lists tasks, optionally starting from a pagination cursor. * * @experimental Use `client.experimental.tasks.listTasks()` to access this method. */ async listTasks(params, options) { // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options); } /** * Cancels a specific task. * * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. */ async cancelTask(params, options) { // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options); } /** * Emits a notification, which is a one-way message that does not expect a response. */ async notification(notification, options) { if (!this._transport) { throw new Error('Not connected'); } this.assertNotificationCapability(notification.method); // Queue notification if related to a task const relatedTaskId = options?.relatedTask?.taskId; if (relatedTaskId) { // Build the JSONRPC notification with metadata const jsonrpcNotification = { ...notification, jsonrpc: '2.0', params: { ...notification.params, _meta: { ...(notification.params?._meta || {}), [RELATED_TASK_META_KEY]: options.relatedTask } } }; await this._enqueueTaskMessage(relatedTaskId, { type: 'notification', message: jsonrpcNotification, timestamp: Date.now() }); // Don't send through transport - queued messages are delivered via tasks/result only // This prevents duplicate delivery for bidirectional transports return; } const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; // A notification can only be debounced if it's in the list AND it's "simple" // (i.e., has no parameters and no related request ID or related task that could be lost). const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; if (canDebounce) { // If a notification of this type is already scheduled, do nothing. if (this._pendingDebouncedNotifications.has(notification.method)) { return; } // Mark this notification type as pending. this._pendingDebouncedNotifications.add(notification.method); // Schedule the actual send to happen in the next microtask. // This allows all synchronous calls in the current event loop tick to be coalesced. Promise.resolve().then(() => { // Un-mark the notification so the next one can be scheduled. this._pendingDebouncedNotifications.delete(notification.method); // SAFETY CHECK: If the connection was closed while this was pending, abort. if (!this._transport) { return; } let jsonrpcNotification = { ...notification, jsonrpc: '2.0' }; // Augment with related task metadata if relatedTask is provided if (options?.relatedTask) { jsonrpcNotification = { ...jsonrpcNotification, params: { ...jsonrpcNotification.params, _meta: { ...(jsonrpcNotification.params?._meta || {}), [RELATED_TASK_META_KEY]: options.relatedTask } } }; } // Send the notification, but don't await it here to avoid blocking. // Handle potential errors with a .catch(). this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error)); }); // Return immediately. return; } let jsonrpcNotification = { ...notification, jsonrpc: '2.0' }; // Augment with related task metadata if relatedTask is provided if (options?.relatedTask) { jsonrpcNotification = { ...jsonrpcNotification, params: { ...jsonrpcNotification.params, _meta: { ...(jsonrpcNotification.params?._meta || {}), [RELATED_TASK_META_KEY]: options.relatedTask } } }; } await this._transport.send(jsonrpcNotification, options); } /** * Registers a handler to invoke when this protocol object receives a request with the given method. * * Note that this will replace any previous request handler for the same method. */ setRequestHandler(requestSchema, handler) { const method = getMethodLiteral(requestSchema); this.assertRequestHandlerCapability(method); this._requestHandlers.set(method, (request, extra) => { const parsed = parseWithCompat(requestSchema, request); return Promise.resolve(handler(parsed, extra)); }); } /** * Removes the request handler for the given method. */ removeRequestHandler(method) { this._requestHandlers.delete(method); } /** * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. */ assertCanSetRequestHandler(method) { if (this._requestHandlers.has(method)) { throw new Error(`A request handler for ${method} already exists, which would be overridden`); } } /** * Registers a handler to invoke when this protocol object receives a notification with the given method. * * Note that this will replace any previous notification handler for the same method. */ setNotificationHandler(notificationSchema, handler) { const method = getMethodLiteral(notificationSchema); this._notificationHandlers.set(method, notification => { const parsed = parseWithCompat(notificationSchema, notification); return Promise.resolve(handler(parsed)); }); } /** * Removes the notification handler for the given method. */ removeNotificationHandler(method) { this._notificationHandlers.delete(method); } /** * Cleans up the progress handler associated with a task. * This should be called when a task reaches a terminal status. */ _cleanupTaskProgressHandler(taskId) { const progressToken = this._taskProgressTokens.get(taskId); if (progressToken !== undefined) { this._progressHandlers.delete(progressToken); this._taskProgressTokens.delete(taskId); } } /** * Enqueues a task-related message for side-channel delivery via tasks/result. * @param taskId The task ID to associate the message with * @param message The message to enqueue * @param sessionId Optional session ID for binding the operation to a specific session * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) * * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer * simply propagates the error. */ async _enqueueTaskMessage(taskId, message, sessionId) { // Task message queues are only used when taskStore is configured if (!this._taskStore || !this._taskMessageQueue) { throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured'); } const maxQueueSize = this._options?.maxTaskQueueSize; // Messages queued by local code carry the session of the current connection, like the ones queued for a request. await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize); } /** * Clears the message queue for a task and rejects any pending request resolvers. * @param taskId The task ID whose queue should be cleared * @param sessionId Optional session ID for binding the operation to a specific session */ async _clearTaskQueue(taskId, sessionId) { if (this._taskMessageQueue) { // Reject any pending request resolvers const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); for (const message of messages) { if (message.type === 'request' && isJSONRPCRequest(message.message)) { // Extract request ID from the message const requestId = message.message.id; const resolver = this._requestResolvers.get(requestId); if (resolver) { resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed')); this._requestResolvers.delete(requestId); } else { // Log error when resolver is missing during cleanup for better observability this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); } } } } } /** * Waits for a task update (new messages or status change) with abort signal support. * Uses polling to check for updates at the task's configured poll interval. * @param taskId The task ID to wait for * @param signal Abort signal to cancel the wait * @param sessionId Session of the request that waits, passed to the task store * @returns Promise that resolves when an update occurs or rejects if aborted */ async _waitForTaskUpdate(taskId, signal, sessionId) { // Get the task's poll interval, falling back to default let interval = this._options?.defaultTaskPollInterval ?? 1000; try { const task = await this._taskStore?.getTask(taskId, sessionId); if (task?.pollInterval) { interval = task.pollInterval; } } catch { // Use default interval if task lookup fails } return new Promise((resolve, reject) => { if (signal.aborted) { reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); return; } // Wait for the poll interval, then resolve so caller can check for updates const timeoutId = setTimeout(resolve, interval); // Clean up timeout and reject if aborted signal.addEventListener('abort', () => { clearTimeout(timeoutId); reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); }, { once: true }); }); } requestTaskStore(request, sessionId) { const taskStore = this._taskStore; if (!taskStore) { throw new Error('No task store configured'); } return { createTask: async (taskParams) => { if (!request) { throw new Error('No request provided'); } return await taskStore.createTask(taskParams, request.id, { method: request.method, params: request.params }, sessionId); }, getTask: async (taskId) => { const task = await taskStore.getTask(taskId, sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); } return task; }, storeTaskResult: async (taskId, status, result) => { await taskStore.storeTaskResult(taskId, status, result, sessionId); // Get updated task state and send notification const task = await taskStore.getTask(taskId, sessionId); if (task) { const notification = TaskStatusNotificationSchema.parse({ method: 'notifications/tasks/status', params: task }); await this.notification(notification); if (isTerminal(task.status)) { this._cleanupTaskProgressHandler(taskId); // Don't clear queue here - it will be cleared after delivery via tasks/result } } }, getTaskResult: taskId => { return taskStore.getTaskResult(taskId, sessionId); }, updateTaskStatus: async (taskId, status, statusMessage) => { // Check if task exists const task = await taskStore.getTask(taskId, sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); } // Don't allow transitions from terminal states if (isTerminal(task.status)) { 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.`); } await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); // Get updated task state and send notification const updatedTask = await taskStore.getTask(taskId, sessionId); if (updatedTask) { const notification = TaskStatusNotificationSchema.parse({ method: 'notifications/tasks/status', params: updatedTask }); await this.notification(notification); if (isTerminal(updatedTask.status)) { this._cleanupTaskProgressHandler(taskId); // Don't clear queue here - it will be cleared after delivery via tasks/result } } }, listTasks: cursor => { return taskStore.listTasks(cursor, sessionId); } }; } } function protocol_isPlainObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); } function mergeCapabilities(base, additional) { const result = { ...base }; for (const key in additional) { const k = key; const addValue = additional[k]; if (addValue === undefined) continue; const baseValue = result[k]; if (protocol_isPlainObject(baseValue) && protocol_isPlainObject(addValue)) { result[k] = { ...baseValue, ...addValue }; } else { result[k] = addValue; } } return result; } //# sourceMappingURL=protocol.js.map // EXTERNAL MODULE: ./node_modules/ajv/dist/ajv.js var dist_ajv = __webpack_require__(3282); // EXTERNAL MODULE: ./node_modules/ajv-formats/dist/index.js var dist = __webpack_require__(8182); ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js /** * AJV-based JSON Schema validator provider */ function createDefaultAjvInstance() { const ajv = new dist_ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); const addFormats = dist; addFormats(ajv); return ajv; } /** * @example * ```typescript * // Use with default AJV instance (recommended) * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; * const validator = new AjvJsonSchemaValidator(); * * // Use with custom AJV instance * import { Ajv } from 'ajv'; * const ajv = new Ajv({ strict: true, allErrors: true }); * const validator = new AjvJsonSchemaValidator(ajv); * ``` */ class AjvJsonSchemaValidator { /** * Create an AJV validator * * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. * * @example * ```typescript * // Use default configuration (recommended for most cases) * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; * const validator = new AjvJsonSchemaValidator(); * * // Or provide custom AJV instance for advanced configuration * import { Ajv } from 'ajv'; * import addFormats from 'ajv-formats'; * * const ajv = new Ajv({ validateFormats: true }); * addFormats(ajv); * const validator = new AjvJsonSchemaValidator(ajv); * ``` */ constructor(ajv) { this._ajv = ajv ?? createDefaultAjvInstance(); } /** * Create a validator for the given JSON Schema * * The validator is compiled once and can be reused multiple times. * If the schema has an $id, it will be cached by AJV automatically. * * @param schema - Standard JSON Schema object * @returns A validator function that validates input data */ getValidator(schema) { // Check if schema has $id and is already compiled/cached const ajvValidator = '$id' in schema && typeof schema.$id === 'string' ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) : this._ajv.compile(schema); return (input) => { const valid = ajvValidator(input); if (valid) { return { valid: true, data: input, errorMessage: undefined }; } else { return { valid: false, data: undefined, errorMessage: this._ajv.errorsText(ajvValidator.errors) }; } }; } } //# sourceMappingURL=ajv-provider.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js /** * Experimental server task features for MCP SDK. * WARNING: These APIs are experimental and may change without notice. * * @experimental */ /** * Experimental task features for low-level MCP servers. * * Access via `server.experimental.tasks`: * ```typescript * const stream = server.experimental.tasks.requestStream(request, schema, options); * ``` * * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead. * * @experimental */ class ExperimentalServerTasks { constructor(_server) { this._server = _server; } /** * Sends a request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * This method provides streaming access to request processing, allowing you to * observe intermediate task status updates for task-augmented requests. * * @param request - The request to send * @param resultSchema - Zod schema for validating the result * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ requestStream(request, resultSchema, options) { return this._server.requestStream(request, resultSchema, options); } /** * Sends a sampling request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages * before the final result. * * @example * ```typescript * const stream = server.experimental.tasks.createMessageStream({ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], * maxTokens: 100 * }, { * onprogress: (progress) => { * // Handle streaming tokens via progress notifications * console.log('Progress:', progress.message); * } * }); * * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('Final result:', message.result); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @param params - The sampling request parameters * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ createMessageStream(params, options) { // Access client capabilities via the server const clientCapabilities = this._server.getClientCapabilities(); // Capability check - only required when tools/toolChoice are provided if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { throw new Error('Client does not support sampling tools capability.'); } // Message structure validation - always validate tool_use/tool_result pairs. // These may appear even without tools/toolChoice in the current request when // a previous sampling request returned tool_use and this is a follow-up with results. if (params.messages.length > 0) { const lastMessage = params.messages[params.messages.length - 1]; const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; const hasToolResults = lastContent.some(c => c.type === 'tool_result'); const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use'); if (hasToolResults) { if (lastContent.some(c => c.type !== 'tool_result')) { throw new Error('The last message must contain only tool_result content if any is present'); } if (!hasPreviousToolUse) { throw new Error('tool_result blocks are not matching any tool_use from the previous message'); } } if (hasPreviousToolUse) { // Extract tool_use IDs from previous message and tool_result IDs from current message const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id)); const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId)); if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) { throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match'); } } } return this.requestStream({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); } /** * Sends an elicitation request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated' * and 'taskStatus' messages before the final result. * * @example * ```typescript * const stream = server.experimental.tasks.elicitInputStream({ * mode: 'url', * message: 'Please authenticate', * elicitationId: 'auth-123', * url: 'https://example.com/auth' * }, { * task: { ttl: 300000 } // Task-augmented for long-running auth flow * }); * * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('User action:', message.result.action); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @param params - The elicitation request parameters * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ elicitInputStream(params, options) { // Access client capabilities via the server const clientCapabilities = this._server.getClientCapabilities(); const mode = params.mode ?? 'form'; // Capability check based on mode switch (mode) { case 'url': { if (!clientCapabilities?.elicitation?.url) { throw new Error('Client does not support url elicitation.'); } break; } case 'form': { if (!clientCapabilities?.elicitation?.form) { throw new Error('Client does not support form elicitation.'); } break; } } // Normalize params to ensure mode is set for form mode (defaults to 'form' per spec) const normalizedParams = mode === 'form' && params.mode === undefined ? { ...params, mode: 'form' } : params; // Cast to ServerRequest needed because TypeScript can't narrow the union type // based on the discriminated 'method' field when constructing the object literal return this.requestStream({ method: 'elicitation/create', params: normalizedParams }, ElicitResultSchema, options); } /** * Gets the current status of a task. * * @param taskId - The task identifier * @param options - Optional request options * @returns The task status * * @experimental */ async getTask(taskId, options) { return this._server.getTask({ taskId }, options); } /** * Retrieves the result of a completed task. * * @param taskId - The task identifier * @param resultSchema - Zod schema for validating the result * @param options - Optional request options * @returns The task result * * @experimental */ async getTaskResult(taskId, resultSchema, options) { return this._server.getTaskResult({ taskId }, resultSchema, options); } /** * Lists tasks with optional pagination. * * @param cursor - Optional pagination cursor * @param options - Optional request options * @returns List of tasks with optional next cursor * * @experimental */ async listTasks(cursor, options) { return this._server.listTasks(cursor ? { cursor } : undefined, options); } /** * Cancels a running task. * * @param taskId - The task identifier * @param options - Optional request options * * @experimental */ async cancelTask(taskId, options) { return this._server.cancelTask({ taskId }, options); } } //# sourceMappingURL=server.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js /** * Experimental task capability assertion helpers. * WARNING: These APIs are experimental and may change without notice. * * @experimental */ /** * Asserts that task creation is supported for tools/call. * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. * * @param requests - The task requests capability object * @param method - The method being checked * @param entityName - 'Server' or 'Client' for error messages * @throws Error if the capability is not supported * * @experimental */ function assertToolsCallTaskCapability(requests, method, entityName) { if (!requests) { throw new Error(`${entityName} does not support task creation (required for ${method})`); } switch (method) { case 'tools/call': if (!requests.tools?.call) { throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); } break; default: // Method doesn't support tasks, which is fine - no error break; } } /** * Asserts that task creation is supported for sampling/createMessage or elicitation/create. * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. * * @param requests - The task requests capability object * @param method - The method being checked * @param entityName - 'Server' or 'Client' for error messages * @throws Error if the capability is not supported * * @experimental */ function assertClientRequestTaskCapability(requests, method, entityName) { if (!requests) { throw new Error(`${entityName} does not support task creation (required for ${method})`); } switch (method) { case 'sampling/createMessage': if (!requests.sampling?.createMessage) { throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); } break; case 'elicitation/create': if (!requests.elicitation?.create) { throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); } break; default: // Method doesn't support tasks, which is fine - no error break; } } //# sourceMappingURL=helpers.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js /** * An MCP server on top of a pluggable transport. * * This server will automatically respond to the initialization flow as initiated from the client. * * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: * * ```typescript * // Custom schemas * const CustomRequestSchema = RequestSchema.extend({...}) * const CustomNotificationSchema = NotificationSchema.extend({...}) * const CustomResultSchema = ResultSchema.extend({...}) * * // Type aliases * type CustomRequest = z.infer<typeof CustomRequestSchema> * type CustomNotification = z.infer<typeof CustomNotificationSchema> * type CustomResult = z.infer<typeof CustomResultSchema> * * // Create typed server * const server = new Server<CustomRequest, CustomNotification, CustomResult>({ * name: "CustomServer", * version: "1.0.0" * }) * ``` * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. */ class Server extends Protocol { /** * Initializes this server with the given name and version information. */ constructor(_serverInfo, options) { super(options); this._serverInfo = _serverInfo; // Map log levels by session id this._loggingLevels = new Map(); // Map LogLevelSchema to severity index this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); // Is a message with the given level ignored in the log level set for the given session id? this.isMessageIgnored = (level, sessionId) => { const currentLevel = this._loggingLevels.get(sessionId); return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; }; this._capabilities = options?.capabilities ?? {}; this._instructions = options?.instructions; this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); if (this._capabilities.logging) { this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined; const { level } = request.params; const parseResult = LoggingLevelSchema.safeParse(level); if (parseResult.success) { this._loggingLevels.set(transportSessionId, parseResult.data); } return {}; }); } } /** * Access experimental features. * * WARNING: These APIs are experimental and may change without notice. * * @experimental */ get experimental() { if (!this._experimental) { this._experimental = { tasks: new ExperimentalServerTasks(this) }; } return this._experimental; } /** * Registers new capabilities. This can only be called before connecting to a transport. * * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). */ registerCapabilities(capabilities) { if (this.transport) { throw new Error('Cannot register capabilities after connecting to transport'); } this._capabilities = mergeCapabilities(this._capabilities, capabilities); } /** * Override request handler registration to enforce server-side validation for tools/call. */ setRequestHandler(requestSchema, handler) { const shape = getObjectShape(requestSchema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error('Schema is missing a method literal'); } const methodValue = getLiteralValue(methodSchema); if (typeof methodValue !== 'string') { throw new Error('Schema method literal must be a string'); } const method = methodValue; if (method === 'tools/call') { const wrappedHandler = async (request, extra) => { const validatedRequest = zod_compat_safeParse(CallToolRequestSchema, request); if (!validatedRequest.success) { const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); } const { params } = validatedRequest.data; const result = await Promise.resolve(handler(request, extra)); // When task creation is requested, validate and return CreateTaskResult if (params.task) { const taskValidationResult = zod_compat_safeParse(CreateTaskResultSchema, result); if (!taskValidationResult.success) { const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); } return taskValidationResult.data; } // For non-task requests, validate against CallToolResultSchema const validationResult = zod_compat_safeParse(CallToolResultSchema, result); if (!validationResult.success) { const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); } return validationResult.data; }; // Install the wrapped handler return super.setRequestHandler(requestSchema, wrappedHandler); } // Other handlers use default behavior return super.setRequestHandler(requestSchema, handler); } assertCapabilityForMethod(method) { switch (method) { case 'sampling/createMessage': if (!this._clientCapabilities?.sampling) { throw new Error(`Client does not support sampling (required for ${method})`); } break; case 'elicitation/create': if (!this._clientCapabilities?.elicitation) { throw new Error(`Client does not support elicitation (required for ${method})`); } break; case 'roots/list': if (!this._clientCapabilities?.roots) { throw new Error(`Client does not support listing roots (required for ${method})`); } break; case 'ping': // No specific capability required for ping break; } } assertNotificationCapability(method) { switch (method) { case 'notifications/message': if (!this._capabilities.logging) { throw new Error(`Server does not support logging (required for ${method})`); } break; case 'notifications/resources/updated': case 'notifications/resources/list_changed': if (!this._capabilities.resources) { throw new Error(`Server does not support notifying about resources (required for ${method})`); } break; case 'notifications/tools/list_changed': if (!this._capabilities.tools) { throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); } break; case 'notifications/prompts/list_changed': if (!this._capabilities.prompts) { throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); } break; case 'notifications/elicitation/complete': if (!this._clientCapabilities?.elicitation?.url) { throw new Error(`Client does not support URL elicitation (required for ${method})`); } break; case 'notifications/cancelled': // Cancellation notifications are always allowed break; case 'notifications/progress': // Progress notifications are always allowed break; } } assertRequestHandlerCapability(method) { // Task handlers are registered in Protocol constructor before _capabilities is initialized // Skip capability check for task methods during initialization if (!this._capabilities) { return; } switch (method) { case 'completion/complete': if (!this._capabilities.completions) { throw new Error(`Server does not support completions (required for ${method})`); } break; case 'logging/setLevel': if (!this._capabilities.logging) { throw new Error(`Server does not support logging (required for ${method})`); } break; case 'prompts/get': case 'prompts/list': if (!this._capabilities.prompts) { throw new Error(`Server does not support prompts (required for ${method})`); } break; case 'resources/list': case 'resources/templates/list': case 'resources/read': if (!this._capabilities.resources) { throw new Error(`Server does not support resources (required for ${method})`); } break; case 'tools/call': case 'tools/list': if (!this._capabilities.tools) { throw new Error(`Server does not support tools (required for ${method})`); } break; case 'tasks/get': case 'tasks/list': case 'tasks/result': case 'tasks/cancel': if (!this._capabilities.tasks) { throw new Error(`Server does not support tasks capability (required for ${method})`); } break; case 'ping': case 'initialize': // No specific capability required for these methods break; } } assertTaskCapability(method) { assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client'); } assertTaskHandlerCapability(method) { // Task handlers are registered in Protocol constructor before _capabilities is initialized // Skip capability check for task methods during initialization if (!this._capabilities) { return; } assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server'); } async _oninitialize(request) { const requestedVersion = request.params.protocolVersion; this._clientCapabilities = request.params.capabilities; this._clientVersion = request.params.clientInfo; const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; return { protocolVersion, capabilities: this.getCapabilities(), serverInfo: this._serverInfo, ...(this._instructions && { instructions: this._instructions }) }; } /** * After initialization has completed, this will be populated with the client's reported capabilities. */ getClientCapabilities() { return this._clientCapabilities; } /** * After initialization has completed, this will be populated with information about the client's name and version. */ getClientVersion() { return this._clientVersion; } getCapabilities() { return this._capabilities; } async ping() { return this.request({ method: 'ping' }, EmptyResultSchema); } // Implementation async createMessage(params, options) { // Capability check - only required when tools/toolChoice are provided if (params.tools || params.toolChoice) { if (!this._clientCapabilities?.sampling?.tools) { throw new Error('Client does not support sampling tools capability.'); } } // Message structure validation - always validate tool_use/tool_result pairs. // These may appear even without tools/toolChoice in the current request when // a previous sampling request returned tool_use and this is a follow-up with results. if (params.messages.length > 0) { const lastMessage = params.messages[params.messages.length - 1]; const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; const hasToolResults = lastContent.some(c => c.type === 'tool_result'); const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use'); if (hasToolResults) { if (lastContent.some(c => c.type !== 'tool_result')) { throw new Error('The last message must contain only tool_result content if any is present'); } if (!hasPreviousToolUse) { throw new Error('tool_result blocks are not matching any tool_use from the previous message'); } } if (hasPreviousToolUse) { const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id)); const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId)); if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) { throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match'); } } } // Use different schemas based on whether tools are provided if (params.tools) { return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options); } return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); } /** * Creates an elicitation request for the given parameters. * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. * @param params The parameters for the elicitation request. * @param options Optional request options. * @returns The result of the elicitation request. */ async elicitInput(params, options) { const mode = (params.mode ?? 'form'); switch (mode) { case 'url': { if (!this._clientCapabilities?.elicitation?.url) { throw new Error('Client does not support url elicitation.'); } const urlParams = params; return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options); } case 'form': { if (!this._clientCapabilities?.elicitation?.form) { throw new Error('Client does not support form elicitation.'); } const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' }; const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options); if (result.action === 'accept' && result.content && formParams.requestedSchema) { try { const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); const validationResult = validator(result.content); if (!validationResult.valid) { throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); } } catch (error) { if (error instanceof McpError) { throw error; } throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); } } return result; } } } /** * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` * notification for the specified elicitation ID. * * @param elicitationId The ID of the elicitation to mark as complete. * @param options Optional notification options. Useful when the completion notification should be related to a prior request. * @returns A function that emits the completion notification when awaited. */ createElicitationCompletionNotifier(elicitationId, options) { if (!this._clientCapabilities?.elicitation?.url) { throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); } return () => this.notification({ method: 'notifications/elicitation/complete', params: { elicitationId } }, options); } async listRoots(params, options) { return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); } /** * Sends a logging message to the client, if connected. * Note: You only need to send the parameters object, not the entire JSON RPC message * @see LoggingMessageNotification * @param params * @param sessionId optional for stateless and backward compatibility */ async sendLoggingMessage(params, sessionId) { if (this._capabilities.logging) { if (!this.isMessageIgnored(params.level, sessionId)) { return this.notification({ method: 'notifications/message', params }); } } } async sendResourceUpdated(params) { return this.notification({ method: 'notifications/resources/updated', params }); } async sendResourceListChanged() { return this.notification({ method: 'notifications/resources/list_changed' }); } async sendToolListChanged() { return this.notification({ method: 'notifications/tools/list_changed' }); } async sendPromptListChanged() { return this.notification({ method: 'notifications/prompts/list_changed' }); } } //# sourceMappingURL=index.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); /** * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. * Works with both Zod v3 and v4 schemas. */ function completable(schema, complete) { Object.defineProperty(schema, COMPLETABLE_SYMBOL, { value: { complete }, enumerable: false, writable: false, configurable: false }); return schema; } /** * Checks if a schema is completable (has completion metadata). */ function isCompletable(schema) { return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema; } /** * Gets the completer callback from a completable schema, if it exists. */ function getCompleter(schema) { const meta = schema[COMPLETABLE_SYMBOL]; return meta?.complete; } /** * Unwraps a completable schema to get the underlying schema. * For backward compatibility with code that called `.unwrap()`. */ function unwrapCompletable(schema) { return schema; } // Legacy exports for backward compatibility // These types are deprecated but kept for existing code var McpZodTypeKind; (function (McpZodTypeKind) { McpZodTypeKind["Completable"] = "McpCompletable"; })(McpZodTypeKind || (McpZodTypeKind = {})); //# sourceMappingURL=completable.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js /** * Tool name validation utilities according to SEP: Specify Format for Tool Names * * Tool names SHOULD be between 1 and 128 characters in length (inclusive). * Tool names are case-sensitive. * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits * (0-9), underscore (_), dash (-), and dot (.). * Tool names SHOULD NOT contain spaces, commas, or other special characters. */ /** * Regular expression for valid tool names according to SEP-986 specification */ const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; /** * Validates a tool name according to the SEP specification * @param name - The tool name to validate * @returns An object containing validation result and any warnings */ function validateToolName(name) { const warnings = []; // Check length if (name.length === 0) { return { isValid: false, warnings: ['Tool name cannot be empty'] }; } if (name.length > 128) { return { isValid: false, warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] }; } // Check for specific problematic patterns (these are warnings, not validation failures) if (name.includes(' ')) { warnings.push('Tool name contains spaces, which may cause parsing issues'); } if (name.includes(',')) { warnings.push('Tool name contains commas, which may cause parsing issues'); } // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) if (name.startsWith('-') || name.endsWith('-')) { warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); } if (name.startsWith('.') || name.endsWith('.')) { warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); } // Check for invalid characters if (!TOOL_NAME_REGEX.test(name)) { const invalidChars = name .split('') .filter(char => !/[A-Za-z0-9._-]/.test(char)) .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); return { isValid: false, warnings }; } return { isValid: true, warnings }; } /** * Issues warnings for non-conforming tool names * @param name - The tool name that triggered the warnings * @param warnings - Array of warning messages */ function issueToolNameWarning(name, warnings) { if (warnings.length > 0) { console.warn(`Tool name validation warning for "${name}":`); for (const warning of warnings) { console.warn(` - ${warning}`); } console.warn('Tool registration will proceed, but this may cause compatibility issues.'); console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); } } /** * Validates a tool name and issues warnings for non-conforming names * @param name - The tool name to validate * @returns true if the name is valid, false otherwise */ function validateAndWarnToolName(name) { const result = validateToolName(name); // Always issue warnings for any validation issues (both invalid names and warnings) issueToolNameWarning(name, result.warnings); return result.isValid; } //# sourceMappingURL=toolNameValidation.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js /** * Experimental McpServer task features for MCP SDK. * WARNING: These APIs are experimental and may change without notice. * * @experimental */ /** * Experimental task features for McpServer. * * Access via `server.experimental.tasks`: * ```typescript * server.experimental.tasks.registerToolTask('long-running', config, handler); * ``` * * @experimental */ class ExperimentalMcpServerTasks { constructor(_mcpServer) { this._mcpServer = _mcpServer; } registerToolTask(name, config, handler) { // Validate that taskSupport is not 'forbidden' for task-based tools const execution = { taskSupport: 'required', ...config.execution }; if (execution.taskSupport === 'forbidden') { throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`); } // Access McpServer's internal _createRegisteredTool method const mcpServerInternal = this._mcpServer; return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler); } } //# sourceMappingURL=mcp-server.js.map ;// ./node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js /* unused harmony import specifier */ var UriTemplate; // Counts array elements and object members in `value`, stopping once the running total passes `max`. function toolInputElementCount(value, max) { let count = 0; const stack = [value]; while (stack.length > 0) { const node = stack.pop(); if (node === null || typeof node !== 'object') continue; if (Array.isArray(node)) { for (const child of node) { if (++count > max) return count; if (child !== null && typeof child === 'object') stack.push(child); } } else { for (const key in node) { if (!Object.prototype.hasOwnProperty.call(node, key)) continue; if (++count > max) return count; const child = node[key]; if (child !== null && typeof child === 'object') stack.push(child); } } } return count; } // Resolves the configured element ceiling: no limit when unset or Infinity, else a number of at least 1. function resolveMaxToolInputElements(value) { if (value === undefined || value === Infinity) return undefined; if (typeof value !== 'number' || Number.isNaN(value) || value < 1) { throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`); } return value; } /** * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. * For advanced usage (like sending notifications or setting custom request handlers), use the underlying * Server instance available via the `server` property. */ class McpServer { constructor(serverInfo, options) { this._registeredResources = {}; this._registeredResourceTemplates = {}; this._registeredTools = {}; this._registeredPrompts = {}; this._toolHandlersInitialized = false; this._completionHandlerInitialized = false; this._resourceHandlersInitialized = false; this._promptHandlersInitialized = false; this.server = new Server(serverInfo, options); this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements); } /** * Access experimental features. * * WARNING: These APIs are experimental and may change without notice. * * @experimental */ get experimental() { if (!this._experimental) { this._experimental = { tasks: new ExperimentalMcpServerTasks(this) }; } return this._experimental; } /** * Attaches to the given transport, starts it, and starts listening for messages. * * 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. */ async connect(transport) { return await this.server.connect(transport); } /** * Closes the connection. */ async close() { await this.server.close(); } setToolRequestHandlers() { if (this._toolHandlersInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); this.server.registerCapabilities({ tools: { listChanged: true } }); this.server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Object.entries(this._registeredTools) .filter(([, tool]) => tool.enabled) .map(([name, tool]) => { const toolDefinition = { name, title: tool.title, description: tool.description, inputSchema: (() => { const obj = normalizeObjectSchema(tool.inputSchema); return obj ? toJsonSchemaCompat(obj, { strictUnions: true, pipeStrategy: 'input' }) : EMPTY_OBJECT_JSON_SCHEMA; })(), annotations: tool.annotations, execution: tool.execution, _meta: tool._meta }; if (tool.outputSchema) { const obj = normalizeObjectSchema(tool.outputSchema); if (obj) { toolDefinition.outputSchema = toJsonSchemaCompat(obj, { strictUnions: true, pipeStrategy: 'output' }); } } return toolDefinition; }) })); this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { try { const tool = this._registeredTools[request.params.name]; if (!tool) { throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); } if (!tool.enabled) { throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); } const isTaskRequest = !!request.params.task; const taskSupport = tool.execution?.taskSupport; const isTaskHandler = 'createTask' in tool.handler; // Validate task hint configuration if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) { throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`); } // Handle taskSupport 'required' without task augmentation if (taskSupport === 'required' && !isTaskRequest) { throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`); } // Handle taskSupport 'optional' without task augmentation - automatic polling if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) { return await this.handleAutomaticTaskPolling(tool, request, extra); } // Normal execution path const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); const result = await this.executeToolHandler(tool, args, extra); // Return CreateTaskResult immediately for task requests if (isTaskRequest) { return result; } // Validate output schema for non-task requests await this.validateToolOutput(tool, result, request.params.name); return result; } catch (error) { if (error instanceof McpError) { if (error.code === ErrorCode.UrlElicitationRequired) { throw error; // Return the error to the caller without wrapping in CallToolResult } } return this.createToolError(error instanceof Error ? error.message : String(error)); } }); this._toolHandlersInitialized = true; } /** * Creates a tool error result. * * @param errorMessage - The error message. * @returns The tool error result. */ createToolError(errorMessage) { return { content: [ { type: 'text', text: errorMessage } ], isError: true }; } /** * Validates tool input arguments against the tool's input schema. */ async validateToolInput(tool, args, toolName) { if (this._maxToolInputElements !== undefined && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) { throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`); } if (!tool.inputSchema) { return undefined; } // Try to normalize to object schema first (for raw shapes and object schemas) // If that fails, use the schema directly (for union/intersection/etc) const inputObj = normalizeObjectSchema(tool.inputSchema); const schemaToParse = inputObj ?? tool.inputSchema; const parseResult = await zod_compat_safeParseAsync(schemaToParse, args ?? {}); if (!parseResult.success) { const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; const errorMessage = getParseErrorMessage(error); throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`); } return parseResult.data; } /** * Validates tool output against the tool's output schema. */ async validateToolOutput(tool, result, toolName) { if (!tool.outputSchema) { return; } // Only validate CallToolResult, not CreateTaskResult if (!('content' in result)) { return; } if (result.isError) { return; } if (!result.structuredContent) { throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); } // if the tool has an output schema, validate structured content const outputObj = normalizeObjectSchema(tool.outputSchema); const parseResult = await zod_compat_safeParseAsync(outputObj, result.structuredContent); if (!parseResult.success) { const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; const errorMessage = getParseErrorMessage(error); throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`); } } /** * Executes a tool handler (either regular or task-based). */ async executeToolHandler(tool, args, extra) { const handler = tool.handler; const isTaskHandler = 'createTask' in handler; if (isTaskHandler) { if (!extra.taskStore) { throw new Error('No task store provided.'); } const taskExtra = { ...extra, taskStore: extra.taskStore }; if (tool.inputSchema) { const typedHandler = handler; // eslint-disable-next-line @typescript-eslint/no-explicit-any return await Promise.resolve(typedHandler.createTask(args, taskExtra)); } else { const typedHandler = handler; // eslint-disable-next-line @typescript-eslint/no-explicit-any return await Promise.resolve(typedHandler.createTask(taskExtra)); } } if (tool.inputSchema) { const typedHandler = handler; // eslint-disable-next-line @typescript-eslint/no-explicit-any return await Promise.resolve(typedHandler(args, extra)); } else { const typedHandler = handler; // eslint-disable-next-line @typescript-eslint/no-explicit-any return await Promise.resolve(typedHandler(extra)); } } /** * Handles automatic task polling for tools with taskSupport 'optional'. */ async handleAutomaticTaskPolling(tool, request, extra) { if (!extra.taskStore) { throw new Error('No task store provided for task-capable tool.'); } // Validate input and create task const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); const handler = tool.handler; const taskExtra = { ...extra, taskStore: extra.taskStore }; const createTaskResult = args // undefined only if tool.inputSchema is undefined ? await Promise.resolve(handler.createTask(args, taskExtra)) : // eslint-disable-next-line @typescript-eslint/no-explicit-any await Promise.resolve(handler.createTask(taskExtra)); // Poll until completion const taskId = createTaskResult.task.taskId; let task = createTaskResult.task; const pollInterval = task.pollInterval ?? 5000; while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') { await new Promise(resolve => setTimeout(resolve, pollInterval)); const updatedTask = await extra.taskStore.getTask(taskId); if (!updatedTask) { throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`); } task = updatedTask; } // Return the final result return (await extra.taskStore.getTaskResult(taskId)); } setCompletionRequestHandler() { if (this._completionHandlerInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); this.server.registerCapabilities({ completions: {} }); this.server.setRequestHandler(CompleteRequestSchema, async (request) => { switch (request.params.ref.type) { case 'ref/prompt': assertCompleteRequestPrompt(request); return this.handlePromptCompletion(request, request.params.ref); case 'ref/resource': assertCompleteRequestResourceTemplate(request); return this.handleResourceCompletion(request, request.params.ref); default: throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); } }); this._completionHandlerInitialized = true; } async handlePromptCompletion(request, ref) { const prompt = this._registeredPrompts[ref.name]; if (!prompt) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); } if (!prompt.enabled) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); } if (!prompt.argsSchema) { return EMPTY_COMPLETION_RESULT; } const promptShape = getObjectShape(prompt.argsSchema); const field = promptShape?.[request.params.argument.name]; if (!isCompletable(field)) { return EMPTY_COMPLETION_RESULT; } const completer = getCompleter(field); if (!completer) { return EMPTY_COMPLETION_RESULT; } const suggestions = await completer(request.params.argument.value, request.params.context); return createCompletionResult(suggestions); } async handleResourceCompletion(request, ref) { const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); if (!template) { if (this._registeredResources[ref.uri]) { // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). return EMPTY_COMPLETION_RESULT; } throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); } const completer = template.resourceTemplate.completeCallback(request.params.argument.name); if (!completer) { return EMPTY_COMPLETION_RESULT; } const suggestions = await completer(request.params.argument.value, request.params.context); return createCompletionResult(suggestions); } setResourceRequestHandlers() { if (this._resourceHandlersInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); this.server.registerCapabilities({ resources: { listChanged: true } }); this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { const resources = Object.entries(this._registeredResources) .filter(([_, resource]) => resource.enabled) .map(([uri, resource]) => ({ uri, name: resource.name, ...resource.metadata })); const templateResources = []; for (const template of Object.values(this._registeredResourceTemplates)) { if (!template.resourceTemplate.listCallback) { continue; } const result = await template.resourceTemplate.listCallback(extra); for (const resource of result.resources) { templateResources.push({ ...template.metadata, // the defined resource metadata should override the template metadata if present ...resource }); } } return { resources: [...resources, ...templateResources] }; }); this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ name, uriTemplate: template.resourceTemplate.uriTemplate.toString(), ...template.metadata })); return { resourceTemplates }; }); this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { const uri = new URL(request.params.uri); // First check for exact resource match const resource = this._registeredResources[uri.toString()]; if (resource) { if (!resource.enabled) { throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); } return resource.readCallback(uri, extra); } // Then check templates for (const template of Object.values(this._registeredResourceTemplates)) { const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); if (variables) { return template.readCallback(uri, variables, extra); } } throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); }); this._resourceHandlersInitialized = true; } setPromptRequestHandlers() { if (this._promptHandlersInitialized) { return; } this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); this.server.registerCapabilities({ prompts: { listChanged: true } }); this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: Object.entries(this._registeredPrompts) .filter(([, prompt]) => prompt.enabled) .map(([name, prompt]) => { return { name, title: prompt.title, description: prompt.description, arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined }; }) })); this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { const prompt = this._registeredPrompts[request.params.name]; if (!prompt) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); } if (!prompt.enabled) { throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); } if (prompt.argsSchema) { const argsObj = normalizeObjectSchema(prompt.argsSchema); const parseResult = await zod_compat_safeParseAsync(argsObj, request.params.arguments ?? {}); if (!parseResult.success) { const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; const errorMessage = getParseErrorMessage(error); throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`); } const args = parseResult.data; const cb = prompt.callback; return await Promise.resolve(cb(args, extra)); } else { const cb = prompt.callback; // eslint-disable-next-line @typescript-eslint/no-explicit-any return await Promise.resolve(cb(extra)); } }); this._promptHandlersInitialized = true; } resource(name, uriOrTemplate, ...rest) { let metadata; if (typeof rest[0] === 'object') { metadata = rest.shift(); } const readCallback = rest[0]; if (typeof uriOrTemplate === 'string') { if (this._registeredResources[uriOrTemplate]) { throw new Error(`Resource ${uriOrTemplate} is already registered`); } const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResource; } else { if (this._registeredResourceTemplates[name]) { throw new Error(`Resource template ${name} is already registered`); } const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResourceTemplate; } } registerResource(name, uriOrTemplate, config, readCallback) { if (typeof uriOrTemplate === 'string') { if (this._registeredResources[uriOrTemplate]) { throw new Error(`Resource ${uriOrTemplate} is already registered`); } const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResource; } else { if (this._registeredResourceTemplates[name]) { throw new Error(`Resource template ${name} is already registered`); } const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); this.setResourceRequestHandlers(); this.sendResourceListChanged(); return registeredResourceTemplate; } } _createRegisteredResource(name, title, uri, metadata, readCallback) { const registeredResource = { name, title, metadata, readCallback, enabled: true, disable: () => registeredResource.update({ enabled: false }), enable: () => registeredResource.update({ enabled: true }), remove: () => registeredResource.update({ uri: null }), update: updates => { if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { delete this._registeredResources[uri]; if (updates.uri) this._registeredResources[updates.uri] = registeredResource; } if (typeof updates.name !== 'undefined') registeredResource.name = updates.name; if (typeof updates.title !== 'undefined') registeredResource.title = updates.title; if (typeof updates.metadata !== 'undefined') registeredResource.metadata = updates.metadata; if (typeof updates.callback !== 'undefined') registeredResource.readCallback = updates.callback; if (typeof updates.enabled !== 'undefined') registeredResource.enabled = updates.enabled; this.sendResourceListChanged(); } }; this._registeredResources[uri] = registeredResource; return registeredResource; } _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { const registeredResourceTemplate = { resourceTemplate: template, title, metadata, readCallback, enabled: true, disable: () => registeredResourceTemplate.update({ enabled: false }), enable: () => registeredResourceTemplate.update({ enabled: true }), remove: () => registeredResourceTemplate.update({ name: null }), update: updates => { if (typeof updates.name !== 'undefined' && updates.name !== name) { delete this._registeredResourceTemplates[name]; if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; } if (typeof updates.title !== 'undefined') registeredResourceTemplate.title = updates.title; if (typeof updates.template !== 'undefined') registeredResourceTemplate.resourceTemplate = updates.template; if (typeof updates.metadata !== 'undefined') registeredResourceTemplate.metadata = updates.metadata; if (typeof updates.callback !== 'undefined') registeredResourceTemplate.readCallback = updates.callback; if (typeof updates.enabled !== 'undefined') registeredResourceTemplate.enabled = updates.enabled; this.sendResourceListChanged(); } }; this._registeredResourceTemplates[name] = registeredResourceTemplate; // If the resource template has any completion callbacks, enable completions capability const variableNames = template.uriTemplate.variableNames; const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v)); if (hasCompleter) { this.setCompletionRequestHandler(); } return registeredResourceTemplate; } _createRegisteredPrompt(name, title, description, argsSchema, callback) { const registeredPrompt = { title, description, argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema), callback, enabled: true, disable: () => registeredPrompt.update({ enabled: false }), enable: () => registeredPrompt.update({ enabled: true }), remove: () => registeredPrompt.update({ name: null }), update: updates => { if (typeof updates.name !== 'undefined' && updates.name !== name) { delete this._registeredPrompts[name]; if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; } if (typeof updates.title !== 'undefined') registeredPrompt.title = updates.title; if (typeof updates.description !== 'undefined') registeredPrompt.description = updates.description; if (typeof updates.argsSchema !== 'undefined') registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); if (typeof updates.callback !== 'undefined') registeredPrompt.callback = updates.callback; if (typeof updates.enabled !== 'undefined') registeredPrompt.enabled = updates.enabled; this.sendPromptListChanged(); } }; this._registeredPrompts[name] = registeredPrompt; // If any argument uses a Completable schema, enable completions capability if (argsSchema) { const hasCompletable = Object.values(argsSchema).some(field => { const inner = field instanceof types_ZodOptional ? field._def?.innerType : field; return isCompletable(inner); }); if (hasCompletable) { this.setCompletionRequestHandler(); } } return registeredPrompt; } _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) { // Validate tool name according to SEP specification validateAndWarnToolName(name); const registeredTool = { title, description, inputSchema: getZodSchemaObject(inputSchema), outputSchema: getZodSchemaObject(outputSchema), annotations, execution, _meta, handler: handler, enabled: true, disable: () => registeredTool.update({ enabled: false }), enable: () => registeredTool.update({ enabled: true }), remove: () => registeredTool.update({ name: null }), update: updates => { if (typeof updates.name !== 'undefined' && updates.name !== name) { if (typeof updates.name === 'string') { validateAndWarnToolName(updates.name); } delete this._registeredTools[name]; if (updates.name) this._registeredTools[updates.name] = registeredTool; } if (typeof updates.title !== 'undefined') registeredTool.title = updates.title; if (typeof updates.description !== 'undefined') registeredTool.description = updates.description; if (typeof updates.paramsSchema !== 'undefined') registeredTool.inputSchema = objectFromShape(updates.paramsSchema); if (typeof updates.outputSchema !== 'undefined') registeredTool.outputSchema = objectFromShape(updates.outputSchema); if (typeof updates.callback !== 'undefined') registeredTool.handler = updates.callback; if (typeof updates.annotations !== 'undefined') registeredTool.annotations = updates.annotations; if (typeof updates._meta !== 'undefined') registeredTool._meta = updates._meta; if (typeof updates.enabled !== 'undefined') registeredTool.enabled = updates.enabled; this.sendToolListChanged(); } }; this._registeredTools[name] = registeredTool; this.setToolRequestHandlers(); this.sendToolListChanged(); return registeredTool; } /** * tool() implementation. Parses arguments passed to overrides defined above. */ tool(name, ...rest) { if (this._registeredTools[name]) { throw new Error(`Tool ${name} is already registered`); } let description; let inputSchema; let outputSchema; let annotations; // Tool properties are passed as separate arguments, with omissions allowed. // Support for this style is frozen as of protocol version 2025-03-26. Future additions // to tool definition should *NOT* be added. if (typeof rest[0] === 'string') { description = rest.shift(); } // Handle the different overload combinations if (rest.length > 1) { // We have at least one more arg before the callback const firstArg = rest[0]; if (isZodRawShapeCompat(firstArg)) { // We have a params schema as the first arg inputSchema = rest.shift(); // Check if the next arg is potentially annotations if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { // Case: tool(name, paramsSchema, annotations, cb) // Or: tool(name, description, paramsSchema, annotations, cb) annotations = rest.shift(); } } else if (typeof firstArg === 'object' && firstArg !== null) { // ToolAnnotations values are primitives. Nested objects indicate a misplaced schema if (Object.values(firstArg).some(v => typeof v === 'object' && v !== null)) { throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`); } annotations = rest.shift(); } } const callback = rest[0]; return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback); } /** * Registers a tool with a config object and callback. */ registerTool(name, config, cb) { if (this._registeredTools[name]) { throw new Error(`Tool ${name} is already registered`); } const { title, description, inputSchema, outputSchema, annotations, _meta } = config; return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb); } prompt(name, ...rest) { if (this._registeredPrompts[name]) { throw new Error(`Prompt ${name} is already registered`); } let description; if (typeof rest[0] === 'string') { description = rest.shift(); } let argsSchema; if (rest.length > 1) { argsSchema = rest.shift(); } const cb = rest[0]; const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); this.setPromptRequestHandlers(); this.sendPromptListChanged(); return registeredPrompt; } /** * Registers a prompt with a config object and callback. */ registerPrompt(name, config, cb) { if (this._registeredPrompts[name]) { throw new Error(`Prompt ${name} is already registered`); } const { title, description, argsSchema } = config; const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); this.setPromptRequestHandlers(); this.sendPromptListChanged(); return registeredPrompt; } /** * Checks if the server is connected to a transport. * @returns True if the server is connected */ isConnected() { return this.server.transport !== undefined; } /** * Sends a logging message to the client, if connected. * Note: You only need to send the parameters object, not the entire JSON RPC message * @see LoggingMessageNotification * @param params * @param sessionId optional for stateless and backward compatibility */ async sendLoggingMessage(params, sessionId) { return this.server.sendLoggingMessage(params, sessionId); } /** * Sends a resource list changed event to the client, if connected. */ sendResourceListChanged() { if (this.isConnected()) { this.server.sendResourceListChanged(); } } /** * Sends a tool list changed event to the client, if connected. */ sendToolListChanged() { if (this.isConnected()) { this.server.sendToolListChanged(); } } /** * Sends a prompt list changed event to the client, if connected. */ sendPromptListChanged() { if (this.isConnected()) { this.server.sendPromptListChanged(); } } } /** * A resource template combines a URI pattern with optional functionality to enumerate * all resources matching that pattern. */ class ResourceTemplate { constructor(uriTemplate, _callbacks) { this._callbacks = _callbacks; this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate; } /** * Gets the URI template pattern. */ get uriTemplate() { return this._uriTemplate; } /** * Gets the list callback, if one was provided. */ get listCallback() { return this._callbacks.list; } /** * Gets the callback for completing a specific URI template variable, if one was provided. */ completeCallback(variable) { return this._callbacks.complete?.[variable]; } } const EMPTY_OBJECT_JSON_SCHEMA = { type: 'object', properties: {} }; /** * Checks if a value looks like a Zod schema by checking for parse/safeParse methods. */ function isZodTypeLike(value) { return (value !== null && typeof value === 'object' && 'parse' in value && typeof value.parse === 'function' && 'safeParse' in value && typeof value.safeParse === 'function'); } /** * Checks if an object is a Zod schema instance (v3 or v4). * * Zod schemas have internal markers: * - v3: `_def` property * - v4: `_zod` property * * This includes transformed schemas like z.preprocess(), z.transform(), z.pipe(). */ function isZodSchemaInstance(obj) { return '_def' in obj || '_zod' in obj || isZodTypeLike(obj); } /** * Checks if an object is a "raw shape" - a plain object where values are Zod schemas. * * Raw shapes are used as shorthand: `{ name: z.string() }` instead of `z.object({ name: z.string() })`. * * IMPORTANT: This must NOT match actual Zod schema instances (like z.preprocess, z.pipe), * which have internal properties that could be mistaken for schema values. */ function isZodRawShapeCompat(obj) { if (typeof obj !== 'object' || obj === null) { return false; } // If it's already a Zod schema instance, it's NOT a raw shape if (isZodSchemaInstance(obj)) { return false; } // Empty objects are valid raw shapes (tools with no parameters) if (Object.keys(obj).length === 0) { return true; } // A raw shape has at least one property that is a Zod schema return Object.values(obj).some(isZodTypeLike); } /** * Converts a provided Zod schema to a Zod object if it is a ZodRawShapeCompat, * otherwise returns the schema as is. Throws if the value is not a valid Zod schema. */ function getZodSchemaObject(schema) { if (!schema) { return undefined; } if (isZodRawShapeCompat(schema)) { return objectFromShape(schema); } if (!isZodSchemaInstance(schema)) { throw new Error('inputSchema must be a Zod schema or raw shape, received an unrecognized object'); } return schema; } function promptArgumentsFromSchema(schema) { const shape = getObjectShape(schema); if (!shape) return []; return Object.entries(shape).map(([name, field]) => { // Get description - works for both v3 and v4 const description = getSchemaDescription(field); // Check if optional - works for both v3 and v4 const isOptional = isSchemaOptional(field); return { name, description, required: !isOptional }; }); } function getMethodValue(schema) { const shape = getObjectShape(schema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error('Schema is missing a method literal'); } // Extract literal value - works for both v3 and v4 const value = getLiteralValue(methodSchema); if (typeof value === 'string') { return value; } throw new Error('Schema method literal must be a string'); } function createCompletionResult(suggestions) { return { completion: { values: suggestions.slice(0, 100), total: suggestions.length, hasMore: suggestions.length > 100 } }; } const EMPTY_COMPLETION_RESULT = { completion: { values: [], hasMore: false } }; //# sourceMappingURL=mcp.js.map ;// ./src/angie/angie-integration.js /** * Angie browser MCP server for Dynific Addons, loaded inside the Elementor editor only. * * Changes the OPEN document live through Elementor's $e commands, so the user sees * every change instantly, can undo it, and saves with Update. Creating templates and * changing templates that are not open is done by the PHP abilities (dynific/*). * Every widget and setting key is validated server-side before it reaches the editor. * Built separately from src/js (see webpack.config.js). */ const angie_integration_config = window.aeproAngie; const SAVE_NOTE = 'Changes are live in the editor but NOT saved. Ask the user to review and click Update (or Save Draft), or save with dynific-editor-save-document when the user asks.'; const elementId = stringType().regex( /^[a-z0-9]+$/i ).max( 20 ); const settingsSchema = recordType( anyType() ).optional().describe( 'Setting keys from dynific/get-widget-schema; omit to keep defaults' ); const request = async ( action, params = {} ) => { const body = new FormData(); body.append( 'action', action ); body.append( 'nonce', angie_integration_config.nonce ); body.append( 'post_id', String( getDocument().id ) ); Object.keys( params ).forEach( ( key ) => body.append( key, params[ key ] ) ); const response = await fetch( angie_integration_config.ajaxUrl, { method: 'POST', credentials: 'same-origin', body, } ); const json = await response.json().catch( () => null ); if ( ! json || ! json.success ) { const message = json && json.data && json.data.message ? json.data.message : `Request failed (${ response.status })`; throw new Error( message ); } return json.data; }; const toResult = async ( fn ) => { try { return { content: [ { type: 'text', text: JSON.stringify( await fn() ) } ] }; } catch ( error ) { return { content: [ { type: 'text', text: error.message } ], isError: true }; } }; const getDocument = () => { const doc = window.elementor && window.elementor.documents && window.elementor.documents.getCurrent(); if ( ! doc || ! doc.container ) { throw new Error( 'No Elementor document is open.' ); } return doc; }; const getContainer = ( id ) => { const container = window.elementor.getContainer( id ); if ( ! container || ! container.model || ( container.document && container.document !== getDocument() ) ) { throw new Error( `Element "${ id }" was not found in the open document. Call dynific-editor-get-open-document.` ); } return container; }; const plainSettings = ( settings ) => ( settings && ! Array.isArray( settings ) ? settings : {} ); /** * Elementor 4 boxes. Dynific widgets can be placed inside them; the boxes themselves * (structure, sizes, styles) are Elementor's job. */ const ATOMIC_BOXES = [ 'e-flexbox', 'e-div-block', 'e-grid' ]; /** * Compact element tree: ids, types and changed (non-default) settings only. */ const summarize = ( elements ) => ( elements || [] ).map( ( element ) => { const item = { id: element.id, elType: element.elType }; if ( element.widgetType ) { item.widgetType = element.widgetType; item.settings = plainSettings( element.settings ); } if ( element.elements && element.elements.length ) { item.elements = summarize( element.elements ); } return item; } ); /** * Where new widgets go. A section resolves to its first column. */ const resolveParent = ( parentId ) => { const parent = getContainer( parentId ); const type = parent.model.get( 'elType' ); if ( 'section' === type ) { const column = parent.model.get( 'elements' ).first(); if ( ! column ) { throw new Error( `Section "${ parentId }" has no column.` ); } return getContainer( column.id ); } if ( 'container' !== type && 'column' !== type && ! ATOMIC_BOXES.includes( type ) ) { throw new Error( `"${ parentId }" is a ${ type }. parent_id must be a box: container, section, column, or an Elementor 4 Flexbox / Div block / Grid.` ); } return parent; }; /** * New top-level wrapper at the end of the document: flexbox container, or section > column. */ const createWrapper = () => { const root = getDocument().container; if ( angie_integration_config.useContainer ) { return $e.run( 'document/elements/create', { container: root, model: { elType: 'container', settings: { flex_direction: 'column' } }, } ); } const section = $e.run( 'document/elements/create', { container: root, model: { elType: 'section' }, columns: 1, } ); return resolveParent( section.id ); }; /** * Group several commands into one undo step. */ const withHistory = ( title, fn ) => { let historyId = null; try { historyId = $e.internal( 'document/history/start-log', { type: 'add', title } ); } catch ( e ) { historyId = null; } try { return fn(); } finally { if ( historyId ) { $e.internal( 'document/history/end-log', { id: historyId } ); } } }; const getOpenDocument = () => { const doc = getDocument(); const docConfig = doc.config || {}; let selected = []; try { selected = window.elementor.selection.getElements().map( ( container ) => container.id ); } catch ( e ) { selected = []; } return { document_id: doc.id, type: docConfig.type, selected_ids: selected, elements: summarize( window.elementor.elements.toJSON( { remove: [ 'default', 'editSettings', 'defaultEditSettings' ] } ) ), note: 'Dynific widgets: dynific-editor-add-widgets / update-widget / move-element / remove-element. Structure: Elementor\'s own tools. ' + SAVE_NOTE, }; }; const addWidgets = async ( { widgets, parent_id: parentId, position } ) => { // Validate everything before touching the editor: all or nothing. const data = await request( 'aepro_ai_validate_widgets', { widgets: JSON.stringify( widgets ) } ); return withHistory( 'Dynific AI: add widgets', () => { const parent = parentId ? resolveParent( parentId ) : createWrapper(); const created = []; data.elements.forEach( ( element, index ) => { const options = {}; if ( Number.isInteger( position ) ) { options.at = position + index; } const container = $e.run( 'document/elements/create', { container: parent, model: { elType: 'widget', widgetType: element.widgetType, settings: plainSettings( element.settings ), }, options, } ); created.push( { id: container.id, widgetType: element.widgetType } ); } ); return { parent_id: parent.id, created, note: SAVE_NOTE }; } ); }; const updateWidget = async ( { element_id: id, settings } ) => { const container = getContainer( id ); const widgetType = container.model.get( 'widgetType' ); if ( 'widget' !== container.model.get( 'elType' ) || ! widgetType ) { throw new Error( `"${ id }" is a box, not a widget. Boxes (structure, sizes, styles) are changed with Elementor's own tools, e.g. elementor/manage-elements.` ); } const data = await request( 'aepro_ai_validate_settings', { widget: widgetType, settings: JSON.stringify( settings ) } ); $e.run( 'document/elements/settings', { container, settings: plainSettings( data.settings ), options: { external: true }, } ); return { id, widgetType, updated: Object.keys( plainSettings( data.settings ) ), note: SAVE_NOTE }; }; const moveElement = ( { element_id: id, parent_id: parentId, position } ) => { const container = getContainer( id ); const target = resolveParent( parentId ); const options = Number.isInteger( position ) ? { at: position } : {}; $e.run( 'document/elements/move', { container, target, options } ); return { id, parent_id: target.id, note: SAVE_NOTE }; }; const removeElement = ( { element_id: id } ) => { $e.run( 'document/elements/delete', { container: getContainer( id ) } ); return { removed: id, note: 'Removed (undo with Ctrl/Cmd+Z). ' + SAVE_NOTE }; }; /** * Elements and widgets in the open editor, to compare with what was saved. */ const countElements = ( elements, widgetsOnly = false ) => ( elements || [] ).reduce( ( count, element ) => count + ( ! widgetsOnly || 'widget' === element.elType ? 1 : 0 ) + countElements( element.elements, widgetsOnly ), 0 ); const hasUnsavedChanges = ( doc ) => !! ( doc.editor && doc.editor.isChanged ); const saveDocument = async ( { status } ) => { const doc = getDocument(); const command = 'publish' === status ? 'document/save/publish' : 'document/save/draft'; const live = window.elementor.elements.toJSON( { remove: [ 'default', 'editSettings', 'defaultEditSettings' ] } ); await $e.run( command, { document: doc } ); // Confirm against the database instead of trusting the command. const saved = await request( 'aepro_ai_document_state' ); const expected = { elements: countElements( live ), widgets: countElements( live, true ) }; if ( hasUnsavedChanges( doc ) ) { throw new Error( 'The editor still has unsaved changes after saving. Ask the user to click Publish/Update and check for an error message in the editor.' ); } if ( 'publish' === status ) { if ( 'publish' !== saved.status ) { throw new Error( `The document was saved but its status is "${ saved.status }", not publish. The user may not be allowed to publish; ask them to click Publish.` ); } if ( saved.elements !== expected.elements || saved.widgets !== expected.widgets ) { throw new Error( `Saved content does not match the editor (saved ${ saved.widgets } widgets, editor has ${ expected.widgets }). Ask the user to click Update and reload the page to check.` ); } } return { document_id: doc.id, status: saved.status, saved_widgets: saved.widgets, note: 'publish' === status ? `Published with all editor changes (${ saved.widgets } widgets saved and verified). If this is a Dynific template, check where it applies with dynific/get-template.` : 'Saved as draft. For a page that is already published, Elementor keeps the live version unchanged.', }; }; const createServer = () => { const server = new McpServer( { name: 'dynific-editor', title: 'Dynific Addons editor tools', version: angie_integration_config.version }, { instructions: angie_integration_config.instructions } ); server.registerTool( 'dynific-editor-get-open-document', { title: 'Dynific: get open document', description: 'Call FIRST before changing the template or page open in the Elementor editor. Returns its element tree (ids, widget types, changed settings) and the ids the user has selected ("this widget").', annotations: { readOnlyHint: true }, }, () => toResult( getOpenDocument ) ); server.registerTool( 'dynific-editor-add-widgets', { title: 'Dynific: add widgets to open document', description: 'Inserts Dynific widgets into the page, post or template open in the Elementor editor, live – into an existing box (parent_id) or, without parent_id, into a new box at the end. Structure (columns, rows) is built with Elementor\'s own tools. Listings work too, e.g. ae-post-blocks with settings {template: "<published block layout id>", ae_post_type: "<post type>"}. Widgets, setting keys, ACF fields and layout IDs are validated first; nothing is added if any is invalid.', inputSchema: { widgets: arrayType( objectType( { widget: stringType().regex( /^[a-z0-9_-]+$/i ).max( 100 ).describe( 'Widget name from dynific/list-widgets, e.g. ae-post-title' ), settings: settingsSchema, } ) ).min( 1 ).max( 30 ), parent_id: elementId.optional().describe( 'Box id from get-open-document: container, section, column, or an Elementor 4 Flexbox / Div block / Grid' ), position: numberType().int().min( 0 ).optional().describe( 'Index inside the parent; omit to append' ), }, }, ( args ) => toResult( () => addWidgets( args ) ) ); server.registerTool( 'dynific-editor-update-widget', { title: 'Dynific: update widget settings', description: 'Changes settings of one Dynific widget in the open editor, live. Send only the keys to change. Keys and select values are validated against dynific/get-widget-schema. Boxes are changed with Elementor\'s own tools.', inputSchema: { element_id: elementId.describe( 'Widget id from get-open-document' ), settings: recordType( anyType() ), }, }, ( args ) => toResult( () => updateWidget( args ) ) ); server.registerTool( 'dynific-editor-move-element', { title: 'Dynific: move element', description: 'Moves a widget or box to another box and/or position in the open editor – e.g. put the title above the image (same parent, new position) or move the rating into the left column (parent_id = that column\'s id from get-open-document).', inputSchema: { element_id: elementId, parent_id: elementId.describe( 'Target box id (container, section, column, or Elementor 4 Flexbox / Div block / Grid)' ), position: numberType().int().min( 0 ).optional(), }, }, ( args ) => toResult( () => moveElement( args ) ) ); server.registerTool( 'dynific-editor-remove-element', { title: 'Dynific: remove element', description: 'Removes a widget or container from the open editor. The user can undo it; confirm with the user before removing more than they asked for.', inputSchema: { element_id: elementId, }, annotations: { destructiveHint: true }, }, ( args ) => toResult( () => removeElement( args ) ) ); server.registerTool( 'dynific-editor-save-document', { title: 'Dynific: save or publish open document', description: 'USE THIS whenever the user is in the Elementor editor and says publish, save or update – never dynific/update-template for that. Clicks the editor\'s Publish/Update (status=publish) or Save Draft (status=draft), so every live change made in the editor is saved, then verifies the saved content matches the editor. status=publish makes it live – only when the user asked. To change where a Dynific template applies (post type, apply_global, specific posts) use dynific/update-template and dynific/assign-template-to-post (settings only).', inputSchema: { status: enumType( [ 'publish', 'draft' ] ).describe( 'publish = Publish/Update; draft = Save Draft' ), }, }, ( args ) => toResult( () => saveDocument( args ) ) ); return server; }; if ( angie_integration_config && angie_integration_config.ajaxUrl && angie_integration_config.nonce && window.$e ) { new dn() .registerLocalServer( { name: 'dynific-editor', version: angie_integration_config.version, description: 'Dynific Addons: change the template or page open in the Elementor editor live (add, update, move, remove Dynific widgets).', server: createServer(), } ) .then( () => window.console.debug( '[Dynific] Angie editor MCP server registered' ) ) .catch( ( error ) => window.console.debug( '[Dynific] Angie editor MCP server registration failed', error ) ); } /******/ })() ;
Save File
Cancel