'use strict'; var chunk3ZV6GYQI_cjs = require('./chunk-3ZV6GYQI.cjs'); var chunkMRD47GBP_cjs = require('./chunk-MRD47GBP.cjs'); var chunk3YQ7NWF6_cjs = require('./chunk-3YQ7NWF6.cjs'); var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs'); var agent = require('@mastra/core/agent'); var storage = require('@mastra/core/storage'); var features = require('@mastra/core/features'); var memory = require('@mastra/core/memory'); var observability = require('@mastra/core/observability'); var utils = require('@mastra/core/utils'); var diagnostics_channel = require('diagnostics_channel'); var tools = require('@mastra/core/tools'); var schema = require('@mastra/core/schema'); var child_process = require('child_process'); var promises = require('fs/promises'); var path = require('path'); var zod = require('zod'); var fs = require('fs'); var module$1 = require('module'); var util$1 = require('util'); var llm = require('@mastra/core/llm'); var os = require('os'); var workflows = require('@mastra/core/workflows'); var z4 = require('zod/v4'); var v3 = require('zod/v3'); function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var z4__namespace = /*#__PURE__*/_interopNamespace(z4); // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ignore/7.0.5/d6411cd18dd20fbb425503c2ba0ac12fc6b5c7b2b2481cbdc797c212eb8be050/node_modules/ignore/index.js var require_ignore = chunkO7I5CWRX_cjs.__commonJS({ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ignore/7.0.5/d6411cd18dd20fbb425503c2ba0ac12fc6b5c7b2b2481cbdc797c212eb8be050/node_modules/ignore/index.js"(exports, module) { function makeArray(subject) { return Array.isArray(subject) ? subject : [subject]; } var UNDEFINED = void 0; var EMPTY = ""; var SPACE4 = " "; var ESCAPE = "\\"; var REGEX_TEST_BLANK_LINE = /^\s+$/; var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/; var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; var REGEX_SPLITALL_CRLF = /\r?\n/g; var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/; var REGEX_TEST_TRAILING_SLASH = /\/$/; var SLASH = "/"; var TMP_KEY_IGNORE = "node-ignore"; if (typeof Symbol !== "undefined") { TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore"); } var KEY_IGNORE = TMP_KEY_IGNORE; var define = (object7, key, value) => { Object.defineProperty(object7, key, { value }); return value; }; var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; var RETURN_FALSE = () => false; var sanitizeRange = (range) => range.replace( REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY ); var cleanRangeBackSlash = (slashes) => { const { length } = slashes; return slashes.slice(0, length - length % 2); }; var REPLACERS = [ [ // Remove BOM // TODO: // Other similar zero-width characters? /^\uFEFF/, () => EMPTY ], // > Trailing spaces are ignored unless they are quoted with backslash ("\") [ // (a\ ) -> (a ) // (a ) -> (a) // (a ) -> (a) // (a \ ) -> (a ) /((?:\\\\)*?)(\\?\s+)$/, (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE4 : EMPTY) ], // Replace (\ ) with ' ' // (\ ) -> ' ' // (\\ ) -> '\\ ' // (\\\ ) -> '\\ ' [ /(\\+?)\s/g, (_, m1) => { const { length } = m1; return m1.slice(0, length - length % 2) + SPACE4; } ], // Escape metacharacters // which is written down by users but means special for regular expressions. // > There are 12 characters with special meanings: // > - the backslash \, // > - the caret ^, // > - the dollar sign $, // > - the period or dot ., // > - the vertical bar or pipe symbol |, // > - the question mark ?, // > - the asterisk or star *, // > - the plus sign +, // > - the opening parenthesis (, // > - the closing parenthesis ), // > - and the opening square bracket [, // > - the opening curly brace {, // > These special characters are often called "metacharacters". [ /[\\$.|*+(){^]/g, (match) => `\\${match}` ], [ // > a question mark (?) matches a single character /(?!\\)\?/g, () => "[^/]" ], // leading slash [ // > A leading slash matches the beginning of the pathname. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". // A leading slash matches the beginning of the pathname /^\//, () => "^" ], // replace special metacharacter slash after the leading slash [ /\//g, () => "\\/" ], [ // > A leading "**" followed by a slash means match in all directories. // > For example, "**/foo" matches file or directory "foo" anywhere, // > the same as pattern "foo". // > "**/foo/bar" matches file or directory "bar" anywhere that is directly // > under directory "foo". // Notice that the '*'s have been replaced as '\\*' /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo' () => "^(?:.*\\/)?" ], // starting [ // there will be no leading '/' // (which has been replaced by section "leading slash") // If starts with '**', adding a '^' to the regular expression also works /^(?=[^^])/, function startingReplacer() { return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^"; } ], // two globstars [ // Use lookahead assertions so that we could match more than one `'/**'` /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories // should not use '*', or it will be replaced by the next replacer // Check if it is not the last `'/**'` (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+" ], // normal intermediate wildcards [ // Never replace escaped '*' // ignore rule '\*' will match the path '*' // 'abc.*/' -> go // 'abc.*' -> skip this rule, // coz trailing single wildcard will be handed by [trailing wildcard] /(^|[^\\]+)(\\\*)+(?=.+)/g, // '*.js' matches '.js' // '*.js' doesn't match 'abc' (_, p1, p2) => { const unescaped = p2.replace(/\\\*/g, "[^\\/]*"); return p1 + unescaped; } ], [ // unescape, revert step 3 except for back slash // For example, if a user escape a '\\*', // after step 3, the result will be '\\\\\\*' /\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE ], [ // '\\\\' -> '\\' /\\\\/g, () => ESCAPE ], [ // > The range notation, e.g. [a-zA-Z], // > can be used to match one of the characters in a range. // `\` is escaped by step 3 /(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]" ], // ending [ // 'js' will not match 'js.' // 'ab' will not match 'abc' /(?:[^*])$/, // WTF! // https://git-scm.com/docs/gitignore // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) // which re-fixes #24, #38 // > If there is a separator at the end of the pattern then the pattern // > will only match directories, otherwise the pattern can match both // > files and directories. // 'js*' will not match 'a.js' // 'js/' will not match 'a.js' // 'js' will match 'a.js' and 'a.js/' (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)` ] ]; var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/; var MODE_IGNORE = "regex"; var MODE_CHECK_IGNORE = "checkRegex"; var UNDERSCORE = "_"; var TRAILING_WILD_CARD_REPLACERS = { [MODE_IGNORE](_, p1) { const prefix = p1 ? `${p1}[^/]+` : "[^/]*"; return `${prefix}(?=$|\\/$)`; }, [MODE_CHECK_IGNORE](_, p1) { const prefix = p1 ? `${p1}[^/]*` : "[^/]*"; return `${prefix}(?=$|\\/$)`; } }; var makeRegexPrefix = (pattern) => REPLACERS.reduce( (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)), pattern ); var isString = (subject) => typeof subject === "string"; var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0; var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean); var IgnoreRule = class { constructor(pattern, mark, body, ignoreCase, negative, prefix) { this.pattern = pattern; this.mark = mark; this.negative = negative; define(this, "body", body); define(this, "ignoreCase", ignoreCase); define(this, "regexPrefix", prefix); } get regex() { const key = UNDERSCORE + MODE_IGNORE; if (this[key]) { return this[key]; } return this._make(MODE_IGNORE, key); } get checkRegex() { const key = UNDERSCORE + MODE_CHECK_IGNORE; if (this[key]) { return this[key]; } return this._make(MODE_CHECK_IGNORE, key); } _make(mode, key) { const str = this.regexPrefix.replace( REGEX_REPLACE_TRAILING_WILDCARD, // It does not need to bind pattern TRAILING_WILD_CARD_REPLACERS[mode] ); const regex = this.ignoreCase ? new RegExp(str, "i") : new RegExp(str); return define(this, key, regex); } }; var createRule = ({ pattern, mark }, ignoreCase) => { let negative = false; let body = pattern; if (body.indexOf("!") === 0) { negative = true; body = body.substr(1); } body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#"); const regexPrefix = makeRegexPrefix(body); return new IgnoreRule( pattern, mark, body, ignoreCase, negative, regexPrefix ); }; var RuleManager = class { constructor(ignoreCase) { this._ignoreCase = ignoreCase; this._rules = []; } _add(pattern) { if (pattern && pattern[KEY_IGNORE]) { this._rules = this._rules.concat(pattern._rules._rules); this._added = true; return; } if (isString(pattern)) { pattern = { pattern }; } if (checkPattern(pattern.pattern)) { const rule = createRule(pattern, this._ignoreCase); this._added = true; this._rules.push(rule); } } // @param {Array | string | Ignore} pattern add(pattern) { this._added = false; makeArray( isString(pattern) ? splitPattern(pattern) : pattern ).forEach(this._add, this); return this._added; } // Test one single path without recursively checking parent directories // // - checkUnignored `boolean` whether should check if the path is unignored, // setting `checkUnignored` to `false` could reduce additional // path matching. // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE` // @returns {TestResult} true if a file is ignored test(path, checkUnignored, mode) { let ignored = false; let unignored = false; let matchedRule; this._rules.forEach((rule) => { const { negative } = rule; if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { return; } const matched = rule[mode].test(path); if (!matched) { return; } ignored = !negative; unignored = negative; matchedRule = negative ? UNDEFINED : rule; }); const ret = { ignored, unignored }; if (matchedRule) { ret.rule = matchedRule; } return ret; } }; var throwError = (message, Ctor) => { throw new Ctor(message); }; var checkPath = (path, originalPath, doThrow) => { if (!isString(path)) { return doThrow( `path must be a string, but got \`${originalPath}\``, TypeError ); } if (!path) { return doThrow(`path must not be empty`, TypeError); } if (checkPath.isNotRelative(path)) { const r = "`path.relative()`d"; return doThrow( `path should be a ${r} string, but got "${originalPath}"`, RangeError ); } return true; }; var isNotRelative = (path) => REGEX_TEST_INVALID_PATH.test(path); checkPath.isNotRelative = isNotRelative; checkPath.convert = (p) => p; var Ignore = class { constructor({ ignorecase = true, ignoreCase = ignorecase, allowRelativePaths = false } = {}) { define(this, KEY_IGNORE, true); this._rules = new RuleManager(ignoreCase); this._strictPathCheck = !allowRelativePaths; this._initCache(); } _initCache() { this._ignoreCache = /* @__PURE__ */ Object.create(null); this._testCache = /* @__PURE__ */ Object.create(null); } add(pattern) { if (this._rules.add(pattern)) { this._initCache(); } return this; } // legacy addPattern(pattern) { return this.add(pattern); } // @returns {TestResult} _test(originalPath, cache, checkUnignored, slices) { const path = originalPath && checkPath.convert(originalPath); checkPath( path, originalPath, this._strictPathCheck ? throwError : RETURN_FALSE ); return this._t(path, cache, checkUnignored, slices); } checkIgnore(path) { if (!REGEX_TEST_TRAILING_SLASH.test(path)) { return this.test(path); } const slices = path.split(SLASH).filter(Boolean); slices.pop(); if (slices.length) { const parent = this._t( slices.join(SLASH) + SLASH, this._testCache, true, slices ); if (parent.ignored) { return parent; } } return this._rules.test(path, false, MODE_CHECK_IGNORE); } _t(path, cache, checkUnignored, slices) { if (path in cache) { return cache[path]; } if (!slices) { slices = path.split(SLASH).filter(Boolean); } slices.pop(); if (!slices.length) { return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE); } const parent = this._t( slices.join(SLASH) + SLASH, cache, checkUnignored, slices ); return cache[path] = parent.ignored ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE); } ignores(path) { return this._test(path, this._ignoreCache, false).ignored; } createFilter() { return (path) => !this.ignores(path); } filter(paths) { return makeArray(paths).filter(this.createFilter()); } // @returns {TestResult} test(path) { return this._test(path, this._testCache, true); } }; var factory = (options) => new Ignore(options); var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE); var setupWindows = () => { const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/"); checkPath.convert = makePosix; const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; checkPath.isNotRelative = (path) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); }; if ( // Detect `process` so that it can run in browsers. typeof process !== "undefined" && process.platform === "win32" ) { setupWindows(); } module.exports = factory; factory.default = factory; module.exports.isPathValid = isPathValid; define(module.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows); } }); // ../memory/dist/chunk-PZ5AY32C.js var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name4 in all) __defProp(target, name4, { get: all[name4], enumerable: true }); }; var E_CANCELED = new Error("request for lock canceled"); var __awaiter$2 = function(thisArg, _arguments, P2, generator) { function adopt(value) { return value instanceof P2 ? value : new P2(function(resolve5) { resolve5(value); }); } return new (P2 || (P2 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e2) { reject(e2); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e2) { reject(e2); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Semaphore = class { constructor(_value, _cancelError = E_CANCELED) { this._value = _value; this._cancelError = _cancelError; this._queue = []; this._weightedWaiters = []; } acquire(weight = 1, priority = 0) { if (weight <= 0) throw new Error(`invalid weight ${weight}: must be positive`); return new Promise((resolve5, reject) => { const task = { resolve: resolve5, reject, weight, priority }; const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority); if (i === -1 && weight <= this._value) { this._dispatchItem(task); } else { this._queue.splice(i + 1, 0, task); } }); } runExclusive(callback_1) { return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) { const [value, release] = yield this.acquire(weight, priority); try { return yield callback(value); } finally { release(); } }); } waitForUnlock(weight = 1, priority = 0) { if (weight <= 0) throw new Error(`invalid weight ${weight}: must be positive`); if (this._couldLockImmediately(weight, priority)) { return Promise.resolve(); } else { return new Promise((resolve5) => { if (!this._weightedWaiters[weight - 1]) this._weightedWaiters[weight - 1] = []; insertSorted(this._weightedWaiters[weight - 1], { resolve: resolve5, priority }); }); } } isLocked() { return this._value <= 0; } getValue() { return this._value; } setValue(value) { this._value = value; this._dispatchQueue(); } release(weight = 1) { if (weight <= 0) throw new Error(`invalid weight ${weight}: must be positive`); this._value += weight; this._dispatchQueue(); } cancel() { this._queue.forEach((entry) => entry.reject(this._cancelError)); this._queue = []; } _dispatchQueue() { this._drainUnlockWaiters(); while (this._queue.length > 0 && this._queue[0].weight <= this._value) { this._dispatchItem(this._queue.shift()); this._drainUnlockWaiters(); } } _dispatchItem(item) { const previousValue = this._value; this._value -= item.weight; item.resolve([previousValue, this._newReleaser(item.weight)]); } _newReleaser(weight) { let called = false; return () => { if (called) return; called = true; this.release(weight); }; } _drainUnlockWaiters() { if (this._queue.length === 0) { for (let weight = this._value; weight > 0; weight--) { const waiters = this._weightedWaiters[weight - 1]; if (!waiters) continue; waiters.forEach((waiter) => waiter.resolve()); this._weightedWaiters[weight - 1] = []; } } else { const queuedPriority = this._queue[0].priority; for (let weight = this._value; weight > 0; weight--) { const waiters = this._weightedWaiters[weight - 1]; if (!waiters) continue; const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority); (i === -1 ? waiters : waiters.splice(0, i)).forEach(((waiter) => waiter.resolve())); } } } _couldLockImmediately(weight, priority) { return (this._queue.length === 0 || this._queue[0].priority < priority) && weight <= this._value; } }; function insertSorted(a, v) { const i = findIndexFromEnd(a, (other) => v.priority <= other.priority); a.splice(i + 1, 0, v); } function findIndexFromEnd(a, predicate) { for (let i = a.length - 1; i >= 0; i--) { if (predicate(a[i])) { return i; } } return -1; } var __awaiter$1 = function(thisArg, _arguments, P2, generator) { function adopt(value) { return value instanceof P2 ? value : new P2(function(resolve5) { resolve5(value); }); } return new (P2 || (P2 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e2) { reject(e2); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e2) { reject(e2); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Mutex = class { constructor(cancelError) { this._semaphore = new Semaphore(1, cancelError); } acquire() { return __awaiter$1(this, arguments, void 0, function* (priority = 0) { const [, releaser] = yield this._semaphore.acquire(1, priority); return releaser; }); } runExclusive(callback, priority = 0) { return this._semaphore.runExclusive(() => callback(), 1, priority); } isLocked() { return this._semaphore.isLocked(); } waitForUnlock(priority = 0) { return this._semaphore.waitForUnlock(1, priority); } release() { if (this._semaphore.isLocked()) this._semaphore.release(); } cancel() { return this._semaphore.cancel(); } }; var S = diagnostics_channel.channel("lru-cache:metrics"); var W = diagnostics_channel.tracingChannel("lru-cache"); var C = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date; var D = () => S.hasSubscribers || W.hasSubscribers; var U = /* @__PURE__ */ new Set(); var L = typeof process == "object" && process ? process : {}; var P = (u3, e2, t, i) => { typeof L.emitWarning == "function" ? L.emitWarning(u3, e2, t, i) : console.error(`[${t}] ${e2}: ${u3}`); }; var H = (u3) => !U.has(u3); var F = (u3) => !!u3 && u3 === Math.floor(u3) && u3 > 0 && isFinite(u3); var j = (u3) => F(u3) ? u3 <= Math.pow(2, 8) ? Uint8Array : u3 <= Math.pow(2, 16) ? Uint16Array : u3 <= Math.pow(2, 32) ? Uint32Array : u3 <= Number.MAX_SAFE_INTEGER ? O : null : null; var O = class extends Array { constructor(e2) { super(e2), this.fill(0); } }; var R = class u { heap; length; static #o = false; static create(e2) { let t = j(e2); if (!t) return []; u.#o = true; let i = new u(e2, t); return u.#o = false, i; } constructor(e2, t) { if (!u.#o) throw new TypeError("instantiate Stack using Stack.create(n)"); this.heap = new t(e2), this.length = 0; } push(e2) { this.heap[this.length++] = e2; } pop() { return this.heap[--this.length]; } }; var M = class u2 { #o; #u; #w; #x; #S; #M; #U; #m; get perf() { return this.#m; } ttl; ttlResolution; ttlAutopurge; updateAgeOnGet; updateAgeOnHas; allowStale; noDisposeOnSet; noUpdateTTL; maxEntrySize; sizeCalculation; noDeleteOnFetchRejection; noDeleteOnStaleGet; allowStaleOnFetchAbort; allowStaleOnFetchRejection; ignoreFetchAbort; #n; #b; #s; #i; #t; #a; #c; #l; #h; #y; #r; #_; #F; #d; #g; #T; #W; #f; #j; static unsafeExposeInternals(e2) { return { starts: e2.#F, ttls: e2.#d, autopurgeTimers: e2.#g, sizes: e2.#_, keyMap: e2.#s, keyList: e2.#i, valList: e2.#t, next: e2.#a, prev: e2.#c, get head() { return e2.#l; }, get tail() { return e2.#h; }, free: e2.#y, isBackgroundFetch: (t) => e2.#e(t), backgroundFetch: (t, i, s, n) => e2.#P(t, i, s, n), moveToTail: (t) => e2.#L(t), indexes: (t) => e2.#A(t), rindexes: (t) => e2.#z(t), isStale: (t) => e2.#p(t) }; } get max() { return this.#o; } get maxSize() { return this.#u; } get calculatedSize() { return this.#b; } get size() { return this.#n; } get fetchMethod() { return this.#M; } get memoMethod() { return this.#U; } get dispose() { return this.#w; } get onInsert() { return this.#x; } get disposeAfter() { return this.#S; } constructor(e2) { let { max: t = 0, ttl: i, ttlResolution: s = 1, ttlAutopurge: n, updateAgeOnGet: o, updateAgeOnHas: r, allowStale: h, dispose: l, onInsert: c, disposeAfter: f, noDisposeOnSet: g, noUpdateTTL: p, maxSize: T = 0, maxEntrySize: w = 0, sizeCalculation: y, fetchMethod: a, memoMethod: m, noDeleteOnFetchRejection: _, noDeleteOnStaleGet: b, allowStaleOnFetchRejection: d, allowStaleOnFetchAbort: A, ignoreFetchAbort: z3, perf: x } = e2; if (x !== void 0 && typeof x?.now != "function") throw new TypeError("perf option must have a now() method if specified"); if (this.#m = x ?? C, t !== 0 && !F(t)) throw new TypeError("max option must be a nonnegative integer"); let v = t ? j(t) : Array; if (!v) throw new Error("invalid max value: " + t); if (this.#o = t, this.#u = T, this.maxEntrySize = w || this.#u, this.sizeCalculation = y, this.sizeCalculation) { if (!this.#u && !this.maxEntrySize) throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize"); if (typeof this.sizeCalculation != "function") throw new TypeError("sizeCalculation set to non-function"); } if (m !== void 0 && typeof m != "function") throw new TypeError("memoMethod must be a function if defined"); if (this.#U = m, a !== void 0 && typeof a != "function") throw new TypeError("fetchMethod must be a function if specified"); if (this.#M = a, this.#W = !!a, this.#s = /* @__PURE__ */ new Map(), this.#i = Array.from({ length: t }).fill(void 0), this.#t = Array.from({ length: t }).fill(void 0), this.#a = new v(t), this.#c = new v(t), this.#l = 0, this.#h = 0, this.#y = R.create(t), this.#n = 0, this.#b = 0, typeof l == "function" && (this.#w = l), typeof c == "function" && (this.#x = c), typeof f == "function" ? (this.#S = f, this.#r = []) : (this.#S = void 0, this.#r = void 0), this.#T = !!this.#w, this.#j = !!this.#x, this.#f = !!this.#S, this.noDisposeOnSet = !!g, this.noUpdateTTL = !!p, this.noDeleteOnFetchRejection = !!_, this.allowStaleOnFetchRejection = !!d, this.allowStaleOnFetchAbort = !!A, this.ignoreFetchAbort = !!z3, this.maxEntrySize !== 0) { if (this.#u !== 0 && !F(this.#u)) throw new TypeError("maxSize must be a positive integer if specified"); if (!F(this.maxEntrySize)) throw new TypeError("maxEntrySize must be a positive integer if specified"); this.#X(); } if (this.allowStale = !!h, this.noDeleteOnStaleGet = !!b, this.updateAgeOnGet = !!o, this.updateAgeOnHas = !!r, this.ttlResolution = F(s) || s === 0 ? s : 1, this.ttlAutopurge = !!n, this.ttl = i || 0, this.ttl) { if (!F(this.ttl)) throw new TypeError("ttl must be a positive integer if specified"); this.#H(); } if (this.#o === 0 && this.ttl === 0 && this.#u === 0) throw new TypeError("At least one of max, maxSize, or ttl is required"); if (!this.ttlAutopurge && !this.#o && !this.#u) { let E = "LRU_CACHE_UNBOUNDED"; H(E) && (U.add(E), P("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", E, u2)); } } getRemainingTTL(e2) { return this.#s.has(e2) ? 1 / 0 : 0; } #H() { let e2 = new O(this.#o), t = new O(this.#o); this.#d = e2, this.#F = t; let i = this.ttlAutopurge ? Array.from({ length: this.#o }) : void 0; this.#g = i, this.#N = (r, h, l = this.#m.now()) => { t[r] = h !== 0 ? l : 0, e2[r] = h, s(r, h); }, this.#D = (r) => { t[r] = e2[r] !== 0 ? this.#m.now() : 0, s(r, e2[r]); }; let s = this.ttlAutopurge ? (r, h) => { if (i?.[r] && (clearTimeout(i[r]), i[r] = void 0), h && h !== 0 && i) { let l = setTimeout(() => { this.#p(r) && this.#v(this.#i[r], "expire"); }, h + 1); l.unref && l.unref(), i[r] = l; } } : () => { }; this.#E = (r, h) => { if (e2[h]) { let l = e2[h], c = t[h]; if (!l || !c) return; r.ttl = l, r.start = c, r.now = n || o(); let f = r.now - c; r.remainingTTL = l - f; } }; let n = 0, o = () => { let r = this.#m.now(); if (this.ttlResolution > 0) { n = r; let h = setTimeout(() => n = 0, this.ttlResolution); h.unref && h.unref(); } return r; }; this.getRemainingTTL = (r) => { let h = this.#s.get(r); if (h === void 0) return 0; let l = e2[h], c = t[h]; if (!l || !c) return 1 / 0; let f = (n || o()) - c; return l - f; }, this.#p = (r) => { let h = t[r], l = e2[r]; return !!l && !!h && (n || o()) - h > l; }; } #D = () => { }; #E = () => { }; #N = () => { }; #p = () => false; #X() { let e2 = new O(this.#o); this.#b = 0, this.#_ = e2, this.#R = (t) => { this.#b -= e2[t], e2[t] = 0; }, this.#k = (t, i, s, n) => { if (this.#e(i)) return 0; if (!F(s)) if (n) { if (typeof n != "function") throw new TypeError("sizeCalculation must be a function"); if (s = n(i, t), !F(s)) throw new TypeError("sizeCalculation return invalid (expect positive integer)"); } else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set."); return s; }, this.#I = (t, i, s) => { if (e2[t] = i, this.#u) { let n = this.#u - e2[t]; for (; this.#b > n; ) this.#G(true); } this.#b += e2[t], s && (s.entrySize = i, s.totalCalculatedSize = this.#b); }; } #R = (e2) => { }; #I = (e2, t, i) => { }; #k = (e2, t, i, s) => { if (i || s) throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache"); return 0; }; *#A({ allowStale: e2 = this.allowStale } = {}) { if (this.#n) for (let t = this.#h; this.#V(t) && ((e2 || !this.#p(t)) && (yield t), t !== this.#l); ) t = this.#c[t]; } *#z({ allowStale: e2 = this.allowStale } = {}) { if (this.#n) for (let t = this.#l; this.#V(t) && ((e2 || !this.#p(t)) && (yield t), t !== this.#h); ) t = this.#a[t]; } #V(e2) { return e2 !== void 0 && this.#s.get(this.#i[e2]) === e2; } *entries() { for (let e2 of this.#A()) this.#t[e2] !== void 0 && this.#i[e2] !== void 0 && !this.#e(this.#t[e2]) && (yield [this.#i[e2], this.#t[e2]]); } *rentries() { for (let e2 of this.#z()) this.#t[e2] !== void 0 && this.#i[e2] !== void 0 && !this.#e(this.#t[e2]) && (yield [this.#i[e2], this.#t[e2]]); } *keys() { for (let e2 of this.#A()) { let t = this.#i[e2]; t !== void 0 && !this.#e(this.#t[e2]) && (yield t); } } *rkeys() { for (let e2 of this.#z()) { let t = this.#i[e2]; t !== void 0 && !this.#e(this.#t[e2]) && (yield t); } } *values() { for (let e2 of this.#A()) this.#t[e2] !== void 0 && !this.#e(this.#t[e2]) && (yield this.#t[e2]); } *rvalues() { for (let e2 of this.#z()) this.#t[e2] !== void 0 && !this.#e(this.#t[e2]) && (yield this.#t[e2]); } [Symbol.iterator]() { return this.entries(); } [Symbol.toStringTag] = "LRUCache"; find(e2, t = {}) { for (let i of this.#A()) { let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s; if (n !== void 0 && e2(n, this.#i[i], this)) return this.#C(this.#i[i], t); } } forEach(e2, t = this) { for (let i of this.#A()) { let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s; n !== void 0 && e2.call(t, n, this.#i[i], this); } } rforEach(e2, t = this) { for (let i of this.#z()) { let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s; n !== void 0 && e2.call(t, n, this.#i[i], this); } } purgeStale() { let e2 = false; for (let t of this.#z({ allowStale: true })) this.#p(t) && (this.#v(this.#i[t], "expire"), e2 = true); return e2; } info(e2) { let t = this.#s.get(e2); if (t === void 0) return; let i = this.#t[t], s = this.#e(i) ? i.__staleWhileFetching : i; if (s === void 0) return; let n = { value: s }; if (this.#d && this.#F) { let o = this.#d[t], r = this.#F[t]; if (o && r) { let h = o - (this.#m.now() - r); n.ttl = h, n.start = Date.now(); } } return this.#_ && (n.size = this.#_[t]), n; } dump() { let e2 = []; for (let t of this.#A({ allowStale: true })) { let i = this.#i[t], s = this.#t[t], n = this.#e(s) ? s.__staleWhileFetching : s; if (n === void 0 || i === void 0) continue; let o = { value: n }; if (this.#d && this.#F) { o.ttl = this.#d[t]; let r = this.#m.now() - this.#F[t]; o.start = Math.floor(Date.now() - r); } this.#_ && (o.size = this.#_[t]), e2.unshift([i, o]); } return e2; } load(e2) { this.clear(); for (let [t, i] of e2) { if (i.start) { let s = Date.now() - i.start; i.start = this.#m.now() - s; } this.#O(t, i.value, i); } } set(e2, t, i = {}) { let { status: s = S.hasSubscribers ? {} : void 0 } = i; i.status = s, s && (s.op = "set", s.key = e2, t !== void 0 && (s.value = t)); let n = this.#O(e2, t, i); return s && S.hasSubscribers && S.publish(s), n; } #O(e2, t, i = {}) { let { ttl: s = this.ttl, start: n, noDisposeOnSet: o = this.noDisposeOnSet, sizeCalculation: r = this.sizeCalculation, status: h } = i; if (t === void 0) return h && (h.set = "deleted"), this.delete(e2), this; let { noUpdateTTL: l = this.noUpdateTTL } = i; h && !this.#e(t) && (h.value = t); let c = this.#k(e2, t, i.size || 0, r, h); if (this.maxEntrySize && c > this.maxEntrySize) return this.#v(e2, "set"), h && (h.set = "miss", h.maxEntrySizeExceeded = true), this; let f = this.#n === 0 ? void 0 : this.#s.get(e2); if (f === void 0) f = this.#n === 0 ? this.#h : this.#y.length !== 0 ? this.#y.pop() : this.#n === this.#o ? this.#G(false) : this.#n, this.#i[f] = e2, this.#t[f] = t, this.#s.set(e2, f), this.#a[this.#h] = f, this.#c[f] = this.#h, this.#h = f, this.#n++, this.#I(f, c, h), h && (h.set = "add"), l = false, this.#j && this.#x?.(t, e2, "add"); else { this.#L(f); let g = this.#t[f]; if (t !== g) { if (this.#W && this.#e(g)) { g.__abortController.abort(new Error("replaced")); let { __staleWhileFetching: p } = g; p !== void 0 && !o && (this.#T && this.#w?.(p, e2, "set"), this.#f && this.#r?.push([p, e2, "set"])); } else o || (this.#T && this.#w?.(g, e2, "set"), this.#f && this.#r?.push([g, e2, "set"])); if (this.#R(f), this.#I(f, c, h), this.#t[f] = t, h) { h.set = "replace"; let p = g && this.#e(g) ? g.__staleWhileFetching : g; p !== void 0 && (h.oldValue = p); } } else h && (h.set = "update"); this.#j && this.onInsert?.(t, e2, t === g ? "update" : "replace"); } if (s !== 0 && !this.#d && this.#H(), this.#d && (l || this.#N(f, s, n), h && this.#E(h, f)), !o && this.#f && this.#r) { let g = this.#r, p; for (; p = g?.shift(); ) this.#S?.(...p); } return this; } pop() { try { for (; this.#n; ) { let e2 = this.#t[this.#l]; if (this.#G(true), this.#e(e2)) { if (e2.__staleWhileFetching) return e2.__staleWhileFetching; } else if (e2 !== void 0) return e2; } } finally { if (this.#f && this.#r) { let e2 = this.#r, t; for (; t = e2?.shift(); ) this.#S?.(...t); } } } #G(e2) { let t = this.#l, i = this.#i[t], s = this.#t[t]; return this.#W && this.#e(s) ? s.__abortController.abort(new Error("evicted")) : (this.#T || this.#f) && (this.#T && this.#w?.(s, i, "evict"), this.#f && this.#r?.push([s, i, "evict"])), this.#R(t), this.#g?.[t] && (clearTimeout(this.#g[t]), this.#g[t] = void 0), e2 && (this.#i[t] = void 0, this.#t[t] = void 0, this.#y.push(t)), this.#n === 1 ? (this.#l = this.#h = 0, this.#y.length = 0) : this.#l = this.#a[t], this.#s.delete(i), this.#n--, t; } has(e2, t = {}) { let { status: i = S.hasSubscribers ? {} : void 0 } = t; t.status = i, i && (i.op = "has", i.key = e2); let s = this.#Y(e2, t); return S.hasSubscribers && S.publish(i), s; } #Y(e2, t = {}) { let { updateAgeOnHas: i = this.updateAgeOnHas, status: s } = t, n = this.#s.get(e2); if (n !== void 0) { let o = this.#t[n]; if (this.#e(o) && o.__staleWhileFetching === void 0) return false; if (this.#p(n)) s && (s.has = "stale", this.#E(s, n)); else return i && this.#D(n), s && (s.has = "hit", this.#E(s, n)), true; } else s && (s.has = "miss"); return false; } peek(e2, t = {}) { let { status: i = D() ? {} : void 0 } = t; i && (i.op = "peek", i.key = e2), t.status = i; let s = this.#J(e2, t); return S.hasSubscribers && S.publish(i), s; } #J(e2, t) { let { status: i, allowStale: s = this.allowStale } = t, n = this.#s.get(e2); if (n === void 0 || !s && this.#p(n)) { i && (i.peek = n === void 0 ? "miss" : "stale"); return; } let o = this.#t[n], r = this.#e(o) ? o.__staleWhileFetching : o; return i && (r !== void 0 ? (i.peek = "hit", i.value = r) : i.peek = "miss"), r; } #P(e2, t, i, s) { let n = t === void 0 ? void 0 : this.#t[t]; if (this.#e(n)) return n; let o = new AbortController(), { signal: r } = i; r?.addEventListener("abort", () => o.abort(r.reason), { signal: o.signal }); let h = { signal: o.signal, options: i, context: s }, l = (w, y = false) => { let { aborted: a } = o.signal, m = i.ignoreFetchAbort && w !== void 0, _ = i.ignoreFetchAbort || !!(i.allowStaleOnFetchAbort && w !== void 0); if (i.status && (a && !y ? (i.status.fetchAborted = true, i.status.fetchError = o.signal.reason, m && (i.status.fetchAbortIgnored = true)) : i.status.fetchResolved = true), a && !m && !y) return f(o.signal.reason, _); let b = p, d = this.#t[t]; return (d === p || d === void 0 && m && y) && (w === void 0 ? b.__staleWhileFetching !== void 0 ? this.#t[t] = b.__staleWhileFetching : this.#v(e2, "fetch") : (i.status && (i.status.fetchUpdated = true), this.#O(e2, w, h.options))), w; }, c = (w) => (i.status && (i.status.fetchRejected = true, i.status.fetchError = w), f(w, false)), f = (w, y) => { let { aborted: a } = o.signal, m = a && i.allowStaleOnFetchAbort, _ = m || i.allowStaleOnFetchRejection, b = _ || i.noDeleteOnFetchRejection, d = p; if (this.#t[t] === p && (!b || !y && d.__staleWhileFetching === void 0 ? this.#v(e2, "fetch") : m || (this.#t[t] = d.__staleWhileFetching)), _) return i.status && d.__staleWhileFetching !== void 0 && (i.status.returnedStale = true), d.__staleWhileFetching; if (d.__returned === d) throw w; }, g = (w, y) => { let a = this.#M?.(e2, n, h); a && a instanceof Promise && a.then((m) => w(m === void 0 ? void 0 : m), y), o.signal.addEventListener("abort", () => { (!i.ignoreFetchAbort || i.allowStaleOnFetchAbort) && (w(void 0), i.allowStaleOnFetchAbort && (w = (m) => l(m, true))); }); }; i.status && (i.status.fetchDispatched = true); let p = new Promise(g).then(l, c), T = Object.assign(p, { __abortController: o, __staleWhileFetching: n, __returned: void 0 }); return t === void 0 ? (this.#O(e2, T, { ...h.options, status: void 0 }), t = this.#s.get(e2)) : this.#t[t] = T, T; } #e(e2) { if (!this.#W) return false; let t = e2; return !!t && t instanceof Promise && t.hasOwnProperty("__staleWhileFetching") && t.__abortController instanceof AbortController; } fetch(e2, t = {}) { let i = W.hasSubscribers, { status: s = D() ? {} : void 0 } = t; t.status = s, s && t.context && (s.context = t.context); let n = this.#B(e2, t); return s && i && (s.trace = true, W.tracePromise(() => n, s).catch(() => { })), n; } async #B(e2, t = {}) { let { allowStale: i = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n = this.noDeleteOnStaleGet, ttl: o = this.ttl, noDisposeOnSet: r = this.noDisposeOnSet, size: h = 0, sizeCalculation: l = this.sizeCalculation, noUpdateTTL: c = this.noUpdateTTL, noDeleteOnFetchRejection: f = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection: g = this.allowStaleOnFetchRejection, ignoreFetchAbort: p = this.ignoreFetchAbort, allowStaleOnFetchAbort: T = this.allowStaleOnFetchAbort, context: w, forceRefresh: y = false, status: a, signal: m } = t; if (a && (a.op = "fetch", a.key = e2, y && (a.forceRefresh = true)), !this.#W) return a && (a.fetch = "get"), this.#C(e2, { allowStale: i, updateAgeOnGet: s, noDeleteOnStaleGet: n, status: a }); let _ = { allowStale: i, updateAgeOnGet: s, noDeleteOnStaleGet: n, ttl: o, noDisposeOnSet: r, size: h, sizeCalculation: l, noUpdateTTL: c, noDeleteOnFetchRejection: f, allowStaleOnFetchRejection: g, allowStaleOnFetchAbort: T, ignoreFetchAbort: p, status: a, signal: m }, b = this.#s.get(e2); if (b === void 0) { a && (a.fetch = "miss"); let d = this.#P(e2, b, _, w); return d.__returned = d; } else { let d = this.#t[b]; if (this.#e(d)) { let E = i && d.__staleWhileFetching !== void 0; return a && (a.fetch = "inflight", E && (a.returnedStale = true)), E ? d.__staleWhileFetching : d.__returned = d; } let A = this.#p(b); if (!y && !A) return a && (a.fetch = "hit"), this.#L(b), s && this.#D(b), a && this.#E(a, b), d; let z3 = this.#P(e2, b, _, w), v = z3.__staleWhileFetching !== void 0 && i; return a && (a.fetch = A ? "stale" : "refresh", v && A && (a.returnedStale = true)), v ? z3.__staleWhileFetching : z3.__returned = z3; } } forceFetch(e2, t = {}) { let i = W.hasSubscribers, { status: s = D() ? {} : void 0 } = t; t.status = s, s && t.context && (s.context = t.context); let n = this.#K(e2, t); return s && i && (s.trace = true, W.tracePromise(() => n, s).catch(() => { })), n; } async #K(e2, t = {}) { let i = await this.#B(e2, t); if (i === void 0) throw new Error("fetch() returned undefined"); return i; } memo(e2, t = {}) { let { status: i = S.hasSubscribers ? {} : void 0 } = t; t.status = i, i && (i.op = "memo", i.key = e2, t.context && (i.context = t.context)); let s = this.#Q(e2, t); return i && (i.value = s), S.hasSubscribers && S.publish(i), s; } #Q(e2, t = {}) { let i = this.#U; if (!i) throw new Error("no memoMethod provided to constructor"); let { context: s, status: n, forceRefresh: o, ...r } = t; n && o && (n.forceRefresh = true); let h = this.#C(e2, r), l = o || h === void 0; if (n && (n.memo = l ? "miss" : "hit", l || (n.value = h)), !l) return h; let c = i(e2, h, { options: r, context: s }); return n && (n.value = c), this.#O(e2, c, r), c; } get(e2, t = {}) { let { status: i = S.hasSubscribers ? {} : void 0 } = t; t.status = i, i && (i.op = "get", i.key = e2); let s = this.#C(e2, t); return i && (s !== void 0 && (i.value = s), S.hasSubscribers && S.publish(i)), s; } #C(e2, t = {}) { let { allowStale: i = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n = this.noDeleteOnStaleGet, status: o } = t, r = this.#s.get(e2); if (r === void 0) { o && (o.get = "miss"); return; } let h = this.#t[r], l = this.#e(h); return o && this.#E(o, r), this.#p(r) ? l ? (o && (o.get = "stale-fetching"), i && h.__staleWhileFetching !== void 0 ? (o && (o.returnedStale = true), h.__staleWhileFetching) : void 0) : (n || this.#v(e2, "expire"), o && (o.get = "stale"), i ? (o && (o.returnedStale = true), h) : void 0) : (o && (o.get = l ? "fetching" : "hit"), this.#L(r), s && this.#D(r), l ? h.__staleWhileFetching : h); } #$(e2, t) { this.#c[t] = e2, this.#a[e2] = t; } #L(e2) { e2 !== this.#h && (e2 === this.#l ? this.#l = this.#a[e2] : this.#$(this.#c[e2], this.#a[e2]), this.#$(this.#h, e2), this.#h = e2); } delete(e2) { return this.#v(e2, "delete"); } #v(e2, t) { S.hasSubscribers && S.publish({ op: "delete", delete: t, key: e2 }); let i = false; if (this.#n !== 0) { let s = this.#s.get(e2); if (s !== void 0) if (this.#g?.[s] && (clearTimeout(this.#g?.[s]), this.#g[s] = void 0), i = true, this.#n === 1) this.#q(t); else { this.#R(s); let n = this.#t[s]; if (this.#e(n) ? n.__abortController.abort(new Error("deleted")) : (this.#T || this.#f) && (this.#T && this.#w?.(n, e2, t), this.#f && this.#r?.push([n, e2, t])), this.#s.delete(e2), this.#i[s] = void 0, this.#t[s] = void 0, s === this.#h) this.#h = this.#c[s]; else if (s === this.#l) this.#l = this.#a[s]; else { let o = this.#c[s]; this.#a[o] = this.#a[s]; let r = this.#a[s]; this.#c[r] = this.#c[s]; } this.#n--, this.#y.push(s); } } if (this.#f && this.#r?.length) { let s = this.#r, n; for (; n = s?.shift(); ) this.#S?.(...n); } return i; } clear() { return this.#q("delete"); } #q(e2) { for (let t of this.#z({ allowStale: true })) { let i = this.#t[t]; if (this.#e(i)) i.__abortController.abort(new Error("deleted")); else { let s = this.#i[t]; this.#T && this.#w?.(i, s, e2), this.#f && this.#r?.push([i, s, e2]); } } if (this.#s.clear(), this.#t.fill(void 0), this.#i.fill(void 0), this.#d && this.#F) { this.#d.fill(0), this.#F.fill(0); for (let t of this.#g ?? []) t !== void 0 && clearTimeout(t); this.#g?.fill(void 0); } if (this.#_ && this.#_.fill(0), this.#l = 0, this.#h = 0, this.#y.length = 0, this.#b = 0, this.#n = 0, this.#f && this.#r) { let t = this.#r, i; for (; i = t?.shift(); ) this.#S?.(...i); } } }; var __create = Object.create; var __defProp2 = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS2 = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. __defProp2(target, "default", { value: mod, enumerable: true }), mod )); var require_secure_json_parse = __commonJS2({ "../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/secure-json-parse/2.7.0/1f65efb0c6ff2d0f745ac6dfe22202b559993ceecd896afead5fc2c075b2d349/node_modules/secure-json-parse/index.js"(exports, module) { var hasBuffer = typeof Buffer !== "undefined"; var suspectProtoRx32 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx32 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse52(text42, reviver, options) { if (options == null) { if (reviver !== null && typeof reviver === "object") { options = reviver; reviver = void 0; } } if (hasBuffer && Buffer.isBuffer(text42)) { text42 = text42.toString(); } if (text42 && text42.charCodeAt(0) === 65279) { text42 = text42.slice(1); } const obj = JSON.parse(text42, reviver); if (obj === null || typeof obj !== "object") { return obj; } const protoAction = options && options.protoAction || "error"; const constructorAction = options && options.constructorAction || "error"; if (protoAction === "ignore" && constructorAction === "ignore") { return obj; } if (protoAction !== "ignore" && constructorAction !== "ignore") { if (suspectProtoRx32.test(text42) === false && suspectConstructorRx32.test(text42) === false) { return obj; } } else if (protoAction !== "ignore" && constructorAction === "ignore") { if (suspectProtoRx32.test(text42) === false) { return obj; } } else { if (suspectConstructorRx32.test(text42) === false) { return obj; } } return filter32(obj, { protoAction, constructorAction, safe: options && options.safe }); } function filter32(obj, { protoAction = "error", constructorAction = "error", safe } = {}) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { if (safe === true) { return null; } else if (protoAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } delete node.__proto__; } if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { if (safe === true) { return null; } else if (constructorAction === "error") { throw new SyntaxError("Object contains forbidden prototype property"); } delete node.constructor; } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function parse5(text42, reviver, options) { const stackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = 0; try { return _parse52(text42, reviver, options); } finally { Error.stackTraceLimit = stackTraceLimit; } } function safeParse5(text42, reviver) { const stackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = 0; try { return _parse52(text42, reviver, { safe: true }); } catch (_e) { return null; } finally { Error.stackTraceLimit = stackTraceLimit; } } module.exports = parse5; module.exports.default = parse5; module.exports.parse = parse5; module.exports.safeParse = safeParse5; module.exports.scan = filter32; } }); var marker = "vercel.ai.error"; var symbol = Symbol.for(marker); var _a; var _AISDKError = class _AISDKError2 extends Error { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name146, message, cause }) { super(message); this[_a] = true; this.name = name146; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error90) { return _AISDKError2.hasMarker(error90, marker); } static hasMarker(error90, marker156) { const markerSymbol = Symbol.for(marker156); return error90 != null && typeof error90 === "object" && markerSymbol in error90 && typeof error90[markerSymbol] === "boolean" && error90[markerSymbol] === true; } }; _a = symbol; var AISDKError = _AISDKError; var name = "AI_APICallError"; var marker2 = `vercel.ai.error.${name}`; var symbol2 = Symbol.for(marker2); var _a2; var APICallError = class extends AISDKError { constructor({ message, url: url3, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name, message, cause }); this[_a2] = true; this.url = url3; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error90) { return AISDKError.hasMarker(error90, marker2); } }; _a2 = symbol2; function getErrorMessage(error90) { if (error90 == null) { return "unknown error"; } if (typeof error90 === "string") { return error90; } if (error90 instanceof Error) { return error90.message; } return JSON.stringify(error90); } var name3 = "AI_InvalidArgumentError"; var marker4 = `vercel.ai.error.${name3}`; var symbol4 = Symbol.for(marker4); var _a4; var InvalidArgumentError = class extends AISDKError { constructor({ message, cause, argument }) { super({ name: name3, message, cause }); this[_a4] = true; this.argument = argument; } static isInstance(error90) { return AISDKError.hasMarker(error90, marker4); } }; _a4 = symbol4; var name6 = "AI_JSONParseError"; var marker7 = `vercel.ai.error.${name6}`; var symbol7 = Symbol.for(marker7); var _a7; var JSONParseError = class extends AISDKError { constructor({ text: text42, cause }) { super({ name: name6, message: `JSON parsing failed: Text: ${text42}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a7] = true; this.text = text42; } static isInstance(error90) { return AISDKError.hasMarker(error90, marker7); } }; _a7 = symbol7; var name12 = "AI_TypeValidationError"; var marker13 = `vercel.ai.error.${name12}`; var symbol13 = Symbol.for(marker13); var _a13; var _TypeValidationError = class _TypeValidationError2 extends AISDKError { constructor({ value, cause }) { super({ name: name12, message: `Type validation failed: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a13] = true; this.value = value; } static isInstance(error90) { return AISDKError.hasMarker(error90, marker13); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause }) { return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause }); } }; _a13 = symbol13; var TypeValidationError = _TypeValidationError; var customAlphabet = (alphabet, defaultSize = 21) => { return (size = defaultSize) => { let id = ""; let i = size | 0; while (i--) { id += alphabet[Math.random() * alphabet.length | 0]; } return id; }; }; var import_secure_json_parse = __toESM2(require_secure_json_parse()); function convertAsyncIteratorToReadableStream(iterator) { return new ReadableStream({ /** * Called when the consumer wants to pull more data from the stream. * * @param {ReadableStreamDefaultController} controller - The controller to enqueue data into the stream. * @returns {Promise} */ async pull(controller) { try { const { value, done } = await iterator.next(); if (done) { controller.close(); } else { controller.enqueue(value); } } catch (error90) { controller.error(error90); } }, /** * Called when the consumer cancels the stream. */ cancel() { } }); } async function delay(delayInMs) { return delayInMs == null ? Promise.resolve() : new Promise((resolve22) => setTimeout(resolve22, delayInMs)); } var createIdGenerator = ({ prefix, size: defaultSize = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = customAlphabet(alphabet, defaultSize); if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return (size) => `${prefix}${separator}${generator(size)}`; }; createIdGenerator(); function getErrorMessage2(error90) { if (error90 == null) { return "unknown error"; } if (typeof error90 === "string") { return error90; } if (error90 instanceof Error) { return error90.message; } return JSON.stringify(error90); } function isAbortError(error90) { return error90 instanceof Error && (error90.name === "AbortError" || error90.name === "TimeoutError"); } var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator"); function validator(validate) { return { [validatorSymbol]: true, validate }; } function isValidator(value) { return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value; } function asValidator(value) { return isValidator(value) ? value : zodValidator(value); } function zodValidator(zodSchema42) { return validator((value) => { const result = zodSchema42.safeParse(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; }); } function safeValidateTypes({ value, schema }) { const validator22 = asValidator(schema); try { if (validator22.validate == null) { return { success: true, value }; } const result = validator22.validate(value); if (result.success) { return result; } return { success: false, error: TypeValidationError.wrap({ value, cause: result.error }) }; } catch (error90) { return { success: false, error: TypeValidationError.wrap({ value, cause: error90 }) }; } } function safeParseJSON({ text: text42, schema }) { try { const value = import_secure_json_parse.default.parse(text42); if (schema == null) { return { success: true, value, rawValue: value }; } const validationResult = safeValidateTypes({ value, schema }); return validationResult.success ? { ...validationResult, rawValue: value } : validationResult; } catch (error90) { return { success: false, error: JSONParseError.isInstance(error90) ? error90 : new JSONParseError({ text: text42, cause: error90 }) }; } } var external_exports = {}; __export(external_exports, { BRAND: () => BRAND, DIRTY: () => DIRTY, EMPTY_PATH: () => EMPTY_PATH, INVALID: () => INVALID, NEVER: () => NEVER, OK: () => OK, ParseStatus: () => ParseStatus, Schema: () => ZodType, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBigInt: () => ZodBigInt, ZodBoolean: () => ZodBoolean, ZodBranded: () => ZodBranded, ZodCatch: () => ZodCatch, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodEffects: () => ZodEffects, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNativeEnum: () => ZodNativeEnum, ZodNever: () => ZodNever, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodParsedType: () => ZodParsedType, ZodPipeline: () => ZodPipeline, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRecord: () => ZodRecord, ZodSchema: () => ZodType, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodSymbol: () => ZodSymbol, ZodTransformer: () => ZodEffects, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, addIssueToContext: () => addIssueToContext, any: () => anyType, array: () => arrayType, bigint: () => bigIntType, boolean: () => booleanType, coerce: () => coerce, custom: () => custom, date: () => dateType, datetimeRegex: () => datetimeRegex, defaultErrorMap: () => en_default, discriminatedUnion: () => discriminatedUnionType, effect: () => effectsType, enum: () => enumType, function: () => functionType, getErrorMap: () => getErrorMap, getParsedType: () => getParsedType, instanceof: () => instanceOfType, intersection: () => intersectionType, isAborted: () => isAborted, isAsync: () => isAsync, isDirty: () => isDirty, isValid: () => isValid, late: () => late, lazy: () => lazyType, literal: () => literalType, makeIssue: () => makeIssue, map: () => mapType, nan: () => nanType, nativeEnum: () => nativeEnumType, never: () => neverType, null: () => nullType, nullable: () => nullableType, number: () => numberType, object: () => objectType, objectUtil: () => objectUtil, oboolean: () => oboolean, onumber: () => onumber, optional: () => optionalType, ostring: () => ostring, pipeline: () => pipelineType, preprocess: () => preprocessType, promise: () => promiseType, quotelessJson: () => quotelessJson, record: () => recordType, set: () => setType, setErrorMap: () => setErrorMap, strictObject: () => strictObjectType, string: () => stringType, symbol: () => symbolType, transformer: () => effectsType, tuple: () => tupleType, undefined: () => undefinedType, union: () => unionType, unknown: () => unknownType, util: () => util, void: () => voidType }); var util; (function(util3) { util3.assertEqual = (_) => { }; function assertIs3(_arg) { } util3.assertIs = assertIs3; function assertNever3(_x) { throw new Error(); } util3.assertNever = assertNever3; util3.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util3.getValidEnumValues = (obj) => { const validKeys = util3.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util3.objectValues(filtered); }; util3.objectValues = (obj) => { return util3.objectKeys(obj).map(function(e2) { return obj[e2]; }); }; util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object62) => { const keys = []; for (const key in object62) { if (Object.prototype.hasOwnProperty.call(object62, key)) { keys.push(key); } } return keys; }; util3.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues3(array4, separator = " | ") { return array4.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util3.joinValues = joinValues3; util3.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil3) { objectUtil3.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var 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; } }; var ZodIssueCode = 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" ]); var quotelessJson = (obj) => { const json4 = JSON.stringify(obj, null, 2); return json4.replace(/"([^"]+)":/g, "$1:"); }; var ZodError = class _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) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue3) { return issue3.message; }; const fieldErrors = { _errors: [] }; const processError = (error90) => { for (const issue3 of error90.issues) { if (issue3.code === "invalid_union") { issue3.unionErrors.map(processError); } else if (issue3.code === "invalid_return_type") { processError(issue3.returnTypeError); } else if (issue3.code === "invalid_arguments") { processError(issue3.argumentsError); } else if (issue3.path.length === 0) { fieldErrors._errors.push(mapper(issue3)); } else { let curr = fieldErrors; let i = 0; while (i < issue3.path.length) { const el = issue3.path[i]; const terminal = i === issue3.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue3)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue3) => issue3.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.create = (issues) => { const error90 = new ZodError(issues); return error90; }; var errorMap = (issue3, _ctx) => { let message; switch (issue3.code) { case ZodIssueCode.invalid_type: if (issue3.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue3.expected}, received ${issue3.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue3.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue3.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue3.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue3.options)}, received '${issue3.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 issue3.validation === "object") { if ("includes" in issue3.validation) { message = `Invalid input: must include "${issue3.validation.includes}"`; if (typeof issue3.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue3.validation.position}`; } } else if ("startsWith" in issue3.validation) { message = `Invalid input: must start with "${issue3.validation.startsWith}"`; } else if ("endsWith" in issue3.validation) { message = `Invalid input: must end with "${issue3.validation.endsWith}"`; } else { util.assertNever(issue3.validation); } } else if (issue3.validation !== "regex") { message = `Invalid ${issue3.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue3.type === "array") message = `Array must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `more than`} ${issue3.minimum} element(s)`; else if (issue3.type === "string") message = `String must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `over`} ${issue3.minimum} character(s)`; else if (issue3.type === "number") message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; else if (issue3.type === "bigint") message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; else if (issue3.type === "date") message = `Date must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue3.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue3.type === "array") message = `Array must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `less than`} ${issue3.maximum} element(s)`; else if (issue3.type === "string") message = `String must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `under`} ${issue3.maximum} character(s)`; else if (issue3.type === "number") message = `Number must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; else if (issue3.type === "bigint") message = `BigInt must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; else if (issue3.type === "date") message = `Date must be ${issue3.exact ? `exactly` : issue3.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue3.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 ${issue3.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue3); } return { message }; }; var en_default = errorMap; var overrideErrorMap = en_default; function setErrorMap(map3) { overrideErrorMap = map3; } function getErrorMap() { return overrideErrorMap; } var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) { return { ...issueData, path: fullPath, message: issueData.message }; } let errorMessage = ""; const maps = errorMaps.filter((m) => !!m).slice().reverse(); for (const map3 of maps) { errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; var EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue3 = makeIssue({ 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 === en_default ? void 0 : en_default // then global default map ].filter((x) => !!x) }); ctx.common.issues.push(issue3); } var ParseStatus = 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 }; } }; var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x) => x.status === "aborted"; var isDirty = (x) => x.status === "dirty"; var isValid = (x) => x.status === "valid"; var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; var errorUtil; (function(errorUtil3) { errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); var ParseInputLazyPath = class { 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; } }; var 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 error90 = new ZodError(ctx.common.issues); this._error = error90; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap3, invalid_type_error, required_error, description } = params; if (errorMap3 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap3) return { errorMap: errorMap3, 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 }; } var ZodType = class { get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: 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: 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: 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: 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: 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(check3, 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 = check3(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(check3, refinementData) { return this._refinement((val, ctx) => { if (!check3(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) { 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 ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform3) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform: transform3 } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new 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 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 ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[0-9a-z]+$/; var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; var 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; var nanoidRegex = /^[a-z0-9_-]{21}$/i; var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; var 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)?)??$/; var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; var emojiRegex; var 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])$/; var 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])$/; var 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]))$/; var 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])$/; var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; var 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])))`; var 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 ? "+" : "?"; return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } 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, version3) { if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) { return true; } if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT(jwt3, alg) { if (!jwtRegex.test(jwt3)) return false; try { const [header] = jwt3.split("."); if (!header) return false; const base645 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base645)); 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, version3) { if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) { return true; } if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) { return true; } return false; } var ZodString = class _ZodString3 extends ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType5 = this._getType(input); if (parsedType5 !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check3 of this._def.checks) { if (check3.kind === "min") { if (input.data.length < check3.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check3.value, type: "string", inclusive: true, exact: false, message: check3.message }); status.dirty(); } } else if (check3.kind === "max") { if (input.data.length > check3.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check3.value, type: "string", inclusive: true, exact: false, message: check3.message }); status.dirty(); } } else if (check3.kind === "length") { const tooBig = input.data.length > check3.value; const tooSmall = input.data.length < check3.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check3.value, type: "string", inclusive: true, exact: true, message: check3.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check3.value, type: "string", inclusive: true, exact: true, message: check3.message }); } status.dirty(); } } else if (check3.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.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: check3.message }); status.dirty(); } } else if (check3.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "url") { try { new URL(input.data); } catch { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "regex") { check3.regex.lastIndex = 0; const testResult = check3.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "trim") { input.data = input.data.trim(); } else if (check3.kind === "includes") { if (!input.data.includes(check3.value, check3.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check3.value, position: check3.position }, message: check3.message }); status.dirty(); } } else if (check3.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check3.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check3.kind === "startsWith") { if (!input.data.startsWith(check3.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check3.value }, message: check3.message }); status.dirty(); } } else if (check3.kind === "endsWith") { if (!input.data.endsWith(check3.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check3.value }, message: check3.message }); status.dirty(); } } else if (check3.kind === "datetime") { const regex = datetimeRegex(check3); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check3.message }); status.dirty(); } } else if (check3.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "date", message: check3.message }); status.dirty(); } } else if (check3.kind === "time") { const regex = timeRegex(check3); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "time", message: check3.message }); status.dirty(); } } else if (check3.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "ip") { if (!isValidIP(input.data, check3.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "jwt") { if (!isValidJWT(input.data, check3.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "cidr") { if (!isValidCidr(input.data, check3.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else if (check3.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode.invalid_string, message: check3.message }); status.dirty(); } } else { util.assertNever(check3); } } 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(check3) { return new _ZodString3({ ...this._def, checks: [...this._def.checks, check3] }); } 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) { 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, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options?.position, ...errorUtil.errToObj(options?.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", 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 _ZodString3({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new _ZodString3({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new _ZodString3({ ...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() { 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; } }; ZodString.create = (params) => { return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; 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; } var ZodNumber = class _ZodNumber extends 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 parsedType5 = this._getType(input); if (parsedType5 !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check3 of this._def.checks) { if (check3.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check3.message }); status.dirty(); } } else if (check3.kind === "min") { const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check3.value, type: "number", inclusive: check3.inclusive, exact: false, message: check3.message }); status.dirty(); } } else if (check3.kind === "max") { const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check3.value, type: "number", inclusive: check3.inclusive, exact: false, message: check3.message }); status.dirty(); } } else if (check3.kind === "multipleOf") { if (floatSafeRemainder(input.data, check3.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check3.value, message: check3.message }); status.dirty(); } } else if (check3.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check3.message }); status.dirty(); } } else { util.assertNever(check3); } } 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 _ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check3) { return new _ZodNumber({ ...this._def, checks: [...this._def.checks, check3] }); } 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, 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.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); } }; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodBigInt = class _ZodBigInt extends 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 parsedType5 = this._getType(input); if (parsedType5 !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = void 0; const status = new ParseStatus(); for (const check3 of this._def.checks) { if (check3.kind === "min") { const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check3.value, inclusive: check3.inclusive, message: check3.message }); status.dirty(); } } else if (check3.kind === "max") { const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check3.value, inclusive: check3.inclusive, message: check3.message }); status.dirty(); } } else if (check3.kind === "multipleOf") { if (input.data % check3.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check3.value, message: check3.message }); status.dirty(); } } else { util.assertNever(check3); } } 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 _ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check3) { return new _ZodBigInt({ ...this._def, checks: [...this._def.checks, check3] }); } 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; } }; ZodBigInt.create = (params) => { return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; var ZodBoolean = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType5 = this._getType(input); if (parsedType5 !== 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); } }; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodDate = class _ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType5 = this._getType(input); if (parsedType5 !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (Number.isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check3 of this._def.checks) { if (check3.kind === "min") { if (input.data.getTime() < check3.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check3.message, inclusive: true, exact: false, minimum: check3.value, type: "date" }); status.dirty(); } } else if (check3.kind === "max") { if (input.data.getTime() > check3.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check3.message, inclusive: true, exact: false, maximum: check3.value, type: "date" }); status.dirty(); } } else { util.assertNever(check3); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check3) { return new _ZodDate({ ...this._def, checks: [...this._def.checks, check3] }); } 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; } }; ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: params?.coerce || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; var ZodSymbol = class extends ZodType { _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 !== 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); } }; ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined = class extends ZodType { _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 !== 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); } }; ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull = class extends ZodType { _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 !== 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); } }; ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; var ZodAny = class extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input) { return OK(input.data); } }; ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown = class extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return OK(input.data); } }; ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever = class extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType }); return INVALID; } }; ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params) }); }; var ZodVoid = class extends ZodType { _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 !== 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); } }; ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; var ZodArray = class _ZodArray extends 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 : void 0, maximum: tooBig ? def.exactLength.value : void 0, 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((result2) => { return ParseStatus.mergeArray(status, result2); }); } 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 _ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new _ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new _ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray.create = (schema, params) => { return new ZodArray({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema) { if (schema instanceof ZodObject) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema._def, shape: () => newShape }); } else if (schema instanceof ZodArray) { return new ZodArray({ ...schema._def, type: deepPartialify(schema.element) }); } else if (schema instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple) { return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } var ZodObject = class _ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof 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 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 { 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) { return new _ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue3, ctx) => { const defaultError = this._def.errorMap?.(issue3, ctx).message ?? ctx.defaultError; if (issue3.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new _ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new _ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _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 _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>, // 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( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // 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 _ZodObject({ ...this._def, catchall: index }); } pick(mask) { const shape = {}; for (const key of util.objectKeys(mask)) { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; for (const key of util.objectKeys(this.shape)) { if (!mask[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new _ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; for (const key of 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 ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } } return new _ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; var ZodUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new 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 = void 0; 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((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type) => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral) { return [type.value]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { return util.objectValues(type.enum); } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined) { return [void 0]; } else if (type instanceof ZodNull) { return [null]; } else if (type instanceof ZodOptional) { return [void 0, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch) { return getDiscriminator(type._def.innerType); } else { return []; } }; var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends 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) { const optionsMap = /* @__PURE__ */ new Map(); 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 _ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; function mergeValues(a, b) { const aType = getParsedType(a); const bType = getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b); const sharedKeys = util.objectKeys(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 }; } 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 = 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 }; } } var ZodIntersection = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = 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 })); } } }; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; var ZodTuple = class _ZodTuple extends 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); 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 _ZodTuple({ ...this._def, rest }); } }; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord = class _ZodRecord extends 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 ZodType) { return new _ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new _ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; var ZodMap = class extends 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 = /* @__PURE__ */ 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 = /* @__PURE__ */ 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 }; } } }; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; var ZodSet = class _ZodSet extends 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(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { 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((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new _ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new _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); } }; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; var ZodFunction = class _ZodFunction extends 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, error90) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error90 } }); } function makeReturnsIssue(returns, error90) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error90 } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { const me = this; return OK(async function(...args) { const error90 = new ZodError([]); const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => { error90.addIssue(makeArgsIssue(args, e2)); throw error90; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => { error90.addIssue(makeReturnsIssue(result, e2)); throw error90; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new 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([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: ZodTuple.create(items).rest(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 : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; var ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema32 = this._def.getter(); return lazySchema32._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral = class extends 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; } }; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var ZodEnum = class _ZodEnum extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: 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 _ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } }; ZodEnum.create = createZodEnum; var ZodNativeEnum = class extends ZodType { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(util.getValidEnumValues(this._def.values)); } if (!this._cache.has(input.data)) { const expectedValues = 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, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise = class extends 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 }); })); } }; ZodPromise.create = (schema, params) => { return new ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends 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 (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, 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(); 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.assertNever(effect); } }; ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess3, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess3 }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional = class extends ZodType { _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable = class extends ZodType { _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault = class extends 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; } }; ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; var ZodCatch = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); 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((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new 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(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; var ZodNaN = class extends ZodType { _parse(input) { const parsedType5 = this._getType(input); if (parsedType5 !== 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 }; } }; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; var BRAND = /* @__PURE__ */ Symbol("zod_brand"); var ZodBranded = class extends 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; } }; var ZodPipeline = class _ZodPipeline extends 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 }); } }; var ZodReadonly = class extends 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; } }; ZodReadonly.create = (type, params) => { return new ZodReadonly({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; 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 custom(check3, _params = {}, fatal) { if (check3) return ZodAny.create().superRefine((data, ctx) => { const r = check3(data); if (r instanceof Promise) { return r.then((r2) => { if (!r2) { 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 ZodAny.create(); } var late = { object: ZodObject.lazycreate }; var ZodFirstPartyTypeKind; (function(ZodFirstPartyTypeKind42) { ZodFirstPartyTypeKind42["ZodString"] = "ZodString"; ZodFirstPartyTypeKind42["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind42["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind42["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind42["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind42["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind42["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind42["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind42["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind42["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind42["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind42["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind42["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind42["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind42["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind42["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind42["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind42["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind42["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind42["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind42["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind42["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind42["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind42["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind42["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind42["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind42["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind42["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind42["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind42["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind42["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind42["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind42["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind42["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind42["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind42["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); var stringType = ZodString.create; var numberType = ZodNumber.create; var nanType = ZodNaN.create; var bigIntType = ZodBigInt.create; var booleanType = ZodBoolean.create; var dateType = ZodDate.create; var symbolType = ZodSymbol.create; var undefinedType = ZodUndefined.create; var nullType = ZodNull.create; var anyType = ZodAny.create; var unknownType = ZodUnknown.create; var neverType = ZodNever.create; var voidType = ZodVoid.create; var arrayType = ZodArray.create; var objectType = ZodObject.create; var strictObjectType = ZodObject.strictCreate; var unionType = ZodUnion.create; var discriminatedUnionType = ZodDiscriminatedUnion.create; var intersectionType = ZodIntersection.create; var tupleType = ZodTuple.create; var recordType = ZodRecord.create; var mapType = ZodMap.create; var setType = ZodSet.create; var functionType = ZodFunction.create; var lazyType = ZodLazy.create; var literalType = ZodLiteral.create; var enumType = ZodEnum.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional.create; var nullableType = ZodNullable.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; var ostring = () => stringType().optional(); var onumber = () => numberType().optional(); var oboolean = () => booleanType().optional(); var coerce = { string: ((arg) => ZodString.create({ ...arg, coerce: true })), number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), boolean: ((arg) => ZodBoolean.create({ ...arg, coerce: true })), bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), date: ((arg) => ZodDate.create({ ...arg, coerce: true })) }; var NEVER = INVALID; var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use"); var defaultOptions = { name: void 0, $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" }; var getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; var getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, flags: { hasReferencedOpenAiAnyType: false }, currentPath, propertyPath: void 0, seen: new Map(Object.entries(_options.definitions).map(([name173, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name173], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ])) }; }; 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); } var 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("/"); }; 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("/") }; } 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; } function parseBigintDef(def, refs) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "min": if (refs.target === "jsonSchema7") { if (check3.inclusive) { setResponseValueAndErrors(res, "minimum", check3.value, check3.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check3.value, check3.message, refs); } } else { if (!check3.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check3.value, check3.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check3.inclusive) { setResponseValueAndErrors(res, "maximum", check3.value, check3.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check3.value, check3.message, refs); } } else { if (!check3.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check3.value, check3.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check3.value, check3.message, refs); break; } } return res; } function parseBooleanDef() { return { type: "boolean" }; } function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; 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); } } var integerDateParser = (def, refs) => { const res = { type: "integer", format: "unix-time" }; if (refs.target === "openApi3") { return res; } for (const check3 of def.checks) { switch (check3.kind) { case "min": setResponseValueAndErrors( res, "minimum", check3.value, // This is in milliseconds check3.message, refs ); break; case "max": setResponseValueAndErrors( res, "maximum", check3.value, // This is in milliseconds check3.message, refs ); break; } } return res; }; function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); } function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values) }; } var 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 } : void 0; const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); if (schema.unevaluatedProperties === void 0) { unevaluatedProperties = void 0; } } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } else { unevaluatedProperties = void 0; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf, ...unevaluatedProperties } : void 0; } function parseLiteralDef(def, refs) { const parsedType5 = typeof def.value; if (parsedType5 !== "bigint" && parsedType5 !== "number" && parsedType5 !== "boolean" && parsedType5 !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } if (refs.target === "openApi3") { return { type: parsedType5 === "bigint" ? "integer" : parsedType5, enum: [def.value] }; } return { type: parsedType5 === "bigint" ? "integer" : parsedType5, const: def.value }; } var emojiRegex2 = void 0; var 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 (emojiRegex2 === void 0) { emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); } return emojiRegex2; }, /** * 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 check3 of def.checks) { switch (check3.kind) { case "min": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value, check3.message, refs); break; case "max": setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value, check3.message, refs); break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check3.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check3.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check3.message, refs); break; } break; case "url": addFormat(res, "uri", check3.message, refs); break; case "uuid": addFormat(res, "uuid", check3.message, refs); break; case "regex": addPattern(res, check3.regex, check3.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check3.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check3.message, refs); break; case "startsWith": addPattern(res, RegExp(`^${escapeLiteralCheckValue(check3.value, refs)}`), check3.message, refs); break; case "endsWith": addPattern(res, RegExp(`${escapeLiteralCheckValue(check3.value, refs)}$`), check3.message, refs); break; case "datetime": addFormat(res, "date-time", check3.message, refs); break; case "date": addFormat(res, "date", check3.message, refs); break; case "time": addFormat(res, "time", check3.message, refs); break; case "duration": addFormat(res, "duration", check3.message, refs); break; case "length": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value, check3.message, refs); setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value, check3.message, refs); break; case "includes": { addPattern(res, RegExp(escapeLiteralCheckValue(check3.value, refs)), check3.message, refs); break; } case "ip": { if (check3.version !== "v6") { addFormat(res, "ipv4", check3.message, refs); } if (check3.version !== "v4") { addFormat(res, "ipv6", check3.message, refs); } break; } case "base64url": addPattern(res, zodPatterns.base64url, check3.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check3.message, refs); break; case "cidr": { if (check3.version !== "v6") { addPattern(res, zodPatterns.ipv4Cidr, check3.message, refs); } if (check3.version !== "v4") { addPattern(res, zodPatterns.ipv6Cidr, check3.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji(), check3.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check3.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check3.message, refs); break; } case "contentEncoding:base64": { setResponseValueAndErrors(res, "contentEncoding", "base64", check3.message, refs); break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check3.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check3.message, refs); } } } } return res; } function escapeLiteralCheckValue(literal3, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal3) : literal3; } var 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; } 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); } } 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); } } function stringifyRegExpWithFlags(regex, refs) { if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), m: regex.flags.includes("m"), s: regex.flags.includes("s") // `.` matches newlines }; 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 ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } return pattern; } 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; } 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 } }; } function parseNativeEnumDef(def) { const object22 = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object22[object22[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object22[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 }; } function parseNeverDef(refs) { return refs.target === "openAi" ? void 0 : { not: parseAnyDef({ ...refs, currentPath: [...refs.currentPath, "not"] }) }; } function parseNullDef(refs) { return refs.target === "openApi3" ? { enum: ["null"], nullable: true } : { type: "null" }; } var 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; if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { const types = options.reduce((types2, x) => { const type = primitiveMappings[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { 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) { 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((x2) => !acc.includes(x2)) ], []) }; } return asAnyOf(def, refs); } var 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 } : void 0; }; 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 base2 = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath] }); if (base2 && "$ref" in base2) return { allOf: [base2], nullable: true }; return base2 && { ...base2, nullable: true }; } const base = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } function parseNumberDef(def, refs) { const res = { type: "number" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "int": res.type = "integer"; addErrorMessage(res, "type", check3.message, refs); break; case "min": if (refs.target === "jsonSchema7") { if (check3.inclusive) { setResponseValueAndErrors(res, "minimum", check3.value, check3.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check3.value, check3.message, refs); } } else { if (!check3.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check3.value, check3.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check3.inclusive) { setResponseValueAndErrors(res, "maximum", check3.value, check3.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check3.value, check3.message, refs); } } else { if (!check3.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check3.value, check3.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check3.value, check3.message, refs); break; } } return res; } function parseObjectDef(def, refs) { const forceOptionalIntoNullable = refs.target === "openAi"; const result = { type: "object", properties: {} }; const required3 = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { 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 === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required3.push(propName); } } if (required3.length) { result.required = required3; } const additionalProperties = decideAdditionalProperties(def, refs); if (additionalProperties !== void 0) { 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; } } var 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); }; var 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 !== void 0) }; }; function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } 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; } 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 === void 0 ? 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 === void 0 ? acc : [...acc, x], []) }; } } function parseUndefinedDef(refs) { return { not: parseAnyDef(refs) }; } function parseUnknownDef(refs) { return parseAnyDef(refs); } var parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; var 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 void 0; default: return /* @__PURE__ */ ((_) => void 0)(); } }; 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 !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); const jsonSchema22 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema22) { addMeta(def, refs, jsonSchema22); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema22, def, refs); newItem.jsonSchema = jsonSchema22; return postProcessResult; } newItem.jsonSchema = jsonSchema22; return jsonSchema22; } var 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) : void 0; } } }; var addMeta = (def, refs, jsonSchema22) => { if (def.description) { jsonSchema22.description = def.description; if (refs.markdownDescription) { jsonSchema22.markdownDescription = def.description; } } return jsonSchema22; }; var zodToJsonSchema = (schema, options) => { const refs = getRefs(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name183, schema2]) => ({ ...acc, [name183]: parseDef(schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name183] }, true) ?? parseAnyDef(refs) }), {}) : void 0; const name173 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; const main = parseDef(schema._def, name173 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name173] }, false) ?? parseAnyDef(refs); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { 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 = name173 === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name173 ].join("/"), [refs.definitionPath]: { ...definitions, [name173]: 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; }; var esm_default = zodToJsonSchema; function fixJson(input) { const stack = ["ROOT"]; let lastValidIndex = -1; let literalStart = null; function processValueStart(char, i, swapState) { { switch (char) { case '"': { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_STRING"); break; } case "f": case "t": case "n": { lastValidIndex = i; literalStart = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_LITERAL"); break; } case "-": { stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "{": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_OBJECT_START"); break; } case "[": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_ARRAY_START"); break; } } } } function processAfterObjectValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_COMMA"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } } function processAfterArrayValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } } } for (let i = 0; i < input.length; i++) { const char = input[i]; const currentState = stack[stack.length - 1]; switch (currentState) { case "ROOT": processValueStart(char, i, "FINISH"); break; case "INSIDE_OBJECT_START": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } break; } case "INSIDE_OBJECT_AFTER_COMMA": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } } break; } case "INSIDE_OBJECT_KEY": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_KEY"); break; } } break; } case "INSIDE_OBJECT_AFTER_KEY": { switch (char) { case ":": { stack.pop(); stack.push("INSIDE_OBJECT_BEFORE_VALUE"); break; } } break; } case "INSIDE_OBJECT_BEFORE_VALUE": { processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE"); break; } case "INSIDE_OBJECT_AFTER_VALUE": { processAfterObjectValue(char, i); break; } case "INSIDE_STRING": { switch (char) { case '"': { stack.pop(); lastValidIndex = i; break; } case "\\": { stack.push("INSIDE_STRING_ESCAPE"); break; } default: { lastValidIndex = i; } } break; } case "INSIDE_ARRAY_START": { switch (char) { case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } } break; } case "INSIDE_ARRAY_AFTER_VALUE": { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; break; } } break; } case "INSIDE_ARRAY_AFTER_COMMA": { processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } case "INSIDE_STRING_ESCAPE": { stack.pop(); lastValidIndex = i; break; } case "INSIDE_NUMBER": { switch (char) { case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; break; } case "e": case "E": case "-": case ".": { break; } case ",": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "}": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "]": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } break; } default: { stack.pop(); break; } } break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, i + 1); if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } } else { lastValidIndex = i; } break; } } } let result = input.slice(0, lastValidIndex + 1); for (let i = stack.length - 1; i >= 0; i--) { const state = stack[i]; switch (state) { case "INSIDE_STRING": { result += '"'; break; } case "INSIDE_OBJECT_KEY": case "INSIDE_OBJECT_AFTER_KEY": case "INSIDE_OBJECT_AFTER_COMMA": case "INSIDE_OBJECT_START": case "INSIDE_OBJECT_BEFORE_VALUE": case "INSIDE_OBJECT_AFTER_VALUE": { result += "}"; break; } case "INSIDE_ARRAY_START": case "INSIDE_ARRAY_AFTER_COMMA": case "INSIDE_ARRAY_AFTER_VALUE": { result += "]"; break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, input.length); if ("true".startsWith(partialLiteral)) { result += "true".slice(partialLiteral.length); } else if ("false".startsWith(partialLiteral)) { result += "false".slice(partialLiteral.length); } else if ("null".startsWith(partialLiteral)) { result += "null".slice(partialLiteral.length); } } } } return result; } function parsePartialJson(jsonText) { if (jsonText === void 0) { return { value: void 0, state: "undefined-input" }; } let result = safeParseJSON({ text: jsonText }); if (result.success) { return { value: result.value, state: "successful-parse" }; } result = safeParseJSON({ text: fixJson(jsonText) }); if (result.success) { return { value: result.value, state: "repaired-parse" }; } return { value: void 0, state: "failed-parse" }; } var textStreamPart2 = { code: "0", name: "text", parse: (value) => { if (typeof value !== "string") { throw new Error('"text" parts expect a string value.'); } return { type: "text", value }; } }; var dataStreamPart = { code: "2", name: "data", parse: (value) => { if (!Array.isArray(value)) { throw new Error('"data" parts expect an array value.'); } return { type: "data", value }; } }; var errorStreamPart2 = { code: "3", name: "error", parse: (value) => { if (typeof value !== "string") { throw new Error('"error" parts expect a string value.'); } return { type: "error", value }; } }; var messageAnnotationsStreamPart = { code: "8", name: "message_annotations", parse: (value) => { if (!Array.isArray(value)) { throw new Error('"message_annotations" parts expect an array value.'); } return { type: "message_annotations", value }; } }; var toolCallStreamPart = { code: "9", name: "tool_call", parse: (value) => { if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") { throw new Error( '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.' ); } return { type: "tool_call", value }; } }; var toolResultStreamPart = { code: "a", name: "tool_result", parse: (value) => { if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) { throw new Error( '"tool_result" parts expect an object with a "toolCallId" and a "result" property.' ); } return { type: "tool_result", value }; } }; var toolCallStreamingStartStreamPart = { code: "b", name: "tool_call_streaming_start", parse: (value) => { if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") { throw new Error( '"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.' ); } return { type: "tool_call_streaming_start", value }; } }; var toolCallDeltaStreamPart = { code: "c", name: "tool_call_delta", parse: (value) => { if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") { throw new Error( '"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.' ); } return { type: "tool_call_delta", value }; } }; var finishMessageStreamPart = { code: "d", name: "finish_message", parse: (value) => { if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") { throw new Error( '"finish_message" parts expect an object with a "finishReason" property.' ); } const result = { finishReason: value.finishReason }; if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) { result.usage = { promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN, completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN }; } return { type: "finish_message", value: result }; } }; var finishStepStreamPart = { code: "e", name: "finish_step", parse: (value) => { if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") { throw new Error( '"finish_step" parts expect an object with a "finishReason" property.' ); } const result = { finishReason: value.finishReason, isContinued: false }; if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) { result.usage = { promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN, completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN }; } if ("isContinued" in value && typeof value.isContinued === "boolean") { result.isContinued = value.isContinued; } return { type: "finish_step", value: result }; } }; var startStepStreamPart = { code: "f", name: "start_step", parse: (value) => { if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") { throw new Error( '"start_step" parts expect an object with an "id" property.' ); } return { type: "start_step", value: { messageId: value.messageId } }; } }; var reasoningStreamPart = { code: "g", name: "reasoning", parse: (value) => { if (typeof value !== "string") { throw new Error('"reasoning" parts expect a string value.'); } return { type: "reasoning", value }; } }; var sourcePart = { code: "h", name: "source", parse: (value) => { if (value == null || typeof value !== "object") { throw new Error('"source" parts expect a Source object.'); } return { type: "source", value }; } }; var redactedReasoningStreamPart = { code: "i", name: "redacted_reasoning", parse: (value) => { if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string") { throw new Error( '"redacted_reasoning" parts expect an object with a "data" property.' ); } return { type: "redacted_reasoning", value: { data: value.data } }; } }; var reasoningSignatureStreamPart = { code: "j", name: "reasoning_signature", parse: (value) => { if (value == null || typeof value !== "object" || !("signature" in value) || typeof value.signature !== "string") { throw new Error( '"reasoning_signature" parts expect an object with a "signature" property.' ); } return { type: "reasoning_signature", value: { signature: value.signature } }; } }; var fileStreamPart = { code: "k", name: "file", parse: (value) => { if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string" || !("mimeType" in value) || typeof value.mimeType !== "string") { throw new Error( '"file" parts expect an object with a "data" and "mimeType" property.' ); } return { type: "file", value }; } }; var dataStreamParts = [ textStreamPart2, dataStreamPart, errorStreamPart2, messageAnnotationsStreamPart, toolCallStreamPart, toolResultStreamPart, toolCallStreamingStartStreamPart, toolCallDeltaStreamPart, finishMessageStreamPart, finishStepStreamPart, startStepStreamPart, reasoningStreamPart, sourcePart, redactedReasoningStreamPart, reasoningSignatureStreamPart, fileStreamPart ]; Object.fromEntries( dataStreamParts.map((part) => [part.code, part]) ); Object.fromEntries( dataStreamParts.map((part) => [part.name, part.code]) ); function formatDataStreamPart(type, value) { const streamPart = dataStreamParts.find((part) => part.name === type); if (!streamPart) { throw new Error(`Invalid stream part type: ${type}`); } return `${streamPart.code}:${JSON.stringify(value)} `; } function zodSchema(zodSchema22, options) { var _a173; const useReferences = (_a173 = void 0) != null ? _a173 : false; return jsonSchema( esm_default(zodSchema22, { $refStrategy: useReferences ? "root" : "none", target: "jsonSchema7" // note: openai mode breaks various gemini conversions }), { validate: (value) => { const result = zodSchema22.safeParse(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function jsonSchema(jsonSchema22, { validate } = {}) { return { [schemaSymbol]: true, _type: void 0, // should never be used directly [validatorSymbol]: true, jsonSchema: jsonSchema22, validate }; } function isSchema(value) { return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value; } function asSchema(schema) { return isSchema(schema) ? schema : zodSchema(schema); } var _globalThis = typeof globalThis === "object" ? globalThis : global; var VERSION = "1.9.0"; var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; function _makeCompatibilityCheck(ownVersion) { var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); var rejectedVersions = /* @__PURE__ */ new Set(); var myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { return function() { return false; }; } var ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], prerelease: myVersionMatch[4] }; if (ownVersionParsed.prerelease != null) { return function isExactmatch(globalVersion) { return globalVersion === ownVersion; }; } function _reject(v) { rejectedVersions.add(v); return false; } function _accept(v) { acceptedVersions.add(v); return true; } return function isCompatible22(globalVersion) { if (acceptedVersions.has(globalVersion)) { return true; } if (rejectedVersions.has(globalVersion)) { return false; } var globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { return _reject(globalVersion); } var globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], prerelease: globalVersionMatch[4] }; if (globalVersionParsed.prerelease != null) { return _reject(globalVersion); } if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); } if (ownVersionParsed.major === 0) { if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { return _accept(globalVersion); } return _reject(globalVersion); } if (ownVersionParsed.minor <= globalVersionParsed.minor) { return _accept(globalVersion); } return _reject(globalVersion); }; } var isCompatible = _makeCompatibilityCheck(VERSION); var major = VERSION.split(".")[0]; var GLOBAL_OPENTELEMETRY_API_KEY = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major); var _global = _globalThis; function registerGlobal(type, instance, diag, allowOverride) { var _a173; if (allowOverride === void 0) { allowOverride = false; } var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a173 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a173 !== void 0 ? _a173 : { version: VERSION }; if (!allowOverride && api[type]) { var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); diag.error(err.stack || err.message); return false; } if (api.version !== VERSION) { var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION); diag.error(err.stack || err.message); return false; } api[type] = instance; diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + "."); return true; } function getGlobal(type) { var _a173, _b19; var globalVersion = (_a173 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a173 === void 0 ? void 0 : _a173.version; if (!globalVersion || !isCompatible(globalVersion)) { return; } return (_b19 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b19 === void 0 ? void 0 : _b19[type]; } function unregisterGlobal(type, diag) { diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + "."); var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } } var __read = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var DiagComponentLogger = ( /** @class */ (function() { function DiagComponentLogger22(props) { this._namespace = props.namespace || "DiagComponentLogger"; } DiagComponentLogger22.prototype.debug = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy("debug", this._namespace, args); }; DiagComponentLogger22.prototype.error = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy("error", this._namespace, args); }; DiagComponentLogger22.prototype.info = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy("info", this._namespace, args); }; DiagComponentLogger22.prototype.warn = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy("warn", this._namespace, args); }; DiagComponentLogger22.prototype.verbose = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy("verbose", this._namespace, args); }; return DiagComponentLogger22; })() ); function logProxy(funcName, namespace, args) { var logger = getGlobal("diag"); if (!logger) { return; } args.unshift(namespace); return logger[funcName].apply(logger, __spreadArray([], __read(args), false)); } var DiagLogLevel; (function(DiagLogLevel22) { DiagLogLevel22[DiagLogLevel22["NONE"] = 0] = "NONE"; DiagLogLevel22[DiagLogLevel22["ERROR"] = 30] = "ERROR"; DiagLogLevel22[DiagLogLevel22["WARN"] = 50] = "WARN"; DiagLogLevel22[DiagLogLevel22["INFO"] = 60] = "INFO"; DiagLogLevel22[DiagLogLevel22["DEBUG"] = 70] = "DEBUG"; DiagLogLevel22[DiagLogLevel22["VERBOSE"] = 80] = "VERBOSE"; DiagLogLevel22[DiagLogLevel22["ALL"] = 9999] = "ALL"; })(DiagLogLevel || (DiagLogLevel = {})); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } logger = logger || {}; function _filterFunc(funcName, theLevel) { var theFunc = logger[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { return theFunc.bind(logger); } return function() { }; } return { error: _filterFunc("error", DiagLogLevel.ERROR), warn: _filterFunc("warn", DiagLogLevel.WARN), info: _filterFunc("info", DiagLogLevel.INFO), debug: _filterFunc("debug", DiagLogLevel.DEBUG), verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE) }; } var __read2 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray2 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME = "diag"; var DiagAPI = ( /** @class */ (function() { function DiagAPI22() { function _logProxy(funcName) { return function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var logger = getGlobal("diag"); if (!logger) return; return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false)); }; } var self = this; var setLogger = function(logger, optionsOrLogLevel) { var _a173, _b19, _c; if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; } if (logger === self) { var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self.error((_a173 = err.stack) !== null && _a173 !== void 0 ? _a173 : err.message); return false; } if (typeof optionsOrLogLevel === "number") { optionsOrLogLevel = { logLevel: optionsOrLogLevel }; } var oldLogger = getGlobal("diag"); var newLogger = createLogLevelDiagLogger((_b19 = optionsOrLogLevel.logLevel) !== null && _b19 !== void 0 ? _b19 : DiagLogLevel.INFO, logger); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn("Current logger will be overwritten from " + stack); newLogger.warn("Current logger will overwrite one already registered from " + stack); } return registerGlobal("diag", newLogger, self, true); }; self.setLogger = setLogger; self.disable = function() { unregisterGlobal(API_NAME, self); }; self.createComponentLogger = function(options) { return new DiagComponentLogger(options); }; self.verbose = _logProxy("verbose"); self.debug = _logProxy("debug"); self.info = _logProxy("info"); self.warn = _logProxy("warn"); self.error = _logProxy("error"); } DiagAPI22.instance = function() { if (!this._instance) { this._instance = new DiagAPI22(); } return this._instance; }; return DiagAPI22; })() ); function createContextKey(description) { return Symbol.for(description); } var BaseContext = ( /** @class */ /* @__PURE__ */ (function() { function BaseContext22(parentContext) { var self = this; self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); self.getValue = function(key) { return self._currentContext.get(key); }; self.setValue = function(key, value) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.set(key, value); return context2; }; self.deleteValue = function(key) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.delete(key); return context2; }; } return BaseContext22; })() ); var ROOT_CONTEXT = new BaseContext(); var __read3 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray3 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var NoopContextManager = ( /** @class */ (function() { function NoopContextManager22() { } NoopContextManager22.prototype.active = function() { return ROOT_CONTEXT; }; NoopContextManager22.prototype.with = function(_context, fn, thisArg) { var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false)); }; NoopContextManager22.prototype.bind = function(_context, target) { return target; }; NoopContextManager22.prototype.enable = function() { return this; }; NoopContextManager22.prototype.disable = function() { return this; }; return NoopContextManager22; })() ); var __read4 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray4 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME2 = "context"; var NOOP_CONTEXT_MANAGER = new NoopContextManager(); var ContextAPI = ( /** @class */ (function() { function ContextAPI22() { } ContextAPI22.getInstance = function() { if (!this._instance) { this._instance = new ContextAPI22(); } return this._instance; }; ContextAPI22.prototype.setGlobalContextManager = function(contextManager) { return registerGlobal(API_NAME2, contextManager, DiagAPI.instance()); }; ContextAPI22.prototype.active = function() { return this._getContextManager().active(); }; ContextAPI22.prototype.with = function(context2, fn, thisArg) { var _a173; var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return (_a173 = this._getContextManager()).with.apply(_a173, __spreadArray4([context2, fn, thisArg], __read4(args), false)); }; ContextAPI22.prototype.bind = function(context2, target) { return this._getContextManager().bind(context2, target); }; ContextAPI22.prototype._getContextManager = function() { return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER; }; ContextAPI22.prototype.disable = function() { this._getContextManager().disable(); unregisterGlobal(API_NAME2, DiagAPI.instance()); }; return ContextAPI22; })() ); var TraceFlags; (function(TraceFlags22) { TraceFlags22[TraceFlags22["NONE"] = 0] = "NONE"; TraceFlags22[TraceFlags22["SAMPLED"] = 1] = "SAMPLED"; })(TraceFlags || (TraceFlags = {})); var INVALID_SPANID = "0000000000000000"; var INVALID_TRACEID = "00000000000000000000000000000000"; var INVALID_SPAN_CONTEXT = { traceId: INVALID_TRACEID, spanId: INVALID_SPANID, traceFlags: TraceFlags.NONE }; var NonRecordingSpan = ( /** @class */ (function() { function NonRecordingSpan22(_spanContext) { if (_spanContext === void 0) { _spanContext = INVALID_SPAN_CONTEXT; } this._spanContext = _spanContext; } NonRecordingSpan22.prototype.spanContext = function() { return this._spanContext; }; NonRecordingSpan22.prototype.setAttribute = function(_key, _value) { return this; }; NonRecordingSpan22.prototype.setAttributes = function(_attributes) { return this; }; NonRecordingSpan22.prototype.addEvent = function(_name, _attributes) { return this; }; NonRecordingSpan22.prototype.addLink = function(_link) { return this; }; NonRecordingSpan22.prototype.addLinks = function(_links) { return this; }; NonRecordingSpan22.prototype.setStatus = function(_status) { return this; }; NonRecordingSpan22.prototype.updateName = function(_name) { return this; }; NonRecordingSpan22.prototype.end = function(_endTime) { }; NonRecordingSpan22.prototype.isRecording = function() { return false; }; NonRecordingSpan22.prototype.recordException = function(_exception, _time) { }; return NonRecordingSpan22; })() ); var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN"); function getSpan(context2) { return context2.getValue(SPAN_KEY) || void 0; } function getActiveSpan() { return getSpan(ContextAPI.getInstance().active()); } function setSpan(context2, span) { return context2.setValue(SPAN_KEY, span); } function deleteSpan(context2) { return context2.deleteValue(SPAN_KEY); } function setSpanContext(context2, spanContext) { return setSpan(context2, new NonRecordingSpan(spanContext)); } function getSpanContext(context2) { var _a173; return (_a173 = getSpan(context2)) === null || _a173 === void 0 ? void 0 : _a173.spanContext(); } var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID; } function isValidSpanId(spanId) { return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; } function isSpanContextValid(spanContext) { return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); } function wrapSpanContext(spanContext) { return new NonRecordingSpan(spanContext); } var contextApi = ContextAPI.getInstance(); var NoopTracer = ( /** @class */ (function() { function NoopTracer22() { } NoopTracer22.prototype.startSpan = function(name173, options, context2) { if (context2 === void 0) { context2 = contextApi.active(); } var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan(); } var parentFromContext = context2 && getSpanContext(context2); if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) { return new NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan(); } }; NoopTracer22.prototype.startActiveSpan = function(name173, arg2, arg3, arg4) { var opts; var ctx; var fn; if (arguments.length < 2) { return; } else if (arguments.length === 2) { fn = arg2; } else if (arguments.length === 3) { opts = arg2; fn = arg3; } else { opts = arg2; ctx = arg3; fn = arg4; } var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); var span = this.startSpan(name173, opts, parentContext); var contextWithSpanSet = setSpan(parentContext, span); return contextApi.with(contextWithSpanSet, fn, void 0, span); }; return NoopTracer22; })() ); function isSpanContext(spanContext) { return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; } var NOOP_TRACER = new NoopTracer(); var ProxyTracer = ( /** @class */ (function() { function ProxyTracer22(_provider, name173, version3, options) { this._provider = _provider; this.name = name173; this.version = version3; this.options = options; } ProxyTracer22.prototype.startSpan = function(name173, options, context2) { return this._getTracer().startSpan(name173, options, context2); }; ProxyTracer22.prototype.startActiveSpan = function(_name, _options, _context, _fn) { var tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); }; ProxyTracer22.prototype._getTracer = function() { if (this._delegate) { return this._delegate; } var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; }; return ProxyTracer22; })() ); var NoopTracerProvider = ( /** @class */ (function() { function NoopTracerProvider22() { } NoopTracerProvider22.prototype.getTracer = function(_name, _version, _options) { return new NoopTracer(); }; return NoopTracerProvider22; })() ); var NOOP_TRACER_PROVIDER = new NoopTracerProvider(); var ProxyTracerProvider = ( /** @class */ (function() { function ProxyTracerProvider22() { } ProxyTracerProvider22.prototype.getTracer = function(name173, version3, options) { var _a173; return (_a173 = this.getDelegateTracer(name173, version3, options)) !== null && _a173 !== void 0 ? _a173 : new ProxyTracer(this, name173, version3, options); }; ProxyTracerProvider22.prototype.getDelegate = function() { var _a173; return (_a173 = this._delegate) !== null && _a173 !== void 0 ? _a173 : NOOP_TRACER_PROVIDER; }; ProxyTracerProvider22.prototype.setDelegate = function(delegate) { this._delegate = delegate; }; ProxyTracerProvider22.prototype.getDelegateTracer = function(name173, version3, options) { var _a173; return (_a173 = this._delegate) === null || _a173 === void 0 ? void 0 : _a173.getTracer(name173, version3, options); }; return ProxyTracerProvider22; })() ); var SpanStatusCode; (function(SpanStatusCode22) { SpanStatusCode22[SpanStatusCode22["UNSET"] = 0] = "UNSET"; SpanStatusCode22[SpanStatusCode22["OK"] = 1] = "OK"; SpanStatusCode22[SpanStatusCode22["ERROR"] = 2] = "ERROR"; })(SpanStatusCode || (SpanStatusCode = {})); var API_NAME3 = "trace"; var TraceAPI = ( /** @class */ (function() { function TraceAPI22() { this._proxyTracerProvider = new ProxyTracerProvider(); this.wrapSpanContext = wrapSpanContext; this.isSpanContextValid = isSpanContextValid; this.deleteSpan = deleteSpan; this.getSpan = getSpan; this.getActiveSpan = getActiveSpan; this.getSpanContext = getSpanContext; this.setSpan = setSpan; this.setSpanContext = setSpanContext; } TraceAPI22.getInstance = function() { if (!this._instance) { this._instance = new TraceAPI22(); } return this._instance; }; TraceAPI22.prototype.setGlobalTracerProvider = function(provider) { var success3 = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance()); if (success3) { this._proxyTracerProvider.setDelegate(provider); } return success3; }; TraceAPI22.prototype.getTracerProvider = function() { return getGlobal(API_NAME3) || this._proxyTracerProvider; }; TraceAPI22.prototype.getTracer = function(name173, version3) { return this.getTracerProvider().getTracer(name173, version3); }; TraceAPI22.prototype.disable = function() { unregisterGlobal(API_NAME3, DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider(); }; return TraceAPI22; })() ); var trace = TraceAPI.getInstance(); var __defProp22 = Object.defineProperty; var __export2 = (target, all) => { for (var name173 in all) __defProp22(target, name173, { get: all[name173], enumerable: true }); }; function prepareResponseHeaders(headers, { contentType, dataStreamVersion }) { const responseHeaders = new Headers(headers != null ? headers : {}); if (!responseHeaders.has("Content-Type")) { responseHeaders.set("Content-Type", contentType); } { responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion); } return responseHeaders; } var UnsupportedModelVersionError = class extends AISDKError { constructor() { super({ name: "AI_UnsupportedModelVersionError", message: `Unsupported model version. AI SDK 4 only supports models that implement specification version "v1". Please upgrade to AI SDK 5 to use this model.` }); } }; var name8 = "AI_InvalidArgumentError"; var marker9 = `vercel.ai.error.${name8}`; var symbol9 = Symbol.for(marker9); var _a9; var InvalidArgumentError2 = class extends AISDKError { constructor({ parameter, value, message }) { super({ name: name8, message: `Invalid argument for parameter ${parameter}: ${message}` }); this[_a9] = true; this.parameter = parameter; this.value = value; } static isInstance(error90) { return AISDKError.hasMarker(error90, marker9); } }; _a9 = symbol9; var name22 = "AI_RetryError"; var marker22 = `vercel.ai.error.${name22}`; var symbol22 = Symbol.for(marker22); var _a22; var RetryError = class extends AISDKError { constructor({ message, reason, errors }) { super({ name: name22, message }); this[_a22] = true; this.reason = reason; this.errors = errors; this.lastError = errors[errors.length - 1]; } static isInstance(error90) { return AISDKError.hasMarker(error90, marker22); } }; _a22 = symbol22; var retryWithExponentialBackoff = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2 } = {}) => async (f) => _retryWithExponentialBackoff(f, { maxRetries, delayInMs: initialDelayInMs, backoffFactor }); async function _retryWithExponentialBackoff(f, { maxRetries, delayInMs, backoffFactor }, errors = []) { try { return await f(); } catch (error90) { if (isAbortError(error90)) { throw error90; } if (maxRetries === 0) { throw error90; } const errorMessage = getErrorMessage2(error90); const newErrors = [...errors, error90]; const tryNumber = newErrors.length; if (tryNumber > maxRetries) { throw new RetryError({ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`, reason: "maxRetriesExceeded", errors: newErrors }); } if (error90 instanceof Error && APICallError.isInstance(error90) && error90.isRetryable === true && tryNumber <= maxRetries) { await delay(delayInMs); return _retryWithExponentialBackoff( f, { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor }, newErrors ); } if (tryNumber === 1) { throw error90; } throw new RetryError({ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`, reason: "errorNotRetryable", errors: newErrors }); } } function prepareRetries({ maxRetries }) { if (maxRetries != null) { if (!Number.isInteger(maxRetries)) { throw new InvalidArgumentError2({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be an integer" }); } if (maxRetries < 0) { throw new InvalidArgumentError2({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be >= 0" }); } } const maxRetriesResult = maxRetries != null ? maxRetries : 2; return { maxRetries: maxRetriesResult, retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult }) }; } function assembleOperationName({ operationId, telemetry }) { return { // standardized operation and resource name: "operation.name": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`, "resource.name": telemetry == null ? void 0 : telemetry.functionId, // detailed, AI SDK specific data: "ai.operationId": operationId, "ai.telemetry.functionId": telemetry == null ? void 0 : telemetry.functionId }; } function getBaseTelemetryAttributes({ model, settings, telemetry, headers }) { var _a173; return { "ai.model.provider": model.provider, "ai.model.id": model.modelId, // settings: ...Object.entries(settings).reduce((attributes, [key, value]) => { attributes[`ai.settings.${key}`] = value; return attributes; }, {}), // add metadata as attributes: ...Object.entries((_a173 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a173 : {}).reduce( (attributes, [key, value]) => { attributes[`ai.telemetry.metadata.${key}`] = value; return attributes; }, {} ), // request headers ...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => { if (value !== void 0) { attributes[`ai.request.headers.${key}`] = value; } return attributes; }, {}) }; } var noopTracer = { startSpan() { return noopSpan; }, startActiveSpan(name173, arg1, arg2, arg3) { if (typeof arg1 === "function") { return arg1(noopSpan); } if (typeof arg2 === "function") { return arg2(noopSpan); } if (typeof arg3 === "function") { return arg3(noopSpan); } } }; var noopSpan = { spanContext() { return noopSpanContext; }, setAttribute() { return this; }, setAttributes() { return this; }, addEvent() { return this; }, addLink() { return this; }, addLinks() { return this; }, setStatus() { return this; }, updateName() { return this; }, end() { return this; }, isRecording() { return false; }, recordException() { return this; } }; var noopSpanContext = { traceId: "", spanId: "", traceFlags: 0 }; function getTracer({ isEnabled = false, tracer } = {}) { if (!isEnabled) { return noopTracer; } if (tracer) { return tracer; } return trace.getTracer("ai"); } function recordSpan({ name: name173, tracer, attributes, fn, endWhenDone = true }) { return tracer.startActiveSpan(name173, { attributes }, async (span) => { try { const result = await fn(span); if (endWhenDone) { span.end(); } return result; } catch (error90) { try { recordErrorOnSpan(span, error90); } finally { span.end(); } throw error90; } }); } function recordErrorOnSpan(span, error90) { if (error90 instanceof Error) { span.recordException({ name: error90.name, message: error90.message, stack: error90.stack }); span.setStatus({ code: SpanStatusCode.ERROR, message: error90.message }); } else { span.setStatus({ code: SpanStatusCode.ERROR }); } } function selectTelemetryAttributes({ telemetry, attributes }) { if ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) { return {}; } return Object.entries(attributes).reduce((attributes2, [key, value]) => { if (value === void 0) { return attributes2; } if (typeof value === "object" && "input" in value && typeof value.input === "function") { if ((telemetry == null ? void 0 : telemetry.recordInputs) === false) { return attributes2; } const result = value.input(); return result === void 0 ? attributes2 : { ...attributes2, [key]: result }; } if (typeof value === "object" && "output" in value && typeof value.output === "function") { if ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) { return attributes2; } const result = value.output(); return result === void 0 ? attributes2 : { ...attributes2, [key]: result }; } return { ...attributes2, [key]: value }; }, {}); } function splitArray(array4, chunkSize) { if (chunkSize <= 0) { throw new Error("chunkSize must be greater than 0"); } const result = []; for (let i = 0; i < array4.length; i += chunkSize) { result.push(array4.slice(i, i + chunkSize)); } return result; } async function embedMany({ model, values, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry }) { if (typeof model === "string" || model.specificationVersion !== "v1") { throw new UnsupportedModelVersionError(); } const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg }); const baseTelemetryAttributes = getBaseTelemetryAttributes({ model, telemetry, headers, settings: { maxRetries } }); const tracer = getTracer(telemetry); return recordSpan({ name: "ai.embedMany", attributes: selectTelemetryAttributes({ telemetry, attributes: { ...assembleOperationName({ operationId: "ai.embedMany", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => values.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (span) => { const maxEmbeddingsPerCall = model.maxEmbeddingsPerCall; if (maxEmbeddingsPerCall == null) { const { embeddings: embeddings2, usage } = await retry(() => { return recordSpan({ name: "ai.embedMany.doEmbed", attributes: selectTelemetryAttributes({ telemetry, attributes: { ...assembleOperationName({ operationId: "ai.embedMany.doEmbed", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => values.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (doEmbedSpan) => { var _a173; const modelResponse = await model.doEmbed({ values, abortSignal, headers }); const embeddings3 = modelResponse.embeddings; const usage2 = (_a173 = modelResponse.usage) != null ? _a173 : { tokens: NaN }; doEmbedSpan.setAttributes( selectTelemetryAttributes({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings3.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": usage2.tokens } }) ); return { embeddings: embeddings3, usage: usage2 }; } }); }); span.setAttributes( selectTelemetryAttributes({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": usage.tokens } }) ); return new DefaultEmbedManyResult({ values, embeddings: embeddings2, usage }); } const valueChunks = splitArray(values, maxEmbeddingsPerCall); const embeddings = []; let tokens = 0; for (const chunk of valueChunks) { const { embeddings: responseEmbeddings, usage } = await retry(() => { return recordSpan({ name: "ai.embedMany.doEmbed", attributes: selectTelemetryAttributes({ telemetry, attributes: { ...assembleOperationName({ operationId: "ai.embedMany.doEmbed", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => chunk.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (doEmbedSpan) => { var _a173; const modelResponse = await model.doEmbed({ values: chunk, abortSignal, headers }); const embeddings2 = modelResponse.embeddings; const usage2 = (_a173 = modelResponse.usage) != null ? _a173 : { tokens: NaN }; doEmbedSpan.setAttributes( selectTelemetryAttributes({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": usage2.tokens } }) ); return { embeddings: embeddings2, usage: usage2 }; } }); }); embeddings.push(...responseEmbeddings); tokens += usage.tokens; } span.setAttributes( selectTelemetryAttributes({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": tokens } }) ); return new DefaultEmbedManyResult({ values, embeddings, usage: { tokens } }); } }); } var DefaultEmbedManyResult = class { constructor(options) { this.values = options.values; this.embeddings = options.embeddings; this.usage = options.usage; } }; var name42 = "AI_NoObjectGeneratedError"; var marker42 = `vercel.ai.error.${name42}`; var symbol42 = Symbol.for(marker42); var _a42; var NoObjectGeneratedError = class extends AISDKError { constructor({ message = "No object generated.", cause, text: text22, response, usage, finishReason }) { super({ name: name42, message, cause }); this[_a42] = true; this.text = text22; this.response = response; this.usage = usage; this.finishReason = finishReason; } static isInstance(error90) { return AISDKError.hasMarker(error90, marker42); } }; _a42 = symbol42; var dataContentSchema = external_exports.union([ external_exports.string(), external_exports.instanceof(Uint8Array), external_exports.instanceof(ArrayBuffer), external_exports.custom( // Buffer might not be available in some environments such as CloudFlare: (value) => { var _a173, _b19; return (_b19 = (_a173 = globalThis.Buffer) == null ? void 0 : _a173.isBuffer(value)) != null ? _b19 : false; }, { message: "Must be a Buffer" } ) ]); var jsonValueSchema = external_exports.lazy( () => external_exports.union([ external_exports.null(), external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.record(external_exports.string(), jsonValueSchema), external_exports.array(jsonValueSchema) ]) ); var providerMetadataSchema = external_exports.record( external_exports.string(), external_exports.record(external_exports.string(), jsonValueSchema) ); var toolResultContentSchema = external_exports.array( external_exports.union([ external_exports.object({ type: external_exports.literal("text"), text: external_exports.string() }), external_exports.object({ type: external_exports.literal("image"), data: external_exports.string(), mimeType: external_exports.string().optional() }) ]) ); var textPartSchema = external_exports.object({ type: external_exports.literal("text"), text: external_exports.string(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var imagePartSchema = external_exports.object({ type: external_exports.literal("image"), image: external_exports.union([dataContentSchema, external_exports.instanceof(URL)]), mimeType: external_exports.string().optional(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var filePartSchema = external_exports.object({ type: external_exports.literal("file"), data: external_exports.union([dataContentSchema, external_exports.instanceof(URL)]), filename: external_exports.string().optional(), mimeType: external_exports.string(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var reasoningPartSchema = external_exports.object({ type: external_exports.literal("reasoning"), text: external_exports.string(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var redactedReasoningPartSchema = external_exports.object({ type: external_exports.literal("redacted-reasoning"), data: external_exports.string(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var toolCallPartSchema = external_exports.object({ type: external_exports.literal("tool-call"), toolCallId: external_exports.string(), toolName: external_exports.string(), args: external_exports.unknown(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var toolResultPartSchema = external_exports.object({ type: external_exports.literal("tool-result"), toolCallId: external_exports.string(), toolName: external_exports.string(), result: external_exports.unknown(), content: toolResultContentSchema.optional(), isError: external_exports.boolean().optional(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var coreSystemMessageSchema = external_exports.object({ role: external_exports.literal("system"), content: external_exports.string(), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var coreUserMessageSchema = external_exports.object({ role: external_exports.literal("user"), content: external_exports.union([ external_exports.string(), external_exports.array(external_exports.union([textPartSchema, imagePartSchema, filePartSchema])) ]), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var coreAssistantMessageSchema = external_exports.object({ role: external_exports.literal("assistant"), content: external_exports.union([ external_exports.string(), external_exports.array( external_exports.union([ textPartSchema, filePartSchema, reasoningPartSchema, redactedReasoningPartSchema, toolCallPartSchema ]) ) ]), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); var coreToolMessageSchema = external_exports.object({ role: external_exports.literal("tool"), content: external_exports.array(toolResultPartSchema), providerOptions: providerMetadataSchema.optional(), experimental_providerMetadata: providerMetadataSchema.optional() }); external_exports.union([ coreSystemMessageSchema, coreUserMessageSchema, coreAssistantMessageSchema, coreToolMessageSchema ]); var DEFAULT_SCHEMA_PREFIX = "JSON schema:"; var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above."; var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON."; function injectJsonInstruction({ prompt, schema, schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0, schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX }) { return [ prompt != null && prompt.length > 0 ? prompt : void 0, prompt != null && prompt.length > 0 ? "" : void 0, // add a newline if prompt is not null schemaPrefix, schema != null ? JSON.stringify(schema) : void 0, schemaSuffix ].filter((line) => line != null).join("\n"); } createIdGenerator({ prefix: "aiobj", size: 24 }); createIdGenerator({ prefix: "aiobj", size: 24 }); createIdGenerator({ prefix: "aitxt", size: 24 }); createIdGenerator({ prefix: "msg", size: 24 }); var output_exports = {}; __export2(output_exports, { object: () => object, text: () => text }); var text = () => ({ type: "text", responseFormat: () => ({ type: "text" }), injectIntoSystemPrompt({ system }) { return system; }, parsePartial({ text: text22 }) { return { partial: text22 }; }, parseOutput({ text: text22 }) { return text22; } }); var object = ({ schema: inputSchema }) => { const schema = asSchema(inputSchema); return { type: "object", responseFormat: ({ model }) => ({ type: "json", schema: model.supportsStructuredOutputs ? schema.jsonSchema : void 0 }), injectIntoSystemPrompt({ system, model }) { return model.supportsStructuredOutputs ? system : injectJsonInstruction({ prompt: system, schema: schema.jsonSchema }); }, parsePartial({ text: text22 }) { const result = parsePartialJson(text22); switch (result.state) { case "failed-parse": case "undefined-input": return void 0; case "repaired-parse": case "successful-parse": return { // Note: currently no validation of partial results: partial: result.value }; default: { const _exhaustiveCheck = result.state; throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`); } } }, parseOutput({ text: text22 }, context2) { const parseResult = safeParseJSON({ text: text22 }); if (!parseResult.success) { throw new NoObjectGeneratedError({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } const validationResult = safeValidateTypes({ value: parseResult.value, schema }); if (!validationResult.success) { throw new NoObjectGeneratedError({ message: "No object generated: response did not match schema.", cause: validationResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } return validationResult.value; } }; }; function mergeStreams(stream1, stream2) { const reader1 = stream1.getReader(); const reader2 = stream2.getReader(); let lastRead1 = void 0; let lastRead2 = void 0; let stream1Done = false; let stream2Done = false; async function readStream1(controller) { try { if (lastRead1 == null) { lastRead1 = reader1.read(); } const result = await lastRead1; lastRead1 = void 0; if (!result.done) { controller.enqueue(result.value); } else { controller.close(); } } catch (error90) { controller.error(error90); } } async function readStream2(controller) { try { if (lastRead2 == null) { lastRead2 = reader2.read(); } const result = await lastRead2; lastRead2 = void 0; if (!result.done) { controller.enqueue(result.value); } else { controller.close(); } } catch (error90) { controller.error(error90); } } return new ReadableStream({ async pull(controller) { try { if (stream1Done) { await readStream2(controller); return; } if (stream2Done) { await readStream1(controller); return; } if (lastRead1 == null) { lastRead1 = reader1.read(); } if (lastRead2 == null) { lastRead2 = reader2.read(); } const { result, reader } = await Promise.race([ lastRead1.then((result2) => ({ result: result2, reader: reader1 })), lastRead2.then((result2) => ({ result: result2, reader: reader2 })) ]); if (!result.done) { controller.enqueue(result.value); } if (reader === reader1) { lastRead1 = void 0; if (result.done) { await readStream2(controller); stream1Done = true; } } else { lastRead2 = void 0; if (result.done) { stream2Done = true; await readStream1(controller); } } } catch (error90) { controller.error(error90); } }, cancel() { reader1.cancel(); reader2.cancel(); } }); } createIdGenerator({ prefix: "aitxt", size: 24 }); createIdGenerator({ prefix: "msg", size: 24 }); var ClientOrServerImplementationSchema = external_exports.object({ name: external_exports.string(), version: external_exports.string() }).passthrough(); var BaseParamsSchema = external_exports.object({ _meta: external_exports.optional(external_exports.object({}).passthrough()) }).passthrough(); var ResultSchema = BaseParamsSchema; var RequestSchema = external_exports.object({ method: external_exports.string(), params: external_exports.optional(BaseParamsSchema) }); var ServerCapabilitiesSchema = external_exports.object({ experimental: external_exports.optional(external_exports.object({}).passthrough()), logging: external_exports.optional(external_exports.object({}).passthrough()), prompts: external_exports.optional( external_exports.object({ listChanged: external_exports.optional(external_exports.boolean()) }).passthrough() ), resources: external_exports.optional( external_exports.object({ subscribe: external_exports.optional(external_exports.boolean()), listChanged: external_exports.optional(external_exports.boolean()) }).passthrough() ), tools: external_exports.optional( external_exports.object({ listChanged: external_exports.optional(external_exports.boolean()) }).passthrough() ) }).passthrough(); ResultSchema.extend({ protocolVersion: external_exports.string(), capabilities: ServerCapabilitiesSchema, serverInfo: ClientOrServerImplementationSchema, instructions: external_exports.optional(external_exports.string()) }); var PaginatedResultSchema = ResultSchema.extend({ nextCursor: external_exports.optional(external_exports.string()) }); var ToolSchema = external_exports.object({ name: external_exports.string(), description: external_exports.optional(external_exports.string()), inputSchema: external_exports.object({ type: external_exports.literal("object"), properties: external_exports.optional(external_exports.object({}).passthrough()) }).passthrough() }).passthrough(); PaginatedResultSchema.extend({ tools: external_exports.array(ToolSchema) }); var TextContentSchema = external_exports.object({ type: external_exports.literal("text"), text: external_exports.string() }).passthrough(); var ImageContentSchema = external_exports.object({ type: external_exports.literal("image"), data: external_exports.string().base64(), mimeType: external_exports.string() }).passthrough(); var ResourceContentsSchema = external_exports.object({ /** * The URI of this resource. */ uri: external_exports.string(), /** * The MIME type of this resource, if known. */ mimeType: external_exports.optional(external_exports.string()) }).passthrough(); var TextResourceContentsSchema = ResourceContentsSchema.extend({ text: external_exports.string() }); var BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: external_exports.string().base64() }); var EmbeddedResourceSchema = external_exports.object({ type: external_exports.literal("resource"), resource: external_exports.union([TextResourceContentsSchema, BlobResourceContentsSchema]) }).passthrough(); ResultSchema.extend({ content: external_exports.array( external_exports.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema]) ), isError: external_exports.boolean().default(false).optional() }).or( ResultSchema.extend({ toolResult: external_exports.unknown() }) ); var JSONRPC_VERSION = "2.0"; var JSONRPCRequestSchema = external_exports.object({ jsonrpc: external_exports.literal(JSONRPC_VERSION), id: external_exports.union([external_exports.string(), external_exports.number().int()]) }).merge(RequestSchema).strict(); var JSONRPCResponseSchema = external_exports.object({ jsonrpc: external_exports.literal(JSONRPC_VERSION), id: external_exports.union([external_exports.string(), external_exports.number().int()]), result: ResultSchema }).strict(); var JSONRPCErrorSchema = external_exports.object({ jsonrpc: external_exports.literal(JSONRPC_VERSION), id: external_exports.union([external_exports.string(), external_exports.number().int()]), error: external_exports.object({ code: external_exports.number().int(), message: external_exports.string(), data: external_exports.optional(external_exports.unknown()) }) }).strict(); var JSONRPCNotificationSchema = external_exports.object({ jsonrpc: external_exports.literal(JSONRPC_VERSION) }).merge( external_exports.object({ method: external_exports.string(), params: external_exports.optional(BaseParamsSchema) }) ).strict(); external_exports.union([ JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema ]); var langchain_adapter_exports = {}; __export2(langchain_adapter_exports, { mergeIntoDataStream: () => mergeIntoDataStream, toDataStream: () => toDataStream, toDataStreamResponse: () => toDataStreamResponse }); function createCallbacksTransformer(callbacks = {}) { const textEncoder = new TextEncoder(); let aggregatedResponse = ""; return new TransformStream({ async start() { if (callbacks.onStart) await callbacks.onStart(); }, async transform(message, controller) { controller.enqueue(textEncoder.encode(message)); aggregatedResponse += message; if (callbacks.onToken) await callbacks.onToken(message); if (callbacks.onText && typeof message === "string") { await callbacks.onText(message); } }, async flush() { if (callbacks.onCompletion) { await callbacks.onCompletion(aggregatedResponse); } if (callbacks.onFinal) { await callbacks.onFinal(aggregatedResponse); } } }); } function toDataStreamInternal(stream, callbacks) { return stream.pipeThrough( new TransformStream({ transform: async (value, controller) => { var _a173; if (typeof value === "string") { controller.enqueue(value); return; } if ("event" in value) { if (value.event === "on_chat_model_stream") { forwardAIMessageChunk( (_a173 = value.data) == null ? void 0 : _a173.chunk, controller ); } return; } forwardAIMessageChunk(value, controller); } }) ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough( new TransformStream({ transform: async (chunk, controller) => { controller.enqueue(formatDataStreamPart("text", chunk)); } }) ); } function toDataStream(stream, callbacks) { return toDataStreamInternal(stream, callbacks).pipeThrough( new TextEncoderStream() ); } function toDataStreamResponse(stream, options) { var _a173; const dataStream = toDataStreamInternal( stream, options == null ? void 0 : options.callbacks ).pipeThrough(new TextEncoderStream()); const data = options == null ? void 0 : options.data; const init = options == null ? void 0 : options.init; const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream; return new Response(responseStream, { status: (_a173 = init == null ? void 0 : init.status) != null ? _a173 : 200, statusText: init == null ? void 0 : init.statusText, headers: prepareResponseHeaders(init == null ? void 0 : init.headers, { contentType: "text/plain; charset=utf-8", dataStreamVersion: "v1" }) }); } function mergeIntoDataStream(stream, options) { options.dataStream.merge(toDataStreamInternal(stream, options.callbacks)); } function forwardAIMessageChunk(chunk, controller) { if (typeof chunk.content === "string") { controller.enqueue(chunk.content); } else { const content = chunk.content; for (const item of content) { if (item.type === "text") { controller.enqueue(item.text); } } } } var llamaindex_adapter_exports = {}; __export2(llamaindex_adapter_exports, { mergeIntoDataStream: () => mergeIntoDataStream2, toDataStream: () => toDataStream2, toDataStreamResponse: () => toDataStreamResponse2 }); function toDataStreamInternal2(stream, callbacks) { const trimStart = trimStartOfStream(); return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough( new TransformStream({ async transform(message, controller) { controller.enqueue(trimStart(message.delta)); } }) ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough( new TransformStream({ transform: async (chunk, controller) => { controller.enqueue(formatDataStreamPart("text", chunk)); } }) ); } function toDataStream2(stream, callbacks) { return toDataStreamInternal2(stream, callbacks).pipeThrough( new TextEncoderStream() ); } function toDataStreamResponse2(stream, options = {}) { var _a173; const { init, data, callbacks } = options; const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough( new TextEncoderStream() ); const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream; return new Response(responseStream, { status: (_a173 = init == null ? void 0 : init.status) != null ? _a173 : 200, statusText: init == null ? void 0 : init.statusText, headers: prepareResponseHeaders(init == null ? void 0 : init.headers, { contentType: "text/plain; charset=utf-8", dataStreamVersion: "v1" }) }); } function mergeIntoDataStream2(stream, options) { options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks)); } function trimStartOfStream() { let isStreamStart = true; return (text22) => { if (isStreamStart) { text22 = text22.trimStart(); if (text22) isStreamStart = false; } return text22; }; } var external_exports2 = {}; __export(external_exports2, { $brand: () => $brand, $input: () => $input, $output: () => $output, NEVER: () => NEVER2, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny2, ZodArray: () => ZodArray2, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt2, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean2, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch2, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate2, ZodDefault: () => ZodDefault2, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum2, ZodError: () => ZodError2, ZodExactOptional: () => ZodExactOptional, ZodFile: () => ZodFile, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, ZodFunction: () => ZodFunction2, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, ZodIntersection: () => ZodIntersection2, ZodIssueCode: () => ZodIssueCode2, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy2, ZodLiteral: () => ZodLiteral2, ZodMAC: () => ZodMAC, ZodMap: () => ZodMap2, ZodNaN: () => ZodNaN2, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever2, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull2, ZodNullable: () => ZodNullable2, ZodNumber: () => ZodNumber2, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject2, ZodOptional: () => ZodOptional2, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPreprocess: () => ZodPreprocess, ZodPromise: () => ZodPromise2, ZodReadonly: () => ZodReadonly2, ZodRealError: () => ZodRealError, ZodRecord: () => ZodRecord2, ZodSet: () => ZodSet2, ZodString: () => ZodString2, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol2, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple2, ZodType: () => ZodType2, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined2, ZodUnion: () => ZodUnion2, ZodUnknown: () => ZodUnknown2, ZodVoid: () => ZodVoid2, ZodXID: () => ZodXID, ZodXor: () => ZodXor, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, clone: () => clone, codec: () => codec, coerce: () => coerce_exports, config: () => config, core: () => core_exports2, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom2, date: () => date3, decode: () => decode2, decodeAsync: () => decodeAsync2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, encode: () => encode2, encodeAsync: () => encodeAsync2, endsWith: () => _endsWith, enum: () => _enum2, exactOptional: () => exactOptional, file: () => file, flattenError: () => flattenError, float32: () => float32, float64: () => float64, formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, getErrorMap: () => getErrorMap2, globalRegistry: () => globalRegistry, gt: () => _gt, gte: () => _gte, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, includes: () => _includes, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, invertCodec: () => invertCodec, ipv4: () => ipv42, ipv6: () => ipv62, iso: () => iso_exports, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, length: () => _length, literal: () => literal, locales: () => locales_exports, looseObject: () => looseObject, looseRecord: () => looseRecord, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, mac: () => mac2, map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, negative: () => _negative, never: () => never, nonnegative: () => _nonnegative, nonoptional: () => nonoptional, nonpositive: () => _nonpositive, normalize: () => _normalize, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object2, optional: () => optional, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, partialRecord: () => partialRecord, pipe: () => pipe, positive: () => _positive, prefault: () => prefault, preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, property: () => _property, readonly: () => readonly, record: () => record, refine: () => refine, regex: () => _regex, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode2, safeDecodeAsync: () => safeDecodeAsync2, safeEncode: () => safeEncode2, safeEncodeAsync: () => safeEncodeAsync2, safeParse: () => safeParse2, safeParseAsync: () => safeParseAsync2, set: () => set, setErrorMap: () => setErrorMap2, size: () => _size, slugify: () => _slugify, startsWith: () => _startsWith, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol17, templateLiteral: () => templateLiteral, toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, uppercase: () => _uppercase, url: () => url, util: () => util_exports, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2, xor: () => xor }); var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, $ZodArray: () => $ZodArray, $ZodAsyncError: () => $ZodAsyncError, $ZodBase64: () => $ZodBase64, $ZodBase64URL: () => $ZodBase64URL, $ZodBigInt: () => $ZodBigInt, $ZodBigIntFormat: () => $ZodBigIntFormat, $ZodBoolean: () => $ZodBoolean, $ZodCIDRv4: () => $ZodCIDRv4, $ZodCIDRv6: () => $ZodCIDRv6, $ZodCUID: () => $ZodCUID, $ZodCUID2: () => $ZodCUID2, $ZodCatch: () => $ZodCatch, $ZodCheck: () => $ZodCheck, $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, $ZodCheckEndsWith: () => $ZodCheckEndsWith, $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, $ZodCheckIncludes: () => $ZodCheckIncludes, $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, $ZodCheckLessThan: () => $ZodCheckLessThan, $ZodCheckLowerCase: () => $ZodCheckLowerCase, $ZodCheckMaxLength: () => $ZodCheckMaxLength, $ZodCheckMaxSize: () => $ZodCheckMaxSize, $ZodCheckMimeType: () => $ZodCheckMimeType, $ZodCheckMinLength: () => $ZodCheckMinLength, $ZodCheckMinSize: () => $ZodCheckMinSize, $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, $ZodCheckStartsWith: () => $ZodCheckStartsWith, $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, $ZodE164: () => $ZodE164, $ZodEmail: () => $ZodEmail, $ZodEmoji: () => $ZodEmoji, $ZodEncodeError: () => $ZodEncodeError, $ZodEnum: () => $ZodEnum, $ZodError: () => $ZodError, $ZodExactOptional: () => $ZodExactOptional, $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, $ZodISODateTime: () => $ZodISODateTime, $ZodISODuration: () => $ZodISODuration, $ZodISOTime: () => $ZodISOTime, $ZodIntersection: () => $ZodIntersection, $ZodJWT: () => $ZodJWT, $ZodKSUID: () => $ZodKSUID, $ZodLazy: () => $ZodLazy, $ZodLiteral: () => $ZodLiteral, $ZodMAC: () => $ZodMAC, $ZodMap: () => $ZodMap, $ZodNaN: () => $ZodNaN, $ZodNanoID: () => $ZodNanoID, $ZodNever: () => $ZodNever, $ZodNonOptional: () => $ZodNonOptional, $ZodNull: () => $ZodNull, $ZodNullable: () => $ZodNullable, $ZodNumber: () => $ZodNumber, $ZodNumberFormat: () => $ZodNumberFormat, $ZodObject: () => $ZodObject, $ZodObjectJIT: () => $ZodObjectJIT, $ZodOptional: () => $ZodOptional, $ZodPipe: () => $ZodPipe, $ZodPrefault: () => $ZodPrefault, $ZodPreprocess: () => $ZodPreprocess, $ZodPromise: () => $ZodPromise, $ZodReadonly: () => $ZodReadonly, $ZodRealError: () => $ZodRealError, $ZodRecord: () => $ZodRecord, $ZodRegistry: () => $ZodRegistry, $ZodSet: () => $ZodSet, $ZodString: () => $ZodString, $ZodStringFormat: () => $ZodStringFormat, $ZodSuccess: () => $ZodSuccess, $ZodSymbol: () => $ZodSymbol, $ZodTemplateLiteral: () => $ZodTemplateLiteral, $ZodTransform: () => $ZodTransform, $ZodTuple: () => $ZodTuple, $ZodType: () => $ZodType, $ZodULID: () => $ZodULID, $ZodURL: () => $ZodURL, $ZodUUID: () => $ZodUUID, $ZodUndefined: () => $ZodUndefined, $ZodUnion: () => $ZodUnion, $ZodUnknown: () => $ZodUnknown, $ZodVoid: () => $ZodVoid, $ZodXID: () => $ZodXID, $ZodXor: () => $ZodXor, $brand: () => $brand, $constructor: () => $constructor, $input: () => $input, $output: () => $output, Doc: () => Doc, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER2, TimePrecision: () => TimePrecision, _any: () => _any, _array: () => _array, _base64: () => _base64, _base64url: () => _base64url, _bigint: () => _bigint, _boolean: () => _boolean, _catch: () => _catch, _check: () => _check, _cidrv4: () => _cidrv4, _cidrv6: () => _cidrv6, _coercedBigint: () => _coercedBigint, _coercedBoolean: () => _coercedBoolean, _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, _date: () => _date, _decode: () => _decode, _decodeAsync: () => _decodeAsync, _default: () => _default, _discriminatedUnion: () => _discriminatedUnion, _e164: () => _e164, _email: () => _email, _emoji: () => _emoji2, _encode: () => _encode, _encodeAsync: () => _encodeAsync, _endsWith: () => _endsWith, _enum: () => _enum, _file: () => _file, _float32: () => _float32, _float64: () => _float64, _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, _includes: () => _includes, _int: () => _int, _int32: () => _int32, _int64: () => _int64, _intersection: () => _intersection, _ipv4: () => _ipv4, _ipv6: () => _ipv6, _isoDate: () => _isoDate, _isoDateTime: () => _isoDateTime, _isoDuration: () => _isoDuration, _isoTime: () => _isoTime, _jwt: () => _jwt, _ksuid: () => _ksuid, _lazy: () => _lazy, _length: () => _length, _literal: () => _literal, _lowercase: () => _lowercase, _lt: () => _lt, _lte: () => _lte, _mac: () => _mac, _map: () => _map, _max: () => _lte, _maxLength: () => _maxLength, _maxSize: () => _maxSize, _mime: () => _mime, _min: () => _gte, _minLength: () => _minLength, _minSize: () => _minSize, _multipleOf: () => _multipleOf, _nan: () => _nan, _nanoid: () => _nanoid, _nativeEnum: () => _nativeEnum, _negative: () => _negative, _never: () => _never, _nonnegative: () => _nonnegative, _nonoptional: () => _nonoptional, _nonpositive: () => _nonpositive, _normalize: () => _normalize, _null: () => _null2, _nullable: () => _nullable, _number: () => _number, _optional: () => _optional, _overwrite: () => _overwrite, _parse: () => _parse, _parseAsync: () => _parseAsync, _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, _property: () => _property, _readonly: () => _readonly, _record: () => _record, _refine: () => _refine, _regex: () => _regex, _safeDecode: () => _safeDecode, _safeDecodeAsync: () => _safeDecodeAsync, _safeEncode: () => _safeEncode, _safeEncodeAsync: () => _safeEncodeAsync, _safeParse: () => _safeParse, _safeParseAsync: () => _safeParseAsync, _set: () => _set, _size: () => _size, _slugify: () => _slugify, _startsWith: () => _startsWith, _string: () => _string, _stringFormat: () => _stringFormat, _stringbool: () => _stringbool, _success: () => _success, _superRefine: () => _superRefine, _symbol: () => _symbol, _templateLiteral: () => _templateLiteral, _toLowerCase: () => _toLowerCase, _toUpperCase: () => _toUpperCase, _transform: () => _transform, _trim: () => _trim, _tuple: () => _tuple, _uint32: () => _uint32, _uint64: () => _uint64, _ulid: () => _ulid, _undefined: () => _undefined2, _union: () => _union, _unknown: () => _unknown, _uppercase: () => _uppercase, _url: () => _url, _uuid: () => _uuid, _uuidv4: () => _uuidv4, _uuidv6: () => _uuidv6, _uuidv7: () => _uuidv7, _void: () => _void, _xid: () => _xid, _xor: () => _xor, clone: () => clone, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, decode: () => decode, decodeAsync: () => decodeAsync, describe: () => describe, encode: () => encode, encodeAsync: () => encodeAsync, extractDefs: () => extractDefs, finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, initializeContext: () => initializeContext, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, isValidJWT: () => isValidJWT2, locales: () => locales_exports, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, prettifyError: () => prettifyError, process: () => process2, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, safeDecodeAsync: () => safeDecodeAsync, safeEncode: () => safeEncode, safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, treeifyError: () => treeifyError, util: () => util_exports, version: () => version }); var _a17; var NEVER2 = /* @__PURE__ */ Object.freeze({ status: "aborted" }); // @__NO_SIDE_EFFECTS__ function $constructor(name21, initializer5, params) { function init(inst, def) { if (!inst._zod) { Object.defineProperty(inst, "_zod", { value: { def, constr: _, traits: /* @__PURE__ */ new Set() }, enumerable: false }); } if (inst._zod.traits.has(name21)) { return; } inst._zod.traits.add(name21); initializer5(inst, def); const proto = _.prototype; const keys = Object.keys(proto); for (let i = 0; i < keys.length; i++) { const k = keys[i]; if (!(k in inst)) { inst[k] = proto[k].bind(inst); } } } const Parent = params?.Parent ?? Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name21 }); function _(def) { var _a282; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a282 = inst._zod).deferred ?? (_a282.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(name21); } }); Object.defineProperty(_, "name", { value: name21 }); return _; } var $brand = /* @__PURE__ */ Symbol("zod_brand"); var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; var $ZodEncodeError = class extends Error { constructor(name21) { super(`Encountered unidirectional transform during encode: ${name21}`); this.name = "ZodEncodeError"; } }; (_a17 = globalThis).__zod_globalConfig ?? (_a17.__zod_globalConfig = {}); var globalConfig = globalThis.__zod_globalConfig; function config(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, allowsEval: () => allowsEval, assert: () => assert, assertEqual: () => assertEqual, assertIs: () => assertIs, assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, captureStackTrace: () => captureStackTrace, cleanEnum: () => cleanEnum, cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, esc: () => esc, escapeRegex: () => escapeRegex, explicitlyAborted: () => explicitlyAborted, extend: () => extend, finalizeIssue: () => finalizeIssue, floatSafeRemainder: () => floatSafeRemainder2, getElementAtPath: () => getElementAtPath, getEnumValues: () => getEnumValues, getLengthableOrigin: () => getLengthableOrigin, getParsedType: () => getParsedType2, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, isObject: () => isObject, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, nullish: () => nullish, numKeys: () => numKeys, objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, parsedType: () => parsedType, partial: () => partial, pick: () => pick, prefixIssues: () => prefixIssues, primitiveTypes: () => primitiveTypes, promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, unwrapMessage: () => unwrapMessage }); function assertEqual(val) { return val; } function assertNotEqual(val) { return val; } function assertIs(_arg) { } function assertNever(_x) { throw new Error("Unexpected value in exhaustive check"); } function assert(_) { } function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); return values; } function joinValues(array4, separator = "|") { return array4.map((val) => stringifyPrimitive(val)).join(separator); } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { return { get value() { { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } } }; } function nullish(input) { return input === null || input === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function floatSafeRemainder2(val, step) { const ratio = val / step; const roundedRatio = Math.round(ratio); const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); if (Math.abs(ratio - roundedRatio) < tolerance) return 0; return ratio - roundedRatio; } var EVALUATING = /* @__PURE__ */ Symbol("evaluating"); function defineLazy(object62, key, getter) { let value = void 0; Object.defineProperty(object62, key, { get() { if (value === EVALUATING) { return void 0; } if (value === void 0) { value = EVALUATING; value = getter(); } return value; }, set(v) { Object.defineProperty(object62, key, { value: v // configurable: true, }); }, configurable: true }); } function objectClone(obj) { return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { const descriptors = Object.getOwnPropertyDescriptors(def); Object.assign(mergedDescriptors, descriptors); } return Object.defineProperties({}, mergedDescriptors); } function cloneDef(schema) { return mergeDefs(schema._zod.def); } function getElementAtPath(obj, path) { if (!path) return obj; return path.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key) => promisesObj[key]); return Promise.all(promises).then((results) => { const resolvedObj = {}; for (let i = 0; i < keys.length; i++) { resolvedObj[keys[i]] = results[i]; } return resolvedObj; }); } function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; for (let i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } function esc(str) { return JSON.stringify(str); } function slugify(input) { return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval = /* @__PURE__ */ cached(() => { if (globalConfig.jitless) { return false; } if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { return false; } try { const F2 = Function; new F2(""); return true; } catch (_) { return false; } }); function isPlainObject(o) { if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; if (typeof ctor !== "function") return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function shallowClone(o) { if (isPlainObject(o)) return { ...o }; if (Array.isArray(o)) return [...o]; if (o instanceof Map) return new Map(o); if (o instanceof Set) return new Set(o); return o; } function numKeys(data) { let keyCount = 0; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { keyCount++; } } return keyCount; } var getParsedType2 = (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}`); } }; var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); var primitiveTypes = /* @__PURE__ */ new Set([ "string", "number", "bigint", "boolean", "symbol", "undefined" ]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function clone(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== void 0) { if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function createTransparentProxy(getter) { let target; return new Proxy({}, { get(_, prop, receiver) { target ?? (target = getter()); return Reflect.get(target, prop, receiver); }, set(_, prop, value, receiver) { target ?? (target = getter()); return Reflect.set(target, prop, value, receiver); }, has(_, prop) { target ?? (target = getter()); return Reflect.has(target, prop); }, deleteProperty(_, prop) { target ?? (target = getter()); return Reflect.deleteProperty(target, prop); }, ownKeys(_) { target ?? (target = getter()); return Reflect.ownKeys(target); }, getOwnPropertyDescriptor(_, prop) { target ?? (target = getter()); return Reflect.getOwnPropertyDescriptor(target, prop); }, defineProperty(_, prop, descriptor) { target ?? (target = getter()); return Reflect.defineProperty(target, prop, descriptor); } }); } function stringifyPrimitive(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } var NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick(schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const newShape = {}; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; newShape[key] = currDef.shape[key]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function omit(schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const newShape = { ...schema._zod.def.shape }; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { const existingShape = schema._zod.def.shape; for (const key in shape) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; } }); return clone(schema, def); } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; } }); return clone(schema, def); } function merge(a, b) { if (a._zod.def.checks?.length) { throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); } const def = mergeDefs(a._zod.def, { get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; assignProp(this, "shape", _shape); return _shape; }, get catchall() { return b._zod.def.catchall; }, checks: b._zod.def.checks ?? [] }); return clone(a, def); } function partial(Class3, schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".partial() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in oldShape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = Class3 ? new Class3({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } else { for (const key in oldShape) { shape[key] = Class3 ? new Class3({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } assignProp(this, "shape", shape); return shape; }, checks: [] }); return clone(schema, def); } function required(Class3, schema, mask) { const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = new Class3({ type: "nonoptional", innerType: oldShape[key] }); } } else { for (const key in oldShape) { shape[key] = new Class3({ type: "nonoptional", innerType: oldShape[key] }); } } assignProp(this, "shape", shape); return shape; } }); return clone(schema, def); } function aborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue !== true) { return true; } } return false; } function explicitlyAborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue === false) { return true; } } return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a282; (_a282 = iss).path ?? (_a282.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue(iss, ctx, config3) { const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config3.customError?.(iss)) ?? unwrapMessage(config3.localeError?.(iss)) ?? "Invalid input"; const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; rest.path ?? (rest.path = []); rest.message = message; if (ctx?.reportInput) { rest.input = _input; } return rest; } function getSizableOrigin(input) { if (input instanceof Set) return "set"; if (input instanceof Map) return "map"; if (input instanceof File) return "file"; return "unknown"; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function parsedType(data) { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "nan" : "number"; } case "object": { if (data === null) { return "null"; } if (Array.isArray(data)) { return "array"; } const obj = data; if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { return obj.constructor.name; } } } return t; } function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst }; } return { ...iss }; } function cleanEnum(obj) { return Object.entries(obj).filter(([k, _]) => { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } function base64ToUint8Array(base645) { const binaryString = atob(base645); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } return bytes; } function uint8ArrayToBase64(bytes) { let binaryString = ""; for (let i = 0; i < bytes.length; i++) { binaryString += String.fromCharCode(bytes[i]); } return btoa(binaryString); } function base64urlToUint8Array(base64url5) { const base645 = base64url5.replace(/-/g, "+").replace(/_/g, "/"); const padding = "=".repeat((4 - base645.length % 4) % 4); return base64ToUint8Array(base645 + padding); } function uint8ArrayToBase64url(bytes) { return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } function hexToUint8Array(hex3) { const cleanHex = hex3.replace(/^0x/, ""); if (cleanHex.length % 2 !== 0) { throw new Error("Invalid hex string length"); } const bytes = new Uint8Array(cleanHex.length / 2); for (let i = 0; i < cleanHex.length; i += 2) { bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); } return bytes; } function uint8ArrayToHex(bytes) { return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); } var Class = class { constructor(..._args) { } }; var initializer = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false }); Object.defineProperty(inst, "issues", { value: def, enumerable: false }); inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false }); }; var $ZodError = /* @__PURE__ */ $constructor("$ZodError", initializer); var $ZodRealError = /* @__PURE__ */ $constructor("$ZodError", initializer, { Parent: Error }); function flattenError(error90, mapper = (issue3) => issue3.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error90.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(error90, mapper = (issue3) => issue3.message) { const fieldErrors = { _errors: [] }; const processError = (error91, path = []) => { for (const issue3 of error91.issues) { if (issue3.code === "invalid_union" && issue3.errors.length) { issue3.errors.map((issues) => processError({ issues }, [...path, ...issue3.path])); } else if (issue3.code === "invalid_key") { processError({ issues: issue3.issues }, [...path, ...issue3.path]); } else if (issue3.code === "invalid_element") { processError({ issues: issue3.issues }, [...path, ...issue3.path]); } else { const fullpath = [...path, ...issue3.path]; if (fullpath.length === 0) { fieldErrors._errors.push(mapper(issue3)); } else { let curr = fieldErrors; let i = 0; while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue3)); } curr = curr[el]; i++; } } } } }; processError(error90); return fieldErrors; } function treeifyError(error90, mapper = (issue3) => issue3.message) { const result = { errors: [] }; const processError = (error91, path = []) => { var _a282, _b19; for (const issue3 of error91.issues) { if (issue3.code === "invalid_union" && issue3.errors.length) { issue3.errors.map((issues) => processError({ issues }, [...path, ...issue3.path])); } else if (issue3.code === "invalid_key") { processError({ issues: issue3.issues }, [...path, ...issue3.path]); } else if (issue3.code === "invalid_element") { processError({ issues: issue3.issues }, [...path, ...issue3.path]); } else { const fullpath = [...path, ...issue3.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue3)); 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 = {}); (_a282 = curr.properties)[el] ?? (_a282[el] = { errors: [] }); curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); (_b19 = curr.items)[el] ?? (_b19[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue3)); } i++; } } } }; processError(error90); return result; } function toDotPath(_path) { const segs = []; const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); for (const seg of path) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); else { if (segs.length) segs.push("."); segs.push(seg); } } return segs.join(""); } function prettifyError(error90) { const lines = []; const issues = [...error90.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); for (const issue3 of issues) { lines.push(`\u2716 ${issue3.message}`); if (issue3.path?.length) lines.push(` \u2192 at ${toDotPath(issue3.path)}`); } return lines.join("\n"); } var _parse = (_Err) => (schema, value, _ctx, _params) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { const e2 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e2, _params?.callee); throw e2; } return result.value; }; var parse = /* @__PURE__ */ _parse($ZodRealError); var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { const e2 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e2, params?.callee); throw e2; } return result.value; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _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 }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; return result.issues.length ? { success: false, error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); var _encode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _parse(_Err)(schema, value, ctx); }; var encode = /* @__PURE__ */ _encode($ZodRealError); var _decode = (_Err) => (schema, value, _ctx) => { return _parse(_Err)(schema, value, _ctx); }; var decode = /* @__PURE__ */ _decode($ZodRealError); var _encodeAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _parseAsync(_Err)(schema, value, ctx); }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); var _decodeAsync = (_Err) => async (schema, value, _ctx) => { return _parseAsync(_Err)(schema, value, _ctx); }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _safeParse(_Err)(schema, value, ctx); }; var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); var _safeDecode = (_Err) => (schema, value, _ctx) => { return _safeParse(_Err)(schema, value, _ctx); }; var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; return _safeParseAsync(_Err)(schema, value, ctx); }; var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { return _safeParseAsync(_Err)(schema, value, _ctx); }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); var regexes_exports = {}; __export(regexes_exports, { base64: () => base64, base64url: () => base64url, bigint: () => bigint, boolean: () => boolean, browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, cuid: () => cuid, cuid2: () => cuid2, date: () => date, datetime: () => datetime, domain: () => domain, duration: () => duration, e164: () => e164, email: () => email, emoji: () => emoji, extendedDuration: () => extendedDuration, guid: () => guid, hex: () => hex, hostname: () => hostname, html5Email: () => html5Email, httpProtocol: () => httpProtocol, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, ipv6: () => ipv6, ksuid: () => ksuid, lowercase: () => lowercase, mac: () => mac, md5_base64: () => md5_base64, md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, sha1_base64: () => sha1_base64, sha1_base64url: () => sha1_base64url, sha1_hex: () => sha1_hex, sha256_base64: () => sha256_base64, sha256_base64url: () => sha256_base64url, sha256_hex: () => sha256_hex, sha384_base64: () => sha384_base64, sha384_base64url: () => sha384_base64url, sha384_hex: () => sha384_hex, sha512_base64: () => sha512_base64, sha512_base64url: () => sha512_base64url, sha512_hex: () => sha512_hex, string: () => string, time: () => time, ulid: () => ulid, undefined: () => _undefined, unicodeEmail: () => unicodeEmail, uppercase: () => uppercase, uuid: () => uuid, uuid4: () => uuid4, uuid6: () => uuid6, uuid7: () => uuid7, xid: () => xid }); var cuid = /^[cC][0-9a-z]{6,}$/; var cuid2 = /^[0-9a-z]+$/; var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var 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)?)??$/; var 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})$/; var uuid = (version3) => { if (!version3) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var 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])?)*$/; var 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,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var 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])?)*$/; var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji() { return new RegExp(_emoji, "u"); } var 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])$/; var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; var mac = (delimiter) => { const escapedDelim = escapeRegex(delimiter ?? ":"); return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var 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])$/; var 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])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url = /^[A-Za-z0-9_-]*$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; var httpProtocol = /^https?$/; var e164 = /^\+[1-9]\d{6,14}$/; var 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])))`; var 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)}$`); } function datetime(args) { const time5 = timeSource({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); const timeRegex3 = `${time5}(?:${opts.join("|")})`; return new RegExp(`^${dateSource}T(?:${timeRegex3})$`); } var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; var bigint = /^-?\d+n?$/; var integer = /^-?\d+$/; var number = /^-?\d+(?:\.\d+)?$/; var boolean = /^(?:true|false)$/i; var _null = /^null$/i; var _undefined = /^undefined$/i; var lowercase = /^[^A-Z]*$/; var uppercase = /^[^a-z]*$/; var hex = /^[0-9a-fA-F]*$/; function fixedBase64(bodyLength, padding) { return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); } function fixedBase64url(length) { return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); } var md5_hex = /^[0-9a-fA-F]{32}$/; var md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); var md5_base64url = /* @__PURE__ */ fixedBase64url(22); var sha1_hex = /^[0-9a-fA-F]{40}$/; var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); var sha1_base64url = /* @__PURE__ */ fixedBase64url(27); var sha256_hex = /^[0-9a-fA-F]{64}$/; var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); var sha256_base64url = /* @__PURE__ */ fixedBase64url(43); var sha384_hex = /^[0-9a-fA-F]{96}$/; var sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); var sha384_base64url = /* @__PURE__ */ fixedBase64url(64); var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a282; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a282 = inst._zod).onattach ?? (_a282.onattach = []); }); var numericOriginMap = { number: "number", bigint: "bigint", object: "date" }; var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { var _a282; (_a282 = inst2._zod.bag).multipleOf ?? (_a282.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) : floatSafeRemainder2(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 }); }; }); var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { $ZodCheck.init(inst, def); def.format = def.format || "float64"; const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) { payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); } else { payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); } return; } } if (input < minimum) { payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "number", input, code: "too_big", maximum, inclusive: true, inst, continue: !def.abort }); } }; }); var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; }); inst._zod.check = (payload) => { const input = payload.value; if (input < minimum) { payload.issues.push({ origin: "bigint", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inclusive: true, inst, continue: !def.abort }); } }; }); var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a282; $ZodCheck.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size <= def.maximum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a282; $ZodCheck.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size >= def.minimum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a282; $ZodCheck.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.size; bag.maximum = def.size; bag.size = def.size; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size === def.size) return; const tooBig = size > def.size; payload.issues.push({ origin: getSizableOrigin(input), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a282; $ZodCheck.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length <= def.maximum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a282; $ZodCheck.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length >= def.minimum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a282; $ZodCheck.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.length; bag.maximum = def.length; bag.length = def.length; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length === def.length) return; const origin = getLengthableOrigin(input); const tooBig = length > def.length; payload.issues.push({ origin, ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a282, _b19; $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; if (def.pattern) { bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(def.pattern); } }); if (def.pattern) (_a282 = inst._zod).check ?? (_a282.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 (_b19 = inst._zod).check ?? (_b19.check = () => { }); }); var $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 }); }; }); var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { def.pattern ?? (def.pattern = lowercase); $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { def.pattern ?? (def.pattern = uppercase); $ZodCheckStringFormat.init(inst, def); }); var $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((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: def.includes, input: payload.value, inst, continue: !def.abort }); }; }); var $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((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: def.prefix, input: payload.value, inst, continue: !def.abort }); }; }); var $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((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: def.suffix, input: payload.value, inst, continue: !def.abort }); }; }); function handleCheckPropertyResult(result, payload, property) { if (result.issues.length) { payload.issues.push(...prefixIssues(property, result.issues)); } } var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { const result = def.schema._zod.run({ value: payload.value[def.property], issues: [] }, {}); if (result instanceof Promise) { return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); } handleCheckPropertyResult(result, payload, def.property); return; }; }); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); inst._zod.onattach.push((inst2) => { inst2._zod.bag.mime = def.mime; }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; payload.issues.push({ code: "invalid_value", values: def.mime, input: payload.value.type, inst, continue: !def.abort }); }; }); var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); var Doc = class { constructor(args = []) { this.content = []; this.indent = 0; if (this) this.args = args; } indented(fn) { this.indent += 1; fn(this); this.indent -= 1; } write(arg) { if (typeof arg === "function") { arg(this, { execution: "sync" }); arg(this, { execution: "async" }); return; } const content = arg; const lines = content.split("\n").filter((x) => x); const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); for (const line of dedented) { this.content.push(line); } } compile() { const F2 = Function; const args = this?.args; const content = this?.content ?? [``]; const lines = [...content.map((x) => ` ${x}`)]; return new F2(...args, lines.join("\n")); } }; var version = { major: 4, minor: 4, patch: 3 }; var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a282; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; const checks = [...inst._zod.def.checks ?? []]; if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); } } if (checks.length === 0) { (_a282 = inst._zod).deferred ?? (_a282.deferred = []); inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks2, ctx) => { let isAborted3 = aborted(payload); let asyncResult; for (const ch of checks2) { if (ch._zod.def.when) { if (explicitlyAborted(payload)) continue; const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted3) { 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 (!isAborted3) isAborted3 = aborted(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted3) isAborted3 = aborted(payload, currLen); } } if (asyncResult) { return asyncResult.then(() => { return payload; }); } return payload; }; const handleCanaryResult = (canary, payload, ctx) => { if (aborted(canary)) { canary.aborted = true; return canary; } const checkResult = runChecks(payload, checks, ctx); if (checkResult instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); } return inst._zod.parse(checkResult, ctx); }; inst._zod.run = (payload, ctx) => { if (ctx.skipChecks) { return inst._zod.parse(payload, ctx); } if (ctx.direction === "backward") { const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); if (canary instanceof Promise) { return canary.then((canary2) => { return handleCanaryResult(canary2, payload, ctx); }); } return handleCanaryResult(canary, payload, ctx); } const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return result.then((result2) => runChecks(result2, checks, ctx)); } return runChecks(result, checks, ctx); }; } defineLazy(inst, "~standard", () => ({ validate: (value) => { try { const r = safeParse(inst, value); return r.success ? { value: r.data } : { issues: r.error?.issues }; } catch (_) { return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } }, vendor: "zod", version: 1 })); }); var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_2) { } if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { $ZodCheckStringFormat.init(inst, def); $ZodString.init(inst, def); }); var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { def.pattern ?? (def.pattern = guid); $ZodStringFormat.init(inst, def); }); var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { if (def.version) { const versionMap = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }; const v = versionMap[def.version]; if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); def.pattern ?? (def.pattern = uuid(v)); } else def.pattern ?? (def.pattern = uuid()); $ZodStringFormat.init(inst, def); }); var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); if (!def.normalize && def.protocol?.source === httpProtocol.source) { if (!/^https?:\/\//i.test(trimmed)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid URL format", input: payload.value, inst, continue: !def.abort }); return; } } const url3 = new URL(trimmed); if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url3.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: def.hostname.source, input: payload.value, inst, continue: !def.abort }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url3.protocol.endsWith(":") ? url3.protocol.slice(0, -1) : url3.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort }); } } if (def.normalize) { payload.value = url3.href; } else { payload.value = trimmed; } return; } catch (_) { payload.issues.push({ code: "invalid_format", format: "url", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { def.pattern ?? (def.pattern = emoji()); $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { def.pattern ?? (def.pattern = nanoid); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { def.pattern ?? (def.pattern = cuid); $ZodStringFormat.init(inst, def); }); var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { def.pattern ?? (def.pattern = cuid2); $ZodStringFormat.init(inst, def); }); var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { def.pattern ?? (def.pattern = ulid); $ZodStringFormat.init(inst, def); }); var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { def.pattern ?? (def.pattern = xid); $ZodStringFormat.init(inst, def); }); var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { def.pattern ?? (def.pattern = ksuid); $ZodStringFormat.init(inst, def); }); var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { def.pattern ?? (def.pattern = datetime(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { def.pattern ?? (def.pattern = date); $ZodStringFormat.init(inst, def); }); var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { def.pattern ?? (def.pattern = time(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { def.pattern ?? (def.pattern = duration); $ZodStringFormat.init(inst, def); }); var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `ipv4`; }); var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); } catch { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { const parts = payload.value.split("/"); try { if (parts.length !== 2) throw new Error(); const [address, prefix] = parts; if (!prefix) throw new Error(); const prefixNum = Number(prefix); if (`${prefixNum}` !== prefix) throw new Error(); if (prefixNum < 0 || prefixNum > 128) throw new Error(); new URL(`http://[${address}]`); } catch { payload.issues.push({ code: "invalid_format", format: "cidrv6", input: payload.value, inst, continue: !def.abort }); } }; }); function isValidBase64(data) { if (data === "") return true; if (/\s/.test(data)) return false; if (data.length % 4 !== 0) return false; try { atob(data); return true; } catch { return false; } } var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { def.pattern ?? (def.pattern = base64); $ZodStringFormat.init(inst, def); inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort }); }; }); function isValidBase64URL(data) { if (!base64url.test(data)) return false; const base645 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base645.padEnd(Math.ceil(base645.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { def.pattern ?? (def.pattern = base64url); $ZodStringFormat.init(inst, def); inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64url", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); function isValidJWT2(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; } } var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (isValidJWT2(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", format: "jwt", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (def.fn(payload.value)) return; payload.issues.push({ code: "invalid_format", format: def.format, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = inst._zod.bag.pattern ?? number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...received ? { received } : {} }); return payload; }; }); var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); }); var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = boolean; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst }); return payload; }; }); var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = bigint; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = BigInt(payload.value); } catch (_) { } if (typeof payload.value === "bigint") return payload; payload.issues.push({ expected: "bigint", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { $ZodCheckBigIntFormat.init(inst, def); $ZodBigInt.init(inst, def); }); var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", input, inst }); return payload; }; }); var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); 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; }; }); var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst }); return payload; }; }); var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $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; }; }); var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", input, inst }); return payload; }; }); var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (def.coerce) { try { payload.value = new Date(payload.value); } catch (_err) { } } const input = payload.value; const isDate = input instanceof Date; const isValidDate = isDate && !Number.isNaN(input.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", input, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); function handleArrayResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst }); return payload; } payload.value = Array(input.length); const proms = []; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { const isPresent = key in input; if (result.issues.length) { if (isOptionalIn && isOptionalOut && !isPresent) { return; } final.issues.push(...prefixIssues(key, result.issues)); } if (!isPresent && !isOptionalIn) { if (!result.issues.length) { final.issues.push({ code: "invalid_type", expected: "nonoptional", input: void 0, path: [key] }); } return; } if (result.value === void 0) { if (isPresent) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } function normalizeDef(def) { const keys = Object.keys(def.shape); for (const k of keys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, keys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } function handleCatchall(proms, input, payload, ctx, def, inst) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; const isOptionalIn = _catchall.optin === "optional"; const isOptionalOut = _catchall.optout === "optional"; for (const key in input) { if (key === "__proto__") continue; if (keySet.has(key)) continue; if (t === "never") { unrecognized.push(key); continue; } const r = _catchall.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); } else { handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, input, inst }); } if (!proms.length) return payload; return Promise.all(proms).then(() => { return payload; }); } var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc = Object.getOwnPropertyDescriptor(def, "shape"); if (!desc?.get) { const sh = def.shape; Object.defineProperty(def, "shape", { get: () => { const newSh = { ...sh }; Object.defineProperty(def, "shape", { value: newSh }); return newSh; } }); } const _normalized = cached(() => normalizeDef(def)); defineLazy(inst._zod, "propValues", () => { const shape = def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); for (const v of field.values) propValues[key].add(v); } } return propValues; }); const isObject3 = isObject; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject3(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } payload.value = {}; const proms = []; const shape = value.shape; for (const key of value.keys) { const el = shape[key]; const isOptionalIn = el._zod.optin === "optional"; const isOptionalOut = el._zod.optout === "optional"; const r = el._zod.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); } else { handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); const generateFastpass = (shape) => { const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key) => { const k = esc(key); return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; }; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; for (const key of normalized.keys) { ids[key] = `key_${counter++}`; } doc.write(`const newResult = {};`); for (const key of normalized.keys) { const id = ids[key]; const k = esc(key); const schema = shape[key]; const isOptionalIn = schema?._zod?.optin === "optional"; const isOptionalOut = schema?._zod?.optout === "optional"; doc.write(`const ${id} = ${parseStr(key)};`); if (isOptionalIn && isOptionalOut) { doc.write(` if (${id}.issues.length) { if (${k} in input) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } } if (${id}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { newResult[${k}] = ${id}.value; } `); } else if (!isOptionalIn) { doc.write(` const ${id}_present = ${k} in input; if (${id}.issues.length) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (!${id}_present && !${id}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${k}] }); } if (${id}_present) { if (${id}.value === undefined) { newResult[${k}] = undefined; } else { newResult[${k}] = ${id}.value; } } `); } else { doc.write(` if (${id}.issues.length) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (${id}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { newResult[${k}] = ${id}.value; } `); } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); const fn = doc.compile(); return (payload, ctx) => fn(shape, payload, ctx); }; let fastpass; const isObject3 = isObject; const jit = !globalConfig.jitless; const allowsEval3 = allowsEval; const fastEnabled = jit && allowsEval3.value; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject3(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { if (!fastpass) fastpass = generateFastpass(def.shape); payload = fastpass(payload, ctx); if (!catchall) return payload; return handleCatchall([], input, payload, ctx, value, inst); } return superParse(payload, ctx); }; }); function handleUnionResults(results, final, inst, ctx) { for (const result of results) { if (result.issues.length === 0) { final.value = result.value; return final; } } const nonaborted = results.filter((r) => !aborted(r)); if (nonaborted.length === 1) { final.value = nonaborted[0].value; return nonaborted[0]; } final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); return final; } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); defineLazy(inst._zod, "values", () => { if (def.options.every((o) => o._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); defineLazy(inst._zod, "pattern", () => { if (def.options.every((o) => o._zod.pattern)) { const patterns = def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; }); const first = def.options.length === 1 ? def.options[0]._zod.run : null; inst._zod.parse = (payload, ctx) => { if (first) { return first(payload, ctx); } let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { if (result.issues.length === 0) return result; results.push(result); } } if (!async) return handleUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleUnionResults(results2, payload, inst, ctx); }); }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { const successes = results.filter((r) => r.issues.length === 0); if (successes.length === 1) { final.value = successes[0].value; return final; } if (successes.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); } else { final.issues.push({ code: "invalid_union", input: final.value, inst, errors: [], inclusive: false }); } return final; } var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { $ZodUnion.init(inst, def); def.inclusive = false; const first = def.options.length === 1 ? def.options[0]._zod.run : null; inst._zod.parse = (payload, ctx) => { if (first) { return first(payload, ctx); } let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { results.push(result); } } if (!async) return handleExclusiveUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleExclusiveUnionResults(results2, payload, inst, ctx); }); }; }); var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; defineLazy(inst._zod, "propValues", () => { const propValues = {}; for (const option of def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); for (const [k, v] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); for (const val of v) { propValues[k].add(val); } } } return propValues; }); const disc = cached(() => { const opts = def.options; const map3 = /* @__PURE__ */ new Map(); for (const o of opts) { const values = o._zod.propValues?.[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); for (const v of values) { if (map3.has(v)) { throw new Error(`Duplicate discriminator value "${String(v)}"`); } map3.set(v, o); } } return map3; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isObject(input)) { payload.issues.push({ code: "invalid_type", expected: "object", input, inst }); return payload; } const opt = disc.value.get(input?.[def.discriminator]); if (opt) { return opt._zod.run(payload, ctx); } if (def.unionFallback || ctx.direction === "backward") { return _super(payload, ctx); } payload.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", discriminator: def.discriminator, options: Array.from(disc.value.keys()), input, path: [def.discriminator], inst }); return payload; }; }); var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; const left = def.left._zod.run({ value: input, issues: [] }, ctx); const right = def.right._zod.run({ value: input, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { return handleIntersectionResults(payload, left2, right2); }); } return handleIntersectionResults(payload, left, right); }; }); function mergeValues2(a, b) { if (a === b) { return { valid: true, data: a }; } if (a instanceof Date && b instanceof Date && +a === +b) { return { valid: true, data: a }; } if (isPlainObject(a) && isPlainObject(b)) { const bKeys = Object.keys(b); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues2(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 = mergeValues2(itemA, itemB); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [index, ...sharedValue.mergeErrorPath] }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } return { valid: false, mergeErrorPath: [] }; } function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; for (const iss of left.issues) { if (iss.code === "unrecognized_keys") { unrecIssue ?? (unrecIssue = iss); for (const k of iss.keys) { if (!unrecKeys.has(k)) unrecKeys.set(k, {}); unrecKeys.get(k).l = true; } } else { result.issues.push(iss); } } for (const iss of right.issues) { if (iss.code === "unrecognized_keys") { for (const k of iss.keys) { if (!unrecKeys.has(k)) unrecKeys.set(k, {}); unrecKeys.get(k).r = true; } } else { result.issues.push(iss); } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); if (bothKeys.length && unrecIssue) { result.issues.push({ ...unrecIssue, keys: bothKeys }); } if (aborted(result)) return result; const merged = mergeValues2(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; return result; } var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ input, inst, expected: "tuple", code: "invalid_type" }); return payload; } payload.value = []; const proms = []; const optinStart = getTupleOptStart(items, "optin"); const optoutStart = getTupleOptStart(items, "optout"); if (!def.rest) { if (input.length < optinStart) { payload.issues.push({ code: "too_small", minimum: optinStart, inclusive: true, input, inst, origin: "array" }); return payload; } if (input.length > items.length) { payload.issues.push({ code: "too_big", maximum: items.length, inclusive: true, input, inst, origin: "array" }); } } const itemResults = new Array(items.length); for (let i = 0; i < items.length; i++) { const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((rr) => { itemResults[i] = rr; })); } else { itemResults[i] = r; } } if (def.rest) { let i = items.length - 1; const rest = input.slice(items.length); for (const el of rest) { i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((r) => handleTupleResult(r, payload, i))); } else { handleTupleResult(result, payload, i); } } } if (proms.length) { return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); } return handleTupleResults(itemResults, payload, items, input, optoutStart); }; }); function getTupleOptStart(items, key) { for (let i = items.length - 1; i >= 0; i--) { if (items[i]._zod[key] !== "optional") return i + 1; } return 0; } function handleTupleResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } function handleTupleResults(itemResults, final, items, input, optoutStart) { for (let i = 0; i < items.length; i++) { const r = itemResults[i]; const isPresent = i < input.length; if (r.issues.length) { if (!isPresent && i >= optoutStart) { final.value.length = i; break; } final.issues.push(...prefixIssues(i, r.issues)); } final.value[i] = r.value; } for (let i = final.value.length - 1; i >= input.length; i--) { if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { final.value.length = i; } else { break; } } return final; } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isPlainObject(input)) { payload.issues.push({ expected: "record", code: "invalid_type", input, inst }); return payload; } const proms = []; const values = def.keyType._zod.values; if (values) { payload.value = {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (keyResult.issues.length) { payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); continue; } const outKey = keyResult.value; const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[outKey] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[outKey] = result.value; } } } let unrecognized; for (const key in input) { if (!recordKeys.has(key)) { 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; if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; if (checkNumericKey) { const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); if (retryResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (retryResult.issues.length === 0) { keyResult = retryResult; } } if (keyResult.issues.length) { if (def.mode === "loose") { payload.value[key] = input[key]; } else { payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); } continue; } const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[keyResult.value] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[keyResult.value] = result.value; } } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", input, inst }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Map(); for (const [key, value] of input) { const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); })); } else { handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); } else { final.issues.push({ code: "invalid_key", origin: "map", input, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } if (valueResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, valueResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_element", input, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } final.value.set(keyResult.value, valueResult.value); } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Set)) { payload.issues.push({ input, inst, expected: "set", code: "invalid_type" }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Set(); for (const item of input) { const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); } else handleSetResult(result, payload); } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleSetResult(result, final) { if (result.issues.length) { final.issues.push(...result.issues); } final.value.add(result.value); } var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); const valuesSet = new Set(values); inst._zod.values = valuesSet; inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (valuesSet.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values, input, inst }); return payload; }; }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); if (def.values.length === 0) { throw new Error("Cannot create literal schema with no valid values"); } const values = new Set(def.values); inst._zod.values = values; inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, input, inst }); return payload; }; }); var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", input, inst }); return payload; }; }); var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { const output = _out instanceof Promise ? _out : Promise.resolve(_out); return output.then((output2) => { payload.value = output2; payload.fallback = true; return payload; }); } if (_out instanceof Promise) { throw new $ZodAsyncError(); } payload.value = _out; payload.fallback = true; return payload; }; }); function handleOptionalResult(result, input) { if (input === void 0 && (result.issues.length || result.fallback)) { return { issues: [], value: void 0 }; } return result; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.optout = "optional"; defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; }); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { const input = payload.value; const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, input)); return handleOptionalResult(result, input); } if (payload.value === void 0) { return payload; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; return payload; } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleDefaultResult(result2, def)); } return handleDefaultResult(result, def); }; }); function handleDefaultResult(payload, def) { if (payload.value === void 0) { payload.value = def.defaultValue; } return payload; } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => { const v = def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleNonOptionalResult(result2, inst)); } return handleNonOptionalResult(result, inst); }; }); function handleNonOptionalResult(payload, inst) { if (!payload.issues.length && payload.value === void 0) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: payload.value, inst }); } return payload; } var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError("ZodSuccess"); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.issues.length === 0; return payload; }); } payload.value = result.issues.length === 0; return payload; }; }); var $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) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.value; if (result2.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value }); payload.issues = []; payload.fallback = true; } 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 = []; payload.fallback = true; } return payload; }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { payload.issues.push({ input: payload.value, inst, expected: "nan", code: "invalid_type" }); return payload; } return payload; }; }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handlePipeResult(right2, def.in, ctx)); } return handlePipeResult(right, def.in, ctx); } const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handlePipeResult(left2, def.out, ctx)); } return handlePipeResult(left, def.out, ctx); }; }); function handlePipeResult(left, next, ctx) { if (left.issues.length) { left.aborted = true; return left; } return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handleCodecAResult(left2, def, ctx)); } return handleCodecAResult(left, def, ctx); } else { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handleCodecAResult(right2, def, ctx)); } return handleCodecAResult(right, def, ctx); } }; }); function handleCodecAResult(result, def, ctx) { if (result.issues.length) { result.aborted = true; return result; } const direction = ctx.direction || "forward"; if (direction === "forward") { const transformed = def.transform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); } return handleCodecTxResult(result, transformed, def.out, ctx); } else { const transformed = def.reverseTransform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); } return handleCodecTxResult(result, transformed, def.in, ctx); } } function handleCodecTxResult(left, value, nextSchema, ctx) { if (left.issues.length) { left.aborted = true; return left; } return nextSchema._zod.run({ value, issues: left.issues }, ctx); } var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => { $ZodPipe.init(inst, def); }); var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then(handleReadonlyResult); } return handleReadonlyResult(result); }; }); function handleReadonlyResult(payload) { payload.value = Object.freeze(payload.value); return payload; } var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { if (!part._zod.pattern) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; if (!source) throw new Error(`Invalid template literal part: ${part._zod.traits}`); const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; regexParts.push(source.slice(start, end)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { throw new Error(`Invalid template literal part: ${part}`); } } inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "string") { payload.issues.push({ input: payload.value, inst, expected: "string", code: "invalid_type" }); return payload; } inst._zod.pattern.lastIndex = 0; if (!inst._zod.pattern.test(payload.value)) { payload.issues.push({ input: payload.value, inst, code: "invalid_format", format: def.format ?? "template_literal", pattern: inst._zod.pattern.source }); return payload; } return payload; }; }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); inst._def = def; inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } return function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; }; }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } return async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; }; }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { payload.issues.push({ code: "invalid_type", expected: "function", input: payload.value, inst }); return payload; } const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; if (hasPromiseOutput) { payload.value = inst.implementAsync(payload.value); } else { payload.value = inst.implement(payload.value); } return payload; }; inst.input = (...args) => { const F2 = inst.constructor; if (Array.isArray(args[0])) { return new F2({ type: "function", input: new $ZodTuple({ type: "tuple", items: args[0], rest: args[1] }), output: inst._def.output }); } return new F2({ type: "function", input: args[0], output: inst._def.output }); }; inst.output = (output) => { const F2 = inst.constructor; return new F2({ type: "function", input: inst._def.input, output }); }; return inst; }); var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); }; }); var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "innerType", () => { const d = def; if (!d._cachedInner) d._cachedInner = def.getter(); return d._cachedInner; }); defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); }; }); var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { $ZodCheck.init(inst, def); $ZodType.init(inst, def); inst._zod.parse = (payload, _) => { return payload; }; inst._zod.check = (payload) => { const input = payload.value; const r = def.fn(input); if (r instanceof Promise) { return r.then((r2) => handleRefineResult(r2, payload, input, inst)); } handleRefineResult(r, payload, input, inst); return; }; }); function handleRefineResult(result, payload, input, inst) { if (!result) { const _iss = { code: "custom", input, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], // incorporates params.error into issue reporting continue: !inst._zod.def.abort // params: inst._zod.def.params, }; if (inst._zod.def.params) _iss.params = inst._zod.def.params; payload.issues.push(issue(_iss)); } } var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, ca: () => ca_default, cs: () => cs_default, da: () => da_default, de: () => de_default, el: () => el_default, en: () => en_default2, eo: () => eo_default, es: () => es_default, fa: () => fa_default, fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, he: () => he_default, hr: () => hr_default, hu: () => hu_default, hy: () => hy_default, id: () => id_default, is: () => is_default, it: () => it_default, ja: () => ja_default, ka: () => ka_default, kh: () => kh_default, km: () => km_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, nl: () => nl_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, ro: () => ro_default, ru: () => ru_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, th: () => th_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, ur: () => ur_default, uz: () => uz_default, vi: () => vi_default, yo: () => yo_default, zhCN: () => zh_CN_default, zhTW: () => zh_TW_default }); var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0645\u062F\u062E\u0644", email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", url: "\u0631\u0627\u0628\u0637", emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue3.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; } return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue3.values[0])}`; return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue3.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue3.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue3.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue3.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue3.prefix}"`; if (_issue.format === "ends_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue3.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; } case "not_multiple_of": return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue3.divisor}`; case "unrecognized_keys": return `\u0645\u0639\u0631\u0641${issue3.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue3.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue3.keys, "\u060C ")}`; case "invalid_key": return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue3.origin}`; case "invalid_union": return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; case "invalid_element": return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue3.origin}`; default: return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; } }; }; function ar_default() { return { localeError: error() }; } var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, set: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue3.expected}, daxil olan ${received}`; } return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue3.values[0])}`; return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue3.origin ?? "d\u0259y\u0259r"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue3.origin ?? "d\u0259y\u0259r"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; if (_issue.format === "ends_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; if (_issue.format === "includes") return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; if (_issue.format === "regex") return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Yanl\u0131\u015F \u0259d\u0259d: ${issue3.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; case "unrecognized_keys": return `Tan\u0131nmayan a\xE7ar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; case "invalid_union": return "Yanl\u0131\u015F d\u0259y\u0259r"; case "invalid_element": return `${issue3.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; default: return `Yanl\u0131\u015F d\u0259y\u0259r`; } }; }; function az_default() { return { localeError: error2() }; } function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error3 = () => { const Sizable = { string: { unit: { one: "\u0441\u0456\u043C\u0432\u0430\u043B", few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u044B", many: "\u0431\u0430\u0439\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0443\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0430\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0447\u0430\u0441", duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u043B\u0456\u043A", array: "\u043C\u0430\u0441\u0456\u045E" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue3.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; } return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue3.values[0])}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { const maxValue = Number(issue3.maximum); const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue3.maximum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { const minValue = Number(issue3.minimum); const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue3.minimum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue3.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue3.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue3.origin}`; case "invalid_union": return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; case "invalid_element": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue3.origin}`; default: return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; } }; }; function be_default() { return { localeError: error3() }; } var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0445\u043E\u0434", email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0438\u0432" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue3.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; } return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue3.values[0])}`; return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue3.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue3.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue3.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue3.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; if (_issue.format === "emoji") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "datetime") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "date") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; if (_issue.format === "time") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "duration") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue3.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue3.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue3.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; case "invalid_element": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue3.origin}`; default: return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; } }; }; function bg_default() { return { localeError: error4() }; } var error5 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entrada", email: "adre\xE7a electr\xF2nica", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Tipus inv\xE0lid: s'esperava instanceof ${issue3.expected}, s'ha rebut ${received}`; } return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue3.values[0])}`; return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue3.values, " o ")}`; case "too_big": { const adj = issue3.inclusive ? "com a m\xE0xim" : "menys de"; const sizing = getSizing(issue3.origin); if (sizing) return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} contingu\xE9s ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} fos ${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? "com a m\xEDnim" : "m\xE9s de"; const sizing = getSizing(issue3.origin); if (sizing) { return `Massa petit: s'esperava que ${issue3.origin} contingu\xE9s ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `Massa petit: s'esperava que ${issue3.origin} fos ${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; if (_issue.format === "includes") return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; if (_issue.format === "regex") return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue3.divisor}`; case "unrecognized_keys": return `Clau${issue3.keys.length > 1 ? "s" : ""} no reconeguda${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Clau inv\xE0lida a ${issue3.origin}`; case "invalid_union": return "Entrada inv\xE0lida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general case "invalid_element": return `Element inv\xE0lid a ${issue3.origin}`; default: return `Entrada inv\xE0lida`; } }; }; function ca_default() { return { localeError: error5() }; } var error6 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, set: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "regul\xE1rn\xED v\xFDraz", email: "e-mailov\xE1 adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "datum a \u010Das ve form\xE1tu ISO", date: "datum ve form\xE1tu ISO", time: "\u010Das ve form\xE1tu ISO", duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", jwt: "JWT", template_literal: "vstup" }; const TypeDictionary = { nan: "NaN", number: "\u010D\xEDslo", string: "\u0159et\u011Bzec", function: "funkce", array: "pole" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue3.expected}, obdr\u017Eeno ${received}`; } return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue3.values[0])}`; return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue3.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue3.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue3.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue3.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; if (_issue.format === "includes") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; if (_issue.format === "regex") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue3.divisor}`; case "unrecognized_keys": return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Neplatn\xFD kl\xED\u010D v ${issue3.origin}`; case "invalid_union": return "Neplatn\xFD vstup"; case "invalid_element": return `Neplatn\xE1 hodnota v ${issue3.origin}`; default: return `Neplatn\xFD vstup`; } }; }; function cs_default() { return { localeError: error6() }; } var error7 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, set: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "e-mailadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkesl\xE6t", date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", string: "streng", number: "tal", boolean: "boolean", array: "liste", object: "objekt", set: "s\xE6t", file: "fil" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Ugyldigt input: forventede instanceof ${issue3.expected}, fik ${received}`; } return `Ugyldigt input: forventede ${expected}, fik ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue3.values[0])}`; return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); const origin = TypeDictionary[issue3.origin] ?? issue3.origin; if (sizing) return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); const origin = TypeDictionary[issue3.origin] ?? issue3.origin; if (sizing) { return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `For lille: forventede ${origin} havde ${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Ugyldig streng: skal starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: skal ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: skal indeholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ugyldigt tal: skal v\xE6re deleligt med ${issue3.divisor}`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8gle i ${issue3.origin}`; case "invalid_union": return "Ugyldigt input: matcher ingen af de tilladte typer"; case "invalid_element": return `Ugyldig v\xE6rdi i ${issue3.origin}`; default: return `Ugyldigt input`; } }; }; function da_default() { return { localeError: error7() }; } var error8 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "Eingabe", email: "E-Mail-Adresse", url: "URL", emoji: "Emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" }; const TypeDictionary = { nan: "NaN", number: "Zahl", array: "Array" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Ung\xFCltige Eingabe: erwartet instanceof ${issue3.expected}, erhalten ${received}`; } return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue3.values[0])}`; return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Zu gro\xDF: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; return `Zu gro\xDF: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ist`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} hat`; } return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ist`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; if (_issue.format === "ends_with") return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; if (_issue.format === "includes") return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; if (_issue.format === "regex") return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue3.divisor} sein`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Ung\xFCltiger Schl\xFCssel in ${issue3.origin}`; case "invalid_union": return "Ung\xFCltige Eingabe"; case "invalid_element": return `Ung\xFCltiger Wert in ${issue3.origin}`; default: return `Ung\xFCltige Eingabe`; } }; }; function de_default() { return { localeError: error8() }; } var error9 = () => { const Sizable = { string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, array: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, set: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, map: { unit: "\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2", email: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1", date: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1", time: "ISO \u03CE\u03C1\u03B1", duration: "ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1", ipv4: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4", ipv6: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6", mac: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC", cidrv4: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4", cidrv6: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6", base64: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64", base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", jwt: "JWT", template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (typeof issue3.expected === "string" && /^[A-Z]/.test(issue3.expected)) { return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue3.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; } return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue3.values[0])}`; return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue3.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`; return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue3.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue3.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue3.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`; if (_issue.format === "regex") return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`; return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue3.divisor}`; case "unrecognized_keys": return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue3.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue3.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue3.origin}`; case "invalid_union": return "\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"; case "invalid_element": return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue3.origin}`; default: return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`; } }; }; function el_default() { return { localeError: error9() }; } var error10 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, array: { unit: "items", verb: "to have" }, set: { unit: "items", verb: "to have" }, map: { unit: "entries", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { // Compatibility: "nan" -> "NaN" for display nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue3.values[0])}`; return `Invalid option: expected one of ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Too big: expected ${issue3.origin ?? "value"} to have ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue3.origin ?? "value"} to be ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Too small: expected ${issue3.origin} to have ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Too small: expected ${issue3.origin} to be ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Invalid string: must start with "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`; if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`; if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; return `Invalid ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Invalid number: must be a multiple of ${issue3.divisor}`; case "unrecognized_keys": return `Unrecognized key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Invalid key in ${issue3.origin}`; case "invalid_union": if (issue3.options && Array.isArray(issue3.options) && issue3.options.length > 0) { const opts = issue3.options.map((o) => `'${o}'`).join(" | "); return `Invalid discriminator value. Expected ${opts}`; } return "Invalid input"; case "invalid_element": return `Invalid value in ${issue3.origin}`; default: return `Invalid input`; } }; }; function en_default2() { return { localeError: error10() }; } var error11 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emo\u011Dio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" }; const TypeDictionary = { nan: "NaN", number: "nombro", array: "tabelo", null: "senvalora" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Nevalida enigo: atendi\u011Dis instanceof ${issue3.expected}, ricevi\u011Dis ${received}`; } return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue3.values[0])}`; return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Tro granda: atendi\u011Dis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementojn"}`; return `Tro granda: atendi\u011Dis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Tro malgranda: atendi\u011Dis ke ${issue3.origin} havu ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Tro malgranda: atendi\u011Dis ke ${issue3.origin} estu ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; if (_issue.format === "includes") return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; if (_issue.format === "regex") return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; return `Nevalida ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Nevalida nombro: devas esti oblo de ${issue3.divisor}`; case "unrecognized_keys": return `Nekonata${issue3.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue3.keys.length > 1 ? "j" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Nevalida \u015Dlosilo en ${issue3.origin}`; case "invalid_union": return "Nevalida enigo"; case "invalid_element": return `Nevalida valoro en ${issue3.origin}`; default: return `Nevalida enigo`; } }; }; function eo_default() { return { localeError: error11() }; } var error12 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entrada", email: "direcci\xF3n de correo electr\xF3nico", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN", string: "texto", number: "n\xFAmero", boolean: "booleano", array: "arreglo", object: "objeto", set: "conjunto", file: "archivo", date: "fecha", bigint: "n\xFAmero grande", symbol: "s\xEDmbolo", undefined: "indefinido", null: "nulo", function: "funci\xF3n", map: "mapa", record: "registro", tuple: "tupla", enum: "enumeraci\xF3n", union: "uni\xF3n", literal: "literal", promise: "promesa", void: "vac\xEDo", never: "nunca", unknown: "desconocido", any: "cualquiera" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Entrada inv\xE1lida: se esperaba instanceof ${issue3.expected}, recibido ${received}`; } return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue3.values[0])}`; return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); const origin = TypeDictionary[issue3.origin] ?? issue3.origin; if (sizing) return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); const origin = TypeDictionary[issue3.origin] ?? issue3.origin; if (sizing) { return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; if (_issue.format === "includes") return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue3.divisor}`; case "unrecognized_keys": return `Llave${issue3.keys.length > 1 ? "s" : ""} desconocida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Llave inv\xE1lida en ${TypeDictionary[issue3.origin] ?? issue3.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido en ${TypeDictionary[issue3.origin] ?? issue3.origin}`; default: return `Entrada inv\xE1lida`; } }; }; function es_default() { return { localeError: error12() }; } var error13 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0648\u0631\u0648\u062F\u06CC", email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", url: "URL", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; const TypeDictionary = { nan: "NaN", number: "\u0639\u062F\u062F", array: "\u0622\u0631\u0627\u06CC\u0647" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue3.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; } return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; } case "invalid_value": if (issue3.values.length === 1) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue3.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; } return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue3.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue3.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue3.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} \u0628\u0627\u0634\u062F`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} \u0628\u0627\u0634\u062F`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; } if (_issue.format === "ends_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; } if (_issue.format === "includes") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; } if (_issue.format === "regex") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; } return `${FormatDictionary[_issue.format] ?? issue3.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } case "not_multiple_of": return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue3.divisor} \u0628\u0627\u0634\u062F`; case "unrecognized_keys": return `\u06A9\u0644\u06CC\u062F${issue3.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue3.origin}`; case "invalid_union": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; case "invalid_element": return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue3.origin}`; default: return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } }; }; function fa_default() { return { localeError: error13() }; } var error14 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "s\xE4\xE4nn\xF6llinen lauseke", email: "s\xE4hk\xF6postiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Virheellinen tyyppi: odotettiin instanceof ${issue3.expected}, oli ${received}`; } return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue3.values[0])}`; return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue3.maximum.toString()} ${sizing.unit}`.trim(); } return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue3.minimum.toString()} ${sizing.unit}`.trim(); } return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; if (_issue.format === "includes") return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; if (_issue.format === "regex") { return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; } return `Virheellinen ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Virheellinen luku: t\xE4ytyy olla luvun ${issue3.divisor} monikerta`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return "Virheellinen avain tietueessa"; case "invalid_union": return "Virheellinen unioni"; case "invalid_element": return "Virheellinen arvo joukossa"; default: return `Virheellinen sy\xF6te`; } }; }; function fi_default() { return { localeError: error14() }; } var error15 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entr\xE9e", email: "adresse e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { string: "cha\xEEne", number: "nombre", int: "entier", boolean: "bool\xE9en", bigint: "grand entier", symbol: "symbole", undefined: "ind\xE9fini", null: "null", never: "jamais", void: "vide", date: "date", array: "tableau", object: "objet", tuple: "tuple", record: "enregistrement", map: "carte", set: "ensemble", file: "fichier", nonoptional: "non-optionnel", nan: "NaN", function: "fonction" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Entr\xE9e invalide : instanceof ${issue3.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } case "invalid_value": if (issue3.values.length === 1) return `Entr\xE9e invalide : ${stringifyPrimitive(issue3.values[0])} attendu`; return `Option invalide : une valeur parmi ${joinValues(issue3.values, "|")} attendue`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Trop grand : ${TypeDictionary[issue3.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; return `Trop grand : ${TypeDictionary[issue3.origin] ?? "valeur"} doit \xEAtre ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) return `Trop petit : ${TypeDictionary[issue3.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; return `Trop petit : ${TypeDictionary[issue3.origin] ?? "valeur"} doit \xEAtre ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue3.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue3.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue3.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue3.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_default() { return { localeError: error15() }; } var error16 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entr\xE9e", email: "adresse courriel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Entr\xE9e invalide : attendu instanceof ${issue3.expected}, re\xE7u ${received}`; } return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue3.values[0])}`; return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "\u2264" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} ait ${adj}${issue3.maximum.toString()} ${sizing.unit}`; return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} soit ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? "\u2265" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Trop petit : attendu que ${issue3.origin} ait ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Trop petit : attendu que ${issue3.origin} soit ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue3.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue3.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue3.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue3.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_CA_default() { return { localeError: error16() }; } var error17 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, bigint: { label: "BigInt", gender: "m" }, date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, promise: { label: "Promise", gender: "m" }, NaN: { label: "NaN", gender: "m" }, unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, value: { label: "\u05E2\u05E8\u05DA", gender: "m" } }; const Sizable = { string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } // no unit }; const typeEntry = (t) => t ? TypeNames[t] : void 0; const typeLabel = (t) => { const e2 = typeEntry(t); if (e2) return e2.label; return t ?? TypeNames.unknown.label; }; const withDefinite = (t) => `\u05D4${typeLabel(t)}`; const verbFor = (t) => { const e2 = typeEntry(t); const gender = e2?.gender ?? "m"; return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; }; const getSizing = (origin) => { if (!origin) return null; return Sizable[origin] ?? null; }; const FormatDictionary = { regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, cuid2: { label: "cuid2", gender: "m" }, ulid: { label: "ULID", gender: "m" }, xid: { label: "XID", gender: "m" }, ksuid: { label: "KSUID", gender: "m" }, datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, jwt: { label: "JWT", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expectedKey = issue3.expected; const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue3.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; } return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; } case "invalid_value": { if (issue3.values.length === 1) { return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue3.values[0])}`; } const stringified = issue3.values.map((v) => stringifyPrimitive(v)); if (issue3.values.length === 2) { return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; } const lastValue = stringified[stringified.length - 1]; const restValues = stringified.slice(0, -1).join(", "); return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; } case "too_big": { const sizing = getSizing(issue3.origin); const subject = withDefinite(issue3.origin ?? "value"); if (issue3.origin === "string") { return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue3.maximum.toString()} ${sizing?.unit ?? ""} ${issue3.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); } if (issue3.origin === "number") { const comparison = issue3.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue3.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue3.maximum}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; } if (issue3.origin === "array" || issue3.origin === "set") { const verb = issue3.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; const comparison = issue3.inclusive ? `${issue3.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue3.maximum} ${sizing?.unit ?? ""}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); } const adj = issue3.inclusive ? "<=" : "<"; const be = verbFor(issue3.origin ?? "value"); if (sizing?.unit) { return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.maximum.toString()} ${sizing.unit}`; } return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const sizing = getSizing(issue3.origin); const subject = withDefinite(issue3.origin ?? "value"); if (issue3.origin === "string") { return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue3.minimum.toString()} ${sizing?.unit ?? ""} ${issue3.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); } if (issue3.origin === "number") { const comparison = issue3.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue3.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue3.minimum}`; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; } if (issue3.origin === "array" || issue3.origin === "set") { const verb = issue3.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; if (issue3.minimum === 1 && issue3.inclusive) { const singularPhrase = issue3.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; } const comparison = issue3.inclusive ? `${issue3.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue3.minimum} ${sizing?.unit ?? ""}`; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); } const adj = issue3.inclusive ? ">=" : ">"; const be = verbFor(issue3.origin ?? "value"); if (sizing?.unit) { return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; if (_issue.format === "regex") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; const nounEntry = FormatDictionary[_issue.format]; const noun = nounEntry?.label ?? _issue.format; const gender = nounEntry?.gender ?? "m"; const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; return `${noun} \u05DC\u05D0 ${adjective}`; } case "not_multiple_of": return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue3.divisor}`; case "unrecognized_keys": return `\u05DE\u05E4\u05EA\u05D7${issue3.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue3.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": { return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; } case "invalid_union": return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; case "invalid_element": { const place = withDefinite(issue3.origin ?? "array"); return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; } default: return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } }; }; function he_default() { return { localeError: error17() }; } var error18 = () => { const Sizable = { string: { unit: "znakova", verb: "imati" }, file: { unit: "bajtova", verb: "imati" }, array: { unit: "stavki", verb: "imati" }, set: { unit: "stavki", verb: "imati" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "unos", email: "email adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum i vrijeme", date: "ISO datum", time: "ISO vrijeme", duration: "ISO trajanje", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "IPv4 raspon", cidrv6: "IPv6 raspon", base64: "base64 kodirani tekst", base64url: "base64url kodirani tekst", json_string: "JSON tekst", e164: "E.164 broj", jwt: "JWT", template_literal: "unos" }; const TypeDictionary = { nan: "NaN", string: "tekst", number: "broj", boolean: "boolean", array: "niz", object: "objekt", set: "skup", file: "datoteka", date: "datum", bigint: "bigint", symbol: "simbol", undefined: "undefined", null: "null", function: "funkcija", map: "mapa" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Neispravan unos: o\u010Dekuje se instanceof ${issue3.expected}, a primljeno je ${received}`; } return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue3.values[0])}`; return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); const origin = TypeDictionary[issue3.origin] ?? issue3.origin; if (sizing) return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemenata"}`; return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); const origin = TypeDictionary[issue3.origin] ?? issue3.origin; if (sizing) { return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`; if (_issue.format === "includes") return `Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`; if (_issue.format === "regex") return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`; return `Neispravna ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue3.divisor}`; case "unrecognized_keys": return `Neprepoznat${issue3.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Neispravan klju\u010D u ${TypeDictionary[issue3.origin] ?? issue3.origin}`; case "invalid_union": return "Neispravan unos"; case "invalid_element": return `Neispravna vrijednost u ${TypeDictionary[issue3.origin] ?? issue3.origin}`; default: return `Neispravan unos`; } }; }; function hr_default() { return { localeError: error18() }; } var error19 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "bemenet", email: "email c\xEDm", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO id\u0151b\xE9lyeg", date: "ISO d\xE1tum", time: "ISO id\u0151", duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", jwt: "JWT", template_literal: "bemenet" }; const TypeDictionary = { nan: "NaN", number: "sz\xE1m", array: "t\xF6mb" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue3.expected}, a kapott \xE9rt\xE9k ${received}`; } return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue3.values[0])}`; return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `T\xFAl nagy: ${issue3.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elem"}`; return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue3.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue3.origin} m\xE9rete t\xFAl kicsi ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue3.origin} t\xFAl kicsi ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; if (_issue.format === "ends_with") return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; if (_issue.format === "includes") return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; if (_issue.format === "regex") return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\xC9rv\xE9nytelen sz\xE1m: ${issue3.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; case "unrecognized_keys": return `Ismeretlen kulcs${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\xC9rv\xE9nytelen kulcs ${issue3.origin}`; case "invalid_union": return "\xC9rv\xE9nytelen bemenet"; case "invalid_element": return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue3.origin}`; default: return `\xC9rv\xE9nytelen bemenet`; } }; }; function hu_default() { return { localeError: error19() }; } function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } function withDefiniteArticle(word) { if (!word) return ""; const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } var error20 = () => { const Sizable = { string: { unit: { one: "\u0576\u0577\u0561\u0576", many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, file: { unit: { one: "\u0562\u0561\u0575\u0569", many: "\u0562\u0561\u0575\u0569\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, array: { unit: { one: "\u057F\u0561\u0580\u0580", many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, set: { unit: { one: "\u057F\u0561\u0580\u0580", many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0574\u0578\u0582\u057F\u0584", email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", url: "URL", emoji: "\u0567\u0574\u0578\u057B\u056B", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", time: "ISO \u056A\u0561\u0574", duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; const TypeDictionary = { nan: "NaN", number: "\u0569\u056B\u057E", array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue3.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; } return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue3.values[1])}`; return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { const maxValue = Number(issue3.maximum); const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue3.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue3.maximum.toString()} ${unit}`; } return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue3.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { const minValue = Number(issue3.minimum); const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue3.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue3.minimum.toString()} ${unit}`; } return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue3.origin)} \u056C\u056B\u0576\u056B ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; if (_issue.format === "ends_with") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; if (_issue.format === "includes") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; if (_issue.format === "regex") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue3.divisor}-\u056B`; case "unrecognized_keys": return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue3.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue3.origin)}-\u0578\u0582\u0574`; case "invalid_union": return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; case "invalid_element": return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue3.origin)}-\u0578\u0582\u0574`; default: return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; } }; }; function hy_default() { return { localeError: error20() }; } var error21 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "alamat email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Input tidak valid: diharapkan instanceof ${issue3.expected}, diterima ${received}`; } return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Input tidak valid: diharapkan ${stringifyPrimitive(issue3.values[0])}`; return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} memiliki ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} menjadi ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Terlalu kecil: diharapkan ${issue3.origin} memiliki ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: diharapkan ${issue3.origin} menjadi ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak valid: harus menyertakan "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak valid: harus sesuai pola ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue3.format} tidak valid`; } case "not_multiple_of": return `Angka tidak valid: harus kelipatan dari ${issue3.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Kunci tidak valid di ${issue3.origin}`; case "invalid_union": return "Input tidak valid"; case "invalid_element": return `Nilai tidak valid di ${issue3.origin}`; default: return `Input tidak valid`; } }; }; function id_default() { return { localeError: error21() }; } var error22 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, set: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "gildi", email: "netfang", url: "vefsl\xF3\xF0", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dagsetning og t\xEDmi", date: "ISO dagsetning", time: "ISO t\xEDmi", duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", jwt: "JWT", template_literal: "gildi" }; const TypeDictionary = { nan: "NaN", number: "n\xFAmer", array: "fylki" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue3.expected}`; } return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; } case "invalid_value": if (issue3.values.length === 1) return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue3.values[0])}`; return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin ?? "gildi"} hafi ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "hluti"}`; return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin ?? "gildi"} s\xE9 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin} hafi ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin} s\xE9 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; if (_issue.format === "regex") return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; return `Rangt ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue3.divisor}`; case "unrecognized_keys": return `\xD3\xFEekkt ${issue3.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Rangur lykill \xED ${issue3.origin}`; case "invalid_union": return "Rangt gildi"; case "invalid_element": return `Rangt gildi \xED ${issue3.origin}`; default: return `Rangt gildi`; } }; }; function is_default() { return { localeError: error22() }; } var error23 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "indirizzo email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "numero", array: "vettore" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Input non valido: atteso instanceof ${issue3.expected}, ricevuto ${received}`; } return `Input non valido: atteso ${expected}, ricevuto ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Input non valido: atteso ${stringifyPrimitive(issue3.values[0])}`; return `Opzione non valida: atteso uno tra ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Troppo grande: ${issue3.origin ?? "valore"} deve avere ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementi"}`; return `Troppo grande: ${issue3.origin ?? "valore"} deve essere ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Troppo piccolo: ${issue3.origin} deve avere ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Troppo piccolo: ${issue3.origin} deve essere ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Stringa non valida: deve terminare con "${_issue.suffix}"`; if (_issue.format === "includes") return `Stringa non valida: deve includere "${_issue.includes}"`; if (_issue.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; return `Input non valido: ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Numero non valido: deve essere un multiplo di ${issue3.divisor}`; case "unrecognized_keys": return `Chiav${issue3.keys.length > 1 ? "i" : "e"} non riconosciut${issue3.keys.length > 1 ? "e" : "a"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Chiave non valida in ${issue3.origin}`; case "invalid_union": return "Input non valido"; case "invalid_element": return `Valore non valido in ${issue3.origin}`; default: return `Input non valido`; } }; }; function it_default() { return { localeError: error23() }; } var error24 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u5165\u529B\u5024", email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", url: "URL", emoji: "\u7D75\u6587\u5B57", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u6642", date: "ISO\u65E5\u4ED8", time: "ISO\u6642\u523B", duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; const TypeDictionary = { nan: "NaN", number: "\u6570\u5024", array: "\u914D\u5217" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue3.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; } return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; } case "invalid_value": if (issue3.values.length === 1) return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue3.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue3.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "too_big": { const adj = issue3.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; const sizing = getSizing(issue3.origin); if (sizing) return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue3.origin ?? "\u5024"}\u306F${issue3.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue3.origin ?? "\u5024"}\u306F${issue3.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "too_small": { const adj = issue3.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; const sizing = getSizing(issue3.origin); if (sizing) return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue3.origin}\u306F${issue3.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue3.origin}\u306F${issue3.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "ends_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "includes") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "regex") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u7121\u52B9\u306A\u6570\u5024: ${issue3.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "unrecognized_keys": return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue3.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue3.keys, "\u3001")}`; case "invalid_key": return `${issue3.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; case "invalid_union": return "\u7121\u52B9\u306A\u5165\u529B"; case "invalid_element": return `${issue3.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; default: return `\u7121\u52B9\u306A\u5165\u529B`; } }; }; function ja_default() { return { localeError: error24() }; } var error25 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", url: "URL", emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", time: "\u10D3\u10E0\u10DD", duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", json_string: "JSON \u10D5\u10D4\u10DA\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; const TypeDictionary = { nan: "NaN", number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", string: "\u10D5\u10D4\u10DA\u10D8", boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue3.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; } return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue3.values[0])}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue3.values, "|")}-\u10D3\u10D0\u10DC`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue3.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit}`; return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue3.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue3.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; } if (_issue.format === "ends_with") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; if (_issue.format === "includes") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; if (_issue.format === "regex") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue3.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; case "unrecognized_keys": return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue3.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue3.origin}-\u10E8\u10D8`; case "invalid_union": return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; case "invalid_element": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue3.origin}-\u10E8\u10D8`; default: return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; } }; }; function ka_default() { return { localeError: error25() }; } var error26 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", url: "URL", emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", time: "\u1798\u17C9\u17C4\u1784 ISO", duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; const TypeDictionary = { nan: "NaN", number: "\u179B\u17C1\u1781", array: "\u17A2\u17B6\u179A\u17C1 (Array)", null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue3.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; } return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue3.values[0])}`; return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin} ${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; if (_issue.format === "regex") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue3.divisor}`; case "unrecognized_keys": return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue3.origin}`; case "invalid_union": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; case "invalid_element": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue3.origin}`; default: return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; } }; }; function km_default() { return { localeError: error26() }; } function kh_default() { return km_default(); } var error27 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, set: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\uC785\uB825", email: "\uC774\uBA54\uC77C \uC8FC\uC18C", url: "URL", emoji: "\uC774\uBAA8\uC9C0", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", date: "ISO \uB0A0\uC9DC", time: "ISO \uC2DC\uAC04", duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", jwt: "JWT", template_literal: "\uC785\uB825" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue3.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; } return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; } case "invalid_value": if (issue3.values.length === 1) return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue3.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue3.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "too_big": { const adj = issue3.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue3.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue3.maximum.toString()}${unit} ${adj}${suffix}`; return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue3.maximum.toString()} ${adj}${suffix}`; } case "too_small": { const adj = issue3.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue3.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) { return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue3.minimum.toString()}${unit} ${adj}${suffix}`; } return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue3.minimum.toString()} ${adj}${suffix}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; } if (_issue.format === "ends_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "includes") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "regex") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue3.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "unrecognized_keys": return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\uC798\uBABB\uB41C \uD0A4: ${issue3.origin}`; case "invalid_union": return `\uC798\uBABB\uB41C \uC785\uB825`; case "invalid_element": return `\uC798\uBABB\uB41C \uAC12: ${issue3.origin}`; default: return `\uC798\uBABB\uB41C \uC785\uB825`; } }; }; function ko_default() { return { localeError: error27() }; } var capitalizeFirstCharacter = (text42) => { return text42.charAt(0).toUpperCase() + text42.slice(1); }; function getUnitTypeFromNumber(number7) { const abs = Math.abs(number7); const last = abs % 10; const last2 = abs % 100; if (last2 >= 11 && last2 <= 19 || last === 0) return "many"; if (last === 1) return "one"; return "few"; } var error28 = () => { const Sizable = { string: { unit: { one: "simbolis", few: "simboliai", many: "simboli\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" }, bigger: { inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" } } }, file: { unit: { one: "baitas", few: "baitai", many: "bait\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne didesnis kaip", notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" }, bigger: { inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", notInclusive: "turi b\u016Bti didesnis kaip" } } }, array: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } }, set: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } } }; function getSizing(origin, unitType, inclusive, targetShouldBe) { const result = Sizable[origin] ?? null; if (result === null) return result; return { unit: result.unit[unitType], verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] }; } const FormatDictionary = { regex: "\u012Fvestis", email: "el. pa\u0161to adresas", url: "URL", emoji: "jaustukas", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO data ir laikas", date: "ISO data", time: "ISO laikas", duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", jwt: "JWT", template_literal: "\u012Fvestis" }; const TypeDictionary = { nan: "NaN", number: "skai\u010Dius", bigint: "sveikasis skai\u010Dius", string: "eilut\u0117", boolean: "login\u0117 reik\u0161m\u0117", undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", function: "funkcija", symbol: "simbolis", array: "masyvas", object: "objektas", null: "nulin\u0117 reik\u0161m\u0117" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue3.expected}`; } return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; } case "invalid_value": if (issue3.values.length === 1) return `Privalo b\u016Bti ${stringifyPrimitive(issue3.values[0])}`; return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue3.values, "|")} pasirinkim\u0173`; case "too_big": { const origin = TypeDictionary[issue3.origin] ?? issue3.origin; const sizing = getSizing(issue3.origin, getUnitTypeFromNumber(Number(issue3.maximum)), issue3.inclusive ?? false, "smaller"); if (sizing?.verb) return `${capitalizeFirstCharacter(origin ?? issue3.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue3.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; const adj = issue3.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; return `${capitalizeFirstCharacter(origin ?? issue3.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue3.maximum.toString()} ${sizing?.unit}`; } case "too_small": { const origin = TypeDictionary[issue3.origin] ?? issue3.origin; const sizing = getSizing(issue3.origin, getUnitTypeFromNumber(Number(issue3.minimum)), issue3.inclusive ?? false, "bigger"); if (sizing?.verb) return `${capitalizeFirstCharacter(origin ?? issue3.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue3.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; const adj = issue3.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; return `${capitalizeFirstCharacter(origin ?? issue3.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue3.minimum.toString()} ${sizing?.unit}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; if (_issue.format === "includes") return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; if (_issue.format === "regex") return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; return `Neteisingas ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Skai\u010Dius privalo b\u016Bti ${issue3.divisor} kartotinis.`; case "unrecognized_keys": return `Neatpa\u017Eint${issue3.keys.length > 1 ? "i" : "as"} rakt${issue3.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return "Rastas klaidingas raktas"; case "invalid_union": return "Klaidinga \u012Fvestis"; case "invalid_element": { const origin = TypeDictionary[issue3.origin] ?? issue3.origin; return `${capitalizeFirstCharacter(origin ?? issue3.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; } default: return "Klaidinga \u012Fvestis"; } }; }; function lt_default() { return { localeError: error28() }; } var error29 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u043D\u0435\u0441", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", url: "URL", emoji: "\u0435\u043C\u043E\u045F\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0443\u043C", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; const TypeDictionary = { nan: "NaN", number: "\u0431\u0440\u043E\u0458", array: "\u043D\u0438\u0437\u0430" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue3.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; } return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue3.values[0])}`; return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; return `Invalid ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue3.divisor}`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue3.origin}`; case "invalid_union": return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; case "invalid_element": return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue3.origin}`; default: return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; } }; }; function mk_default() { return { localeError: error29() }; } var error30 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "alamat e-mel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "nombor" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Input tidak sah: dijangka instanceof ${issue3.expected}, diterima ${received}`; } return `Input tidak sah: dijangka ${expected}, diterima ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Input tidak sah: dijangka ${stringifyPrimitive(issue3.values[0])}`; return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} adalah ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Terlalu kecil: dijangka ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: dijangka ${issue3.origin} adalah ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak sah: mesti mengandungi "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue3.format} tidak sah`; } case "not_multiple_of": return `Nombor tidak sah: perlu gandaan ${issue3.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Kunci tidak sah dalam ${issue3.origin}`; case "invalid_union": return "Input tidak sah"; case "invalid_element": return `Nilai tidak sah dalam ${issue3.origin}`; default: return `Input tidak sah`; } }; }; function ms_default() { return { localeError: error30() }; } var error31 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, set: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "invoer", email: "emailadres", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" }; const TypeDictionary = { nan: "NaN", number: "getal" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Ongeldige invoer: verwacht instanceof ${issue3.expected}, ontving ${received}`; } return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue3.values[0])}`; return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); const longName = issue3.origin === "date" ? "laat" : issue3.origin === "string" ? "lang" : "groot"; if (sizing) return `Te ${longName}: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; return `Te ${longName}: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} is`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); const shortName = issue3.origin === "date" ? "vroeg" : issue3.origin === "string" ? "kort" : "klein"; if (sizing) { return `Te ${shortName}: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} ${sizing.verb}`; } return `Te ${shortName}: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} is`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; } if (_issue.format === "ends_with") return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; if (_issue.format === "includes") return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; if (_issue.format === "regex") return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ongeldig getal: moet een veelvoud van ${issue3.divisor} zijn`; case "unrecognized_keys": return `Onbekende key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Ongeldige key in ${issue3.origin}`; case "invalid_union": return "Ongeldige invoer"; case "invalid_element": return `Ongeldige waarde in ${issue3.origin}`; default: return `Ongeldige invoer`; } }; }; function nl_default() { return { localeError: error31() }; } var error32 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, set: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "e-postadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "tall", array: "liste" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Ugyldig input: forventet instanceof ${issue3.expected}, fikk ${received}`; } return `Ugyldig input: forventet ${expected}, fikk ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Ugyldig verdi: forventet ${stringifyPrimitive(issue3.values[0])}`; return `Ugyldig valg: forventet en av ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `For stor(t): forventet ${issue3.origin ?? "value"} til \xE5 ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor(t): forventet ${issue3.origin ?? "value"} til \xE5 ha ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `For lite(n): forventet ${issue3.origin} til \xE5 ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `For lite(n): forventet ${issue3.origin} til \xE5 ha ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue3.divisor}`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8kkel i ${issue3.origin}`; case "invalid_union": return "Ugyldig input"; case "invalid_element": return `Ugyldig verdi i ${issue3.origin}`; default: return `Ugyldig input`; } }; }; function no_default() { return { localeError: error32() }; } var error33 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "giren", email: "epostag\xE2h", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO heng\xE2m\u0131", date: "ISO tarihi", time: "ISO zaman\u0131", duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "giren" }; const TypeDictionary = { nan: "NaN", number: "numara", array: "saf", null: "gayb" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `F\xE2sit giren: umulan instanceof ${issue3.expected}, al\u0131nan ${received}`; } return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `F\xE2sit giren: umulan ${stringifyPrimitive(issue3.values[0])}`; return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Fazla b\xFCy\xFCk: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; return `Fazla b\xFCy\xFCk: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} olmal\u0131yd\u0131.`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Fazla k\xFC\xE7\xFCk: ${issue3.origin}, ${adj}${issue3.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; } return `Fazla k\xFC\xE7\xFCk: ${issue3.origin}, ${adj}${issue3.minimum.toString()} olmal\u0131yd\u0131.`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; if (_issue.format === "ends_with") return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; if (_issue.format === "includes") return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; if (_issue.format === "regex") return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `F\xE2sit say\u0131: ${issue3.divisor} kat\u0131 olmal\u0131yd\u0131.`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} i\xE7in tan\u0131nmayan anahtar var.`; case "invalid_union": return "Giren tan\u0131namad\u0131."; case "invalid_element": return `${issue3.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; default: return `K\u0131ymet tan\u0131namad\u0131.`; } }; }; function ota_default() { return { localeError: error33() }; } var error34 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0648\u0631\u0648\u062F\u064A", email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", date: "\u0646\u06D0\u067C\u0647", time: "\u0648\u062E\u062A", duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; const TypeDictionary = { nan: "NaN", number: "\u0639\u062F\u062F", array: "\u0627\u0631\u06D0" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue3.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; } return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; } case "invalid_value": if (issue3.values.length === 1) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue3.values[0])} \u0648\u0627\u06CC`; } return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue3.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue3.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue3.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} \u0648\u064A`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} \u0648\u064A`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; } if (_issue.format === "ends_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; } if (_issue.format === "includes") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; } if (_issue.format === "regex") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; } return `${FormatDictionary[_issue.format] ?? issue3.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; } case "not_multiple_of": return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue3.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; case "unrecognized_keys": return `\u0646\u0627\u0633\u0645 ${issue3.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue3.origin} \u06A9\u06D0`; case "invalid_union": return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; case "invalid_element": return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue3.origin} \u06A9\u06D0`; default: return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; } }; }; function ps_default() { return { localeError: error34() }; } var error35 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, set: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "wyra\u017Cenie", email: "adres email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wej\u015Bcie" }; const TypeDictionary = { nan: "NaN", number: "liczba", array: "tablica" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue3.expected}, otrzymano ${received}`; } return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue3.values[0])}`; return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; if (_issue.format === "includes") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; if (_issue.format === "regex") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue3.divisor}`; case "unrecognized_keys": return `Nierozpoznane klucze${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Nieprawid\u0142owy klucz w ${issue3.origin}`; case "invalid_union": return "Nieprawid\u0142owe dane wej\u015Bciowe"; case "invalid_element": return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue3.origin}`; default: return `Nieprawid\u0142owe dane wej\u015Bciowe`; } }; }; function pl_default() { return { localeError: error35() }; } var error36 = () => { const Sizable = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "padr\xE3o", email: "endere\xE7o de e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "dura\xE7\xE3o ISO", ipv4: "endere\xE7o IPv4", ipv6: "endere\xE7o IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN", number: "n\xFAmero", null: "nulo" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Tipo inv\xE1lido: esperado instanceof ${issue3.expected}, recebido ${received}`; } return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue3.values[0])}`; return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Muito grande: esperado que ${issue3.origin ?? "valor"} tivesse ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Muito grande: esperado que ${issue3.origin ?? "valor"} fosse ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Muito pequeno: esperado que ${issue3.origin} tivesse ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Muito pequeno: esperado que ${issue3.origin} fosse ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue3.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue3.divisor}`; case "unrecognized_keys": return `Chave${issue3.keys.length > 1 ? "s" : ""} desconhecida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Chave inv\xE1lida em ${issue3.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido em ${issue3.origin}`; default: return `Campo inv\xE1lido`; } }; }; function pt_default() { return { localeError: error36() }; } var error37 = () => { const Sizable = { string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, array: { unit: "elemente", verb: "s\u0103 aib\u0103" }, set: { unit: "elemente", verb: "s\u0103 aib\u0103" }, map: { unit: "intr\u0103ri", verb: "s\u0103 aib\u0103" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "intrare", email: "adres\u0103 de email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "dat\u0103 \u0219i or\u0103 ISO", date: "dat\u0103 ISO", time: "or\u0103 ISO", duration: "durat\u0103 ISO", ipv4: "adres\u0103 IPv4", ipv6: "adres\u0103 IPv6", mac: "adres\u0103 MAC", cidrv4: "interval IPv4", cidrv6: "interval IPv6", base64: "\u0219ir codat base64", base64url: "\u0219ir codat base64url", json_string: "\u0219ir JSON", e164: "num\u0103r E.164", jwt: "JWT", template_literal: "intrare" }; const TypeDictionary = { nan: "NaN", string: "\u0219ir", number: "num\u0103r", boolean: "boolean", function: "func\u021Bie", array: "matrice", object: "obiect", undefined: "nedefinit", symbol: "simbol", bigint: "num\u0103r mare", void: "void", never: "never", map: "hart\u0103", set: "set" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue3.values[0])}`; return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Prea mare: a\u0219teptat ca ${issue3.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemente"}`; return `Prea mare: a\u0219teptat ca ${issue3.origin ?? "valoarea"} s\u0103 fie ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Prea mic: a\u0219teptat ca ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Prea mic: a\u0219teptat ca ${issue3.origin} s\u0103 fie ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`; return `Format invalid: ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue3.divisor}`; case "unrecognized_keys": return `Chei nerecunoscute: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Cheie invalid\u0103 \xEEn ${issue3.origin}`; case "invalid_union": return "Intrare invalid\u0103"; case "invalid_element": return `Valoare invalid\u0103 \xEEn ${issue3.origin}`; default: return `Intrare invalid\u0103`; } }; }; function ro_default() { return { localeError: error37() }; } function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error38 = () => { const Sizable = { string: { unit: { one: "\u0441\u0438\u043C\u0432\u043E\u043B", few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u0430", many: "\u0431\u0430\u0439\u0442" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u044F", duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0441\u0438\u0432" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue3.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; } return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue3.values[0])}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { const maxValue = Number(issue3.maximum); const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue3.maximum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { const minValue = Number(issue3.minimum); const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue3.minimum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue3.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue3.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue3.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; case "invalid_element": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue3.origin}`; default: return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; } }; }; function ru_default() { return { localeError: error38() }; } var error39 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "vnos", email: "e-po\u0161tni naslov", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum in \u010Das", date: "ISO datum", time: "ISO \u010Das", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", jwt: "JWT", template_literal: "vnos" }; const TypeDictionary = { nan: "NaN", number: "\u0161tevilo", array: "tabela" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue3.expected}, prejeto ${received}`; } return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue3.values[0])}`; return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Preveliko: pri\u010Dakovano, da bo ${issue3.origin ?? "vrednost"} imelo ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementov"}`; return `Preveliko: pri\u010Dakovano, da bo ${issue3.origin ?? "vrednost"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Premajhno: pri\u010Dakovano, da bo ${issue3.origin} imelo ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Premajhno: pri\u010Dakovano, da bo ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; if (_issue.format === "includes") return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; if (_issue.format === "regex") return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; return `Neveljaven ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue3.divisor}`; case "unrecognized_keys": return `Neprepoznan${issue3.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Neveljaven klju\u010D v ${issue3.origin}`; case "invalid_union": return "Neveljaven vnos"; case "invalid_element": return `Neveljavna vrednost v ${issue3.origin}`; default: return "Neveljaven vnos"; } }; }; function sl_default() { return { localeError: error39() }; } var error40 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, set: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "regulj\xE4rt uttryck", email: "e-postadress", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" }; const TypeDictionary = { nan: "NaN", number: "antal", array: "lista" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue3.expected}, fick ${received}`; } return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue3.values[0])}`; return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; } return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; if (_issue.format === "regex") return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue3.divisor}`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Ogiltig nyckel i ${issue3.origin ?? "v\xE4rdet"}`; case "invalid_union": return "Ogiltig input"; case "invalid_element": return `Ogiltigt v\xE4rde i ${issue3.origin ?? "v\xE4rdet"}`; default: return `Ogiltig input`; } }; }; function sv_default() { return { localeError: error40() }; } var error41 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "\u0B8E\u0BA3\u0BCD", array: "\u0B85\u0BA3\u0BBF", null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue3.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; } return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue3.values[0])}`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue3.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue3.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin} ${adj}${issue3.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "ends_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "includes") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "regex") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue3.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; case "unrecognized_keys": return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue3.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; case "invalid_union": return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; case "invalid_element": return `${issue3.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; default: return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; } }; }; function ta_default() { return { localeError: error41() }; } var error42 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", url: "URL", emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; const TypeDictionary = { nan: "NaN", number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue3.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; } return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue3.values[0])}`; return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue3.origin); if (sizing) return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; if (_issue.format === "regex") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue3.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; case "unrecognized_keys": return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue3.origin}`; case "invalid_union": return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; case "invalid_element": return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue3.origin}`; default: return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; } }; }; function th_default() { return { localeError: error42() }; } var error43 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "girdi", email: "e-posta adresi", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue3.expected}, al\u0131nan ${received}`; } return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue3.values[0])}`; return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ok b\xFCy\xFCk: beklenen ${issue3.origin ?? "de\u011Fer"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; return `\xC7ok b\xFCy\xFCk: beklenen ${issue3.origin ?? "de\u011Fer"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; if (_issue.format === "ends_with") return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; if (_issue.format === "includes") return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; if (_issue.format === "regex") return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ge\xE7ersiz say\u0131: ${issue3.divisor} ile tam b\xF6l\xFCnebilmeli`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} i\xE7inde ge\xE7ersiz anahtar`; case "invalid_union": return "Ge\xE7ersiz de\u011Fer"; case "invalid_element": return `${issue3.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; default: return `Ge\xE7ersiz de\u011Fer`; } }; }; function tr_default() { return { localeError: error43() }; } var error44 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", date: "\u0434\u0430\u0442\u0430 ISO", time: "\u0447\u0430\u0441 ISO", duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0438\u0432" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue3.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; } return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue3.values[0])}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin} \u0431\u0443\u0434\u0435 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue3.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue3.origin}`; case "invalid_union": return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; case "invalid_element": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue3.origin}`; default: return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; } }; }; function uk_default() { return { localeError: error44() }; } function ua_default() { return uk_default(); } var error45 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0627\u0646 \u067E\u0679", email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; const TypeDictionary = { nan: "NaN", number: "\u0646\u0645\u0628\u0631", array: "\u0622\u0631\u06D2", null: "\u0646\u0644" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue3.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; } return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; } case "invalid_value": if (issue3.values.length === 1) return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue3.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue3.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue3.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue3.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue3.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue3.origin} \u06A9\u06D2 ${adj}${issue3.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; } return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue3.origin} \u06A9\u0627 ${adj}${issue3.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; } if (_issue.format === "ends_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "includes") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "regex") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue3.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; case "unrecognized_keys": return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue3.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue3.keys, "\u060C ")}`; case "invalid_key": return `${issue3.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; case "invalid_union": return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; case "invalid_element": return `${issue3.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; default: return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; } }; }; function ur_default() { return { localeError: error45() }; } var error46 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, array: { unit: "element", verb: "bo\u2018lishi kerak" }, set: { unit: "element", verb: "bo\u2018lishi kerak" }, map: { unit: "yozuv", verb: "bo\u2018lishi kerak" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "kirish", email: "elektron pochta manzili", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO sana va vaqti", date: "ISO sana", time: "ISO vaqt", duration: "ISO davomiylik", ipv4: "IPv4 manzil", ipv6: "IPv6 manzil", mac: "MAC manzil", cidrv4: "IPv4 diapazon", cidrv6: "IPv6 diapazon", base64: "base64 kodlangan satr", base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", jwt: "JWT", template_literal: "kirish" }; const TypeDictionary = { nan: "NaN", number: "raqam", array: "massiv" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue3.expected}, qabul qilingan ${received}`; } return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue3.values[0])}`; return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Juda katta: kutilgan ${issue3.origin ?? "qiymat"} ${adj}${issue3.maximum.toString()} ${sizing.unit} ${sizing.verb}`; return `Juda katta: kutilgan ${issue3.origin ?? "qiymat"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Juda kichik: kutilgan ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} ${sizing.verb}`; } return `Juda kichik: kutilgan ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; if (_issue.format === "ends_with") return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; if (_issue.format === "includes") return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; if (_issue.format === "regex") return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Noto\u2018g\u2018ri raqam: ${issue3.divisor} ning karralisi bo\u2018lishi kerak`; case "unrecognized_keys": return `Noma\u2019lum kalit${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} dagi kalit noto\u2018g\u2018ri`; case "invalid_union": return "Noto\u2018g\u2018ri kirish"; case "invalid_element": return `${issue3.origin} da noto\u2018g\u2018ri qiymat`; default: return `Noto\u2018g\u2018ri kirish`; } }; }; function uz_default() { return { localeError: error46() }; } var error47 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0111\u1EA7u v\xE0o", email: "\u0111\u1ECBa ch\u1EC9 email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ng\xE0y gi\u1EDD ISO", date: "ng\xE0y ISO", time: "gi\u1EDD ISO", duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; const TypeDictionary = { nan: "NaN", number: "s\u1ED1", array: "m\u1EA3ng" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue3.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; } return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue3.values[0])}`; return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue3.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue3.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; if (_issue.format === "includes") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; if (_issue.format === "regex") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue3.format} kh\xF4ng h\u1EE3p l\u1EC7`; } case "not_multiple_of": return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue3.divisor}`; case "unrecognized_keys": return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue3.origin}`; case "invalid_union": return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; case "invalid_element": return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue3.origin}`; default: return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; } }; }; function vi_default() { return { localeError: error47() }; } var error48 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, set: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u8F93\u5165", email: "\u7535\u5B50\u90AE\u4EF6", url: "URL", emoji: "\u8868\u60C5\u7B26\u53F7", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u671F\u65F6\u95F4", date: "ISO\u65E5\u671F", time: "ISO\u65F6\u95F4", duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", jwt: "JWT", template_literal: "\u8F93\u5165" }; const TypeDictionary = { nan: "NaN", number: "\u6570\u5B57", array: "\u6570\u7EC4", null: "\u7A7A\u503C(null)" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue3.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; } return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue3.values[0])}`; return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue3.origin ?? "\u503C"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue3.origin ?? "\u503C"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; if (_issue.format === "ends_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; if (_issue.format === "includes") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue3.divisor} \u7684\u500D\u6570`; case "unrecognized_keys": return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; case "invalid_union": return "\u65E0\u6548\u8F93\u5165"; case "invalid_element": return `${issue3.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; default: return `\u65E0\u6548\u8F93\u5165`; } }; }; function zh_CN_default() { return { localeError: error48() }; } var error49 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u8F38\u5165", email: "\u90F5\u4EF6\u5730\u5740", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u65E5\u671F\u6642\u9593", date: "ISO \u65E5\u671F", time: "ISO \u6642\u9593", duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", jwt: "JWT", template_literal: "\u8F38\u5165" }; const TypeDictionary = { nan: "NaN" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue3.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; } return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue3.values[0])}`; return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue3.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue3.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue3.origin} \u61C9\u70BA ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue3.origin} \u61C9\u70BA ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; } if (_issue.format === "ends_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; if (_issue.format === "includes") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue3.divisor} \u7684\u500D\u6578`; case "unrecognized_keys": return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue3.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue3.keys, "\u3001")}`; case "invalid_key": return `${issue3.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; case "invalid_union": return "\u7121\u6548\u7684\u8F38\u5165\u503C"; case "invalid_element": return `${issue3.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; default: return `\u7121\u6548\u7684\u8F38\u5165\u503C`; } }; }; function zh_TW_default() { return { localeError: error49() }; } var error50 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, set: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\xE0k\xF3k\xF2 ISO", date: "\u1ECDj\u1ECD\u0301 ISO", time: "\xE0k\xF3k\xF2 ISO", duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; const TypeDictionary = { nan: "NaN", number: "n\u1ECD\u0301mb\xE0", array: "akop\u1ECD" }; return (issue3) => { switch (issue3.code) { case "invalid_type": { const expected = TypeDictionary[issue3.expected] ?? issue3.expected; const receivedType = parsedType(issue3.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue3.expected)) { return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue3.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; } return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; } case "invalid_value": if (issue3.values.length === 1) return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue3.values[0])}`; return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue3.origin ?? "iye"} ${sizing.verb} ${adj}${issue3.maximum} ${sizing.unit}`; return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue3.maximum}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum} ${sizing.unit}`; return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue3.minimum}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; if (_issue.format === "regex") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue3.divisor}`; case "unrecognized_keys": return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue3.keys, ", ")}`; case "invalid_key": return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue3.origin}`; case "invalid_union": return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; case "invalid_element": return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue3.origin}`; default: return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; } }; }; function yo_default() { return { localeError: error50() }; } var _a18; var $output = /* @__PURE__ */ Symbol("ZodOutput"); var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); } add(schema, ..._meta) { const meta3 = _meta[0]; this._map.set(schema, meta3); if (meta3 && typeof meta3 === "object" && "id" in meta3) { this._idmap.set(meta3.id, schema); } return this; } clear() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); return this; } remove(schema) { const meta3 = this._map.get(schema); if (meta3 && typeof meta3 === "object" && "id" in meta3) { this._idmap.delete(meta3.id); } this._map.delete(schema); return this; } get(schema) { const p = schema._zod.parent; if (p) { const pm = { ...this.get(p) ?? {} }; delete pm.id; const f = { ...pm, ...this._map.get(schema) }; return Object.keys(f).length ? f : void 0; } return this._map.get(schema); } has(schema) { return this._map.has(schema); } }; function registry() { return new $ZodRegistry(); } (_a18 = globalThis).__zod_globalRegistry ?? (_a18.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; // @__NO_SIDE_EFFECTS__ function _string(Class3, params) { return new Class3({ type: "string", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class3, params) { return new Class3({ type: "string", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _email(Class3, params) { return new Class3({ type: "string", format: "email", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _guid(Class3, params) { return new Class3({ type: "string", format: "guid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuid(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv4(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv6(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv7(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _url(Class3, params) { return new Class3({ type: "string", format: "url", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _emoji2(Class3, params) { return new Class3({ type: "string", format: "emoji", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nanoid(Class3, params) { return new Class3({ type: "string", format: "nanoid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cuid(Class3, params) { return new Class3({ type: "string", format: "cuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cuid2(Class3, params) { return new Class3({ type: "string", format: "cuid2", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ulid(Class3, params) { return new Class3({ type: "string", format: "ulid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _xid(Class3, params) { return new Class3({ type: "string", format: "xid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ksuid(Class3, params) { return new Class3({ type: "string", format: "ksuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ipv4(Class3, params) { return new Class3({ type: "string", format: "ipv4", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ipv6(Class3, params) { return new Class3({ type: "string", format: "ipv6", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _mac(Class3, params) { return new Class3({ type: "string", format: "mac", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cidrv4(Class3, params) { return new Class3({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cidrv6(Class3, params) { return new Class3({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _base64(Class3, params) { return new Class3({ type: "string", format: "base64", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _base64url(Class3, params) { return new Class3({ type: "string", format: "base64url", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _e164(Class3, params) { return new Class3({ type: "string", format: "e164", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _jwt(Class3, params) { return new Class3({ type: "string", format: "jwt", check: "string_format", abort: false, ...normalizeParams(params) }); } var TimePrecision = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 }; // @__NO_SIDE_EFFECTS__ function _isoDateTime(Class3, params) { return new Class3({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoDate(Class3, params) { return new Class3({ type: "string", format: "date", check: "string_format", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoTime(Class3, params) { return new Class3({ type: "string", format: "time", check: "string_format", precision: null, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoDuration(Class3, params) { return new Class3({ type: "string", format: "duration", check: "string_format", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _number(Class3, params) { return new Class3({ type: "number", checks: [], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class3, params) { return new Class3({ type: "number", coerce: true, checks: [], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "safeint", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _float32(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "float32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _float64(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "float64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int32(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "int32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uint32(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "uint32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _boolean(Class3, params) { return new Class3({ type: "boolean", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedBoolean(Class3, params) { return new Class3({ type: "boolean", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _bigint(Class3, params) { return new Class3({ type: "bigint", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedBigint(Class3, params) { return new Class3({ type: "bigint", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int64(Class3, params) { return new Class3({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uint64(Class3, params) { return new Class3({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _symbol(Class3, params) { return new Class3({ type: "symbol", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _undefined2(Class3, params) { return new Class3({ type: "undefined", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _null2(Class3, params) { return new Class3({ type: "null", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _any(Class3) { return new Class3({ type: "any" }); } // @__NO_SIDE_EFFECTS__ function _unknown(Class3) { return new Class3({ type: "unknown" }); } // @__NO_SIDE_EFFECTS__ function _never(Class3, params) { return new Class3({ type: "never", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _void(Class3, params) { return new Class3({ type: "void", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _date(Class3, params) { return new Class3({ type: "date", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedDate(Class3, params) { return new Class3({ type: "date", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nan(Class3, params) { return new Class3({ type: "nan", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _lt(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: false }); } // @__NO_SIDE_EFFECTS__ function _lte(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: true }); } // @__NO_SIDE_EFFECTS__ function _gt(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: false }); } // @__NO_SIDE_EFFECTS__ function _gte(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: true }); } // @__NO_SIDE_EFFECTS__ function _positive(params) { return /* @__PURE__ */ _gt(0, params); } // @__NO_SIDE_EFFECTS__ function _negative(params) { return /* @__PURE__ */ _lt(0, params); } // @__NO_SIDE_EFFECTS__ function _nonpositive(params) { return /* @__PURE__ */ _lte(0, params); } // @__NO_SIDE_EFFECTS__ function _nonnegative(params) { return /* @__PURE__ */ _gte(0, params); } // @__NO_SIDE_EFFECTS__ function _multipleOf(value, params) { return new $ZodCheckMultipleOf({ check: "multiple_of", ...normalizeParams(params), value }); } // @__NO_SIDE_EFFECTS__ function _maxSize(maximum, params) { return new $ZodCheckMaxSize({ check: "max_size", ...normalizeParams(params), maximum }); } // @__NO_SIDE_EFFECTS__ function _minSize(minimum, params) { return new $ZodCheckMinSize({ check: "min_size", ...normalizeParams(params), minimum }); } // @__NO_SIDE_EFFECTS__ function _size(size, params) { return new $ZodCheckSizeEquals({ check: "size_equals", ...normalizeParams(params), size }); } // @__NO_SIDE_EFFECTS__ function _maxLength(maximum, params) { const ch = new $ZodCheckMaxLength({ check: "max_length", ...normalizeParams(params), maximum }); return ch; } // @__NO_SIDE_EFFECTS__ function _minLength(minimum, params) { return new $ZodCheckMinLength({ check: "min_length", ...normalizeParams(params), minimum }); } // @__NO_SIDE_EFFECTS__ function _length(length, params) { return new $ZodCheckLengthEquals({ check: "length_equals", ...normalizeParams(params), length }); } // @__NO_SIDE_EFFECTS__ function _regex(pattern, params) { return new $ZodCheckRegex({ check: "string_format", format: "regex", ...normalizeParams(params), pattern }); } // @__NO_SIDE_EFFECTS__ function _lowercase(params) { return new $ZodCheckLowerCase({ check: "string_format", format: "lowercase", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uppercase(params) { return new $ZodCheckUpperCase({ check: "string_format", format: "uppercase", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _includes(includes, params) { return new $ZodCheckIncludes({ check: "string_format", format: "includes", ...normalizeParams(params), includes }); } // @__NO_SIDE_EFFECTS__ function _startsWith(prefix, params) { return new $ZodCheckStartsWith({ check: "string_format", format: "starts_with", ...normalizeParams(params), prefix }); } // @__NO_SIDE_EFFECTS__ function _endsWith(suffix, params) { return new $ZodCheckEndsWith({ check: "string_format", format: "ends_with", ...normalizeParams(params), suffix }); } // @__NO_SIDE_EFFECTS__ function _property(property, schema, params) { return new $ZodCheckProperty({ check: "property", property, schema, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _mime(types, params) { return new $ZodCheckMimeType({ check: "mime_type", mime: types, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _overwrite(tx) { return new $ZodCheckOverwrite({ check: "overwrite", tx }); } // @__NO_SIDE_EFFECTS__ function _normalize(form) { return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { return /* @__PURE__ */ _overwrite((input) => input.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { return /* @__PURE__ */ _overwrite((input) => slugify(input)); } // @__NO_SIDE_EFFECTS__ function _array(Class3, element, params) { return new Class3({ type: "array", element, // get element() { // return element; // }, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _union(Class3, options, params) { return new Class3({ type: "union", options, ...normalizeParams(params) }); } function _xor(Class3, options, params) { return new Class3({ type: "union", options, inclusive: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _discriminatedUnion(Class3, discriminator, options, params) { return new Class3({ type: "union", options, discriminator, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _intersection(Class3, left, right) { return new Class3({ type: "intersection", left, right }); } // @__NO_SIDE_EFFECTS__ function _tuple(Class3, items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new Class3({ type: "tuple", items, rest, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _record(Class3, keyType, valueType, params) { return new Class3({ type: "record", keyType, valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _map(Class3, keyType, valueType, params) { return new Class3({ type: "map", keyType, valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _set(Class3, valueType, params) { return new Class3({ type: "set", valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _enum(Class3, values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new Class3({ type: "enum", entries, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nativeEnum(Class3, entries, params) { return new Class3({ type: "enum", entries, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _literal(Class3, value, params) { return new Class3({ type: "literal", values: Array.isArray(value) ? value : [value], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _file(Class3, params) { return new Class3({ type: "file", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _transform(Class3, fn) { return new Class3({ type: "transform", transform: fn }); } // @__NO_SIDE_EFFECTS__ function _optional(Class3, innerType) { return new Class3({ type: "optional", innerType }); } // @__NO_SIDE_EFFECTS__ function _nullable(Class3, innerType) { return new Class3({ type: "nullable", innerType }); } // @__NO_SIDE_EFFECTS__ function _default(Class3, innerType, defaultValue) { return new Class3({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); } }); } // @__NO_SIDE_EFFECTS__ function _nonoptional(Class3, innerType, params) { return new Class3({ type: "nonoptional", innerType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _success(Class3, innerType) { return new Class3({ type: "success", innerType }); } // @__NO_SIDE_EFFECTS__ function _catch(Class3, innerType, catchValue) { return new Class3({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } // @__NO_SIDE_EFFECTS__ function _pipe(Class3, in_, out) { return new Class3({ type: "pipe", in: in_, out }); } // @__NO_SIDE_EFFECTS__ function _readonly(Class3, innerType) { return new Class3({ type: "readonly", innerType }); } // @__NO_SIDE_EFFECTS__ function _templateLiteral(Class3, parts, params) { return new Class3({ type: "template_literal", parts, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _lazy(Class3, getter) { return new Class3({ type: "lazy", getter }); } // @__NO_SIDE_EFFECTS__ function _promise(Class3, innerType) { return new Class3({ type: "promise", innerType }); } // @__NO_SIDE_EFFECTS__ function _custom(Class3, fn, _params) { const norm = normalizeParams(_params); norm.abort ?? (norm.abort = true); const schema = new Class3({ type: "custom", check: "custom", fn, ...norm }); return schema; } // @__NO_SIDE_EFFECTS__ function _refine(Class3, fn, _params) { const schema = new Class3({ type: "custom", check: "custom", fn, ...normalizeParams(_params) }); return schema; } // @__NO_SIDE_EFFECTS__ function _superRefine(fn, params) { const ch = /* @__PURE__ */ _check((payload) => { payload.addIssue = (issue3) => { if (typeof issue3 === "string") { payload.issues.push(issue(issue3, payload.value, ch._zod.def)); } else { const _issue = issue3; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); } }; return fn(payload.value, payload); }, params); return ch; } // @__NO_SIDE_EFFECTS__ function _check(fn, params) { const ch = new $ZodCheck({ check: "custom", ...normalizeParams(params) }); ch._zod.check = fn; return ch; } // @__NO_SIDE_EFFECTS__ function describe(description) { const ch = new $ZodCheck({ check: "describe" }); ch._zod.onattach = [ (inst) => { const existing = globalRegistry.get(inst) ?? {}; globalRegistry.add(inst, { ...existing, description }); } ]; ch._zod.check = () => { }; return ch; } // @__NO_SIDE_EFFECTS__ function meta(metadata) { const ch = new $ZodCheck({ check: "meta" }); ch._zod.onattach = [ (inst) => { const existing = globalRegistry.get(inst) ?? {}; globalRegistry.add(inst, { ...existing, ...metadata }); } ]; ch._zod.check = () => { }; return ch; } // @__NO_SIDE_EFFECTS__ function _stringbool(Classes, _params) { const params = normalizeParams(_params); let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; if (params.case !== "sensitive") { truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); } const truthySet = new Set(truthyArray); const falsySet = new Set(falsyArray); const _Codec = Classes.Codec ?? $ZodCodec; const _Boolean = Classes.Boolean ?? $ZodBoolean; const _String = Classes.String ?? $ZodString; const stringSchema = new _String({ type: "string", error: params.error }); const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); const codec2 = new _Codec({ type: "pipe", in: stringSchema, out: booleanSchema, transform: ((input, payload) => { let data = input; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { return true; } else if (falsySet.has(data)) { return false; } else { payload.issues.push({ code: "invalid_value", expected: "stringbool", values: [...truthySet, ...falsySet], input: payload.value, inst: codec2, continue: false }); return {}; } }), reverseTransform: ((input, _payload) => { if (input === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; } }), error: params.error }); return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class3, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { ...normalizeParams(_params), check: "string_format", type: "string", format, fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), ...params }; if (fnOrRegex instanceof RegExp) { def.pattern = fnOrRegex; } const inst = new Class3(def); return inst; } function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") target = "draft-04"; if (target === "draft-7") target = "draft-07"; return { processors: params.processors ?? {}, metadataRegistry: params?.metadata ?? globalRegistry, target, unrepresentable: params?.unrepresentable ?? "throw", override: params?.override ?? (() => { }), io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", external: params?.external ?? void 0 }; } function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a282; const def = schema._zod.def; const seen = ctx.seen.get(schema); if (seen) { seen.count++; const isCycle = _params.schemaPath.includes(schema); if (isCycle) { seen.cycle = _params.path; } return seen.schema; } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; } else { const params = { ..._params, schemaPath: [..._params.schemaPath, schema], path: _params.path }; if (schema._zod.processJSONSchema) { schema._zod.processJSONSchema(ctx, result.schema, params); } else { const _json = result.schema; const processor = ctx.processors[def.type]; if (!processor) { throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); } processor(schema, ctx, _json, params); } const parent = schema._zod.parent; if (parent) { if (!result.ref) result.ref = parent; process2(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) Object.assign(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; } if (ctx.io === "input" && "_prefault" in result.schema) (_a282 = result.schema).default ?? (_a282.default = result.schema._prefault); delete result.schema._prefault; const _result = ctx.seen.get(schema); return _result.schema; } function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; if (id) { const existing = idToSchema.get(id); if (existing && existing !== entry[0]) { throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); } idToSchema.set(id, entry[0]); } } const makeURI = (entry) => { const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; if (ctx.external) { const externalId = ctx.external.registry.get(entry[0])?.id; const uriGenerator = ctx.external.uri ?? ((id2) => id2); if (externalId) { return { ref: uriGenerator(externalId) }; } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } if (entry[1] === root) { return { ref: "#" }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; return { defId, ref: defUriPrefix + defId }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { return; } const seen = entry[1]; const { ref, defId } = makeURI(entry); seen.def = { ...seen.schema }; if (defId) seen.defId = defId; const schema2 = seen.schema; for (const key in schema2) { delete schema2[key]; } schema2.$ref = ref; }; if (ctx.cycles === "throw") { for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (seen.cycle) { throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); } } } for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (schema === entry[0]) { extractToDef(entry); continue; } if (ctx.external) { const ext = ctx.external.registry.get(entry[0])?.id; if (schema !== entry[0] && ext) { extractToDef(entry); continue; } } const id = ctx.metadataRegistry.get(entry[0])?.id; if (id) { extractToDef(entry); continue; } if (seen.cycle) { extractToDef(entry); continue; } if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); continue; } } } } function finalize(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const flattenRef = (zodSchema42) => { const seen = ctx.seen.get(zodSchema42); if (seen.ref === null) return; const schema2 = seen.def ?? seen.schema; const _cached = { ...schema2 }; const ref = seen.ref; seen.ref = null; if (ref) { flattenRef(ref); const refSeen = ctx.seen.get(ref); const refSchema = refSeen.schema; if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { Object.assign(schema2, refSchema); } Object.assign(schema2, _cached); const isParentRef = zodSchema42._zod.parent === ref; if (isParentRef) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (!(key in _cached)) { delete schema2[key]; } } } if (refSchema.$ref && refSeen.def) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { delete schema2[key]; } } } } const parent = zodSchema42._zod.parent; if (parent && parent !== ref) { flattenRef(parent); const parentSeen = ctx.seen.get(parent); if (parentSeen?.schema.$ref) { schema2.$ref = parentSeen.schema.$ref; if (parentSeen.def) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { delete schema2[key]; } } } } } ctx.override({ zodSchema: zodSchema42, jsonSchema: schema2, path: seen.path ?? [] }); }; for (const entry of [...ctx.seen.entries()].reverse()) { flattenRef(entry[0]); } const result = {}; if (ctx.target === "draft-2020-12") { result.$schema = "https://json-schema.org/draft/2020-12/schema"; } else if (ctx.target === "draft-07") { result.$schema = "http://json-schema.org/draft-07/schema#"; } else if (ctx.target === "draft-04") { result.$schema = "http://json-schema.org/draft-04/schema#"; } else ; if (ctx.external?.uri) { const id = ctx.external.registry.get(schema)?.id; if (!id) throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } Object.assign(result, root.def ?? root.schema); const rootMetaId = ctx.metadataRegistry.get(schema)?.id; if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; const defs = ctx.external?.defs ?? {}; for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (seen.def && seen.defId) { if (seen.def.id === seen.defId) delete seen.def.id; defs[seen.defId] = seen.def; } } if (ctx.external) ; else { if (Object.keys(defs).length > 0) { if (ctx.target === "draft-2020-12") { result.$defs = defs; } else { result.definitions = defs; } } } try { const finalized = JSON.parse(JSON.stringify(result)); Object.defineProperty(finalized, "~standard", { value: { ...schema["~standard"], jsonSchema: { input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) } }, enumerable: false, writable: false }); return finalized; } catch (_err) { throw new Error("Error converting schema to JSON."); } } function isTransforming(_schema, _ctx) { const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; if (ctx.seen.has(_schema)) return false; ctx.seen.add(_schema); const def = _schema._zod.def; if (def.type === "transform") return true; if (def.type === "array") return isTransforming(def.element, ctx); if (def.type === "set") return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); } if (def.type === "record" || def.type === "map") { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } if (def.type === "pipe") { if (_schema._zod.traits.has("$ZodCodec")) return true; return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); } if (def.type === "object") { for (const key in def.shape) { if (isTransforming(def.shape[key], ctx)) return true; } return false; } if (def.type === "union") { for (const option of def.options) { if (isTransforming(option, ctx)) return true; } return false; } if (def.type === "tuple") { for (const item of def.items) { if (isTransforming(item, ctx)) return true; } if (def.rest && isTransforming(def.rest, ctx)) return true; return false; } return false; } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); process2(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); process2(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var formatMap = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" // do not set }; var stringProcessor = (schema, ctx, _json, _params) => { const json4 = _json; json4.type = "string"; const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; if (typeof minimum === "number") json4.minLength = minimum; if (typeof maximum === "number") json4.maxLength = maximum; if (format) { json4.format = formatMap[format] ?? format; if (json4.format === "") delete json4.format; if (format === "time") { delete json4.format; } } if (contentEncoding) json4.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { const regexes = [...patterns]; if (regexes.length === 1) json4.pattern = regexes[0].source; else if (regexes.length > 1) { json4.allOf = [ ...regexes.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) ]; } } }; var numberProcessor = (schema, ctx, _json, _params) => { const json4 = _json; const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; if (typeof format === "string" && format.includes("int")) json4.type = "integer"; else json4.type = "number"; const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; if (exMin) { if (legacy) { json4.minimum = exclusiveMinimum; json4.exclusiveMinimum = true; } else { json4.exclusiveMinimum = exclusiveMinimum; } } else if (typeof minimum === "number") { json4.minimum = minimum; } if (exMax) { if (legacy) { json4.maximum = exclusiveMaximum; json4.exclusiveMaximum = true; } else { json4.exclusiveMaximum = exclusiveMaximum; } } else if (typeof maximum === "number") { json4.maximum = maximum; } if (typeof multipleOf === "number") json4.multipleOf = multipleOf; }; var booleanProcessor = (_schema, _ctx, json4, _params) => { json4.type = "boolean"; }; var bigintProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("BigInt cannot be represented in JSON Schema"); } }; var symbolProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Symbols cannot be represented in JSON Schema"); } }; var nullProcessor = (_schema, ctx, json4, _params) => { if (ctx.target === "openapi-3.0") { json4.type = "string"; json4.nullable = true; json4.enum = [null]; } else { json4.type = "null"; } }; var undefinedProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Undefined cannot be represented in JSON Schema"); } }; var voidProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Void cannot be represented in JSON Schema"); } }; var neverProcessor = (_schema, _ctx, json4, _params) => { json4.not = {}; }; var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; var dateProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Date cannot be represented in JSON Schema"); } }; var enumProcessor = (schema, _ctx, json4, _params) => { const def = schema._zod.def; const values = getEnumValues(def.entries); if (values.every((v) => typeof v === "number")) json4.type = "number"; if (values.every((v) => typeof v === "string")) json4.type = "string"; json4.enum = values; }; var literalProcessor = (schema, ctx, json4, _params) => { const def = schema._zod.def; const vals = []; for (const val of def.values) { if (val === void 0) { if (ctx.unrepresentable === "throw") { throw new Error("Literal `undefined` cannot be represented in JSON Schema"); } } else if (typeof val === "bigint") { if (ctx.unrepresentable === "throw") { throw new Error("BigInt literals cannot be represented in JSON Schema"); } else { vals.push(Number(val)); } } else { vals.push(val); } } if (vals.length === 0) ; else if (vals.length === 1) { const val = vals[0]; json4.type = val === null ? "null" : typeof val; if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { json4.enum = [val]; } else { json4.const = val; } } else { if (vals.every((v) => typeof v === "number")) json4.type = "number"; if (vals.every((v) => typeof v === "string")) json4.type = "string"; if (vals.every((v) => typeof v === "boolean")) json4.type = "boolean"; if (vals.every((v) => v === null)) json4.type = "null"; json4.enum = vals; } }; var nanProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("NaN cannot be represented in JSON Schema"); } }; var templateLiteralProcessor = (schema, _ctx, json4, _params) => { const _json = json4; const pattern = schema._zod.pattern; if (!pattern) throw new Error("Pattern not found in template literal"); _json.type = "string"; _json.pattern = pattern.source; }; var fileProcessor = (schema, _ctx, json4, _params) => { const _json = json4; const file3 = { type: "string", format: "binary", contentEncoding: "binary" }; const { minimum, maximum, mime } = schema._zod.bag; if (minimum !== void 0) file3.minLength = minimum; if (maximum !== void 0) file3.maxLength = maximum; if (mime) { if (mime.length === 1) { file3.contentMediaType = mime[0]; Object.assign(_json, file3); } else { Object.assign(_json, file3); _json.anyOf = mime.map((m) => ({ contentMediaType: m })); } } else { Object.assign(_json, file3); } }; var successProcessor = (_schema, _ctx, json4, _params) => { json4.type = "boolean"; }; var customProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Custom types cannot be represented in JSON Schema"); } }; var functionProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Function types cannot be represented in JSON Schema"); } }; var transformProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Transforms cannot be represented in JSON Schema"); } }; var mapProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Map cannot be represented in JSON Schema"); } }; var setProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Set cannot be represented in JSON Schema"); } }; var arrayProcessor = (schema, ctx, _json, params) => { const json4 = _json; const def = schema._zod.def; const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json4.minItems = minimum; if (typeof maximum === "number") json4.maxItems = maximum; json4.type = "array"; json4.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; var objectProcessor = (schema, ctx, _json, params) => { const json4 = _json; const def = schema._zod.def; json4.type = "object"; json4.properties = {}; const shape = def.shape; for (const key in shape) { json4.properties[key] = process2(shape[key], ctx, { ...params, path: [...params.path, "properties", key] }); } const allKeys = new Set(Object.keys(shape)); const requiredKeys = new Set([...allKeys].filter((key) => { const v = def.shape[key]._zod; if (ctx.io === "input") { return v.optin === void 0; } else { return v.optout === void 0; } })); if (requiredKeys.size > 0) { json4.required = Array.from(requiredKeys); } if (def.catchall?._zod.def.type === "never") { json4.additionalProperties = false; } else if (!def.catchall) { if (ctx.io === "output") json4.additionalProperties = false; } else if (def.catchall) { json4.additionalProperties = process2(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } }; var unionProcessor = (schema, ctx, json4, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; const options = def.options.map((x, i) => process2(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); if (isExclusive) { json4.oneOf = options; } else { json4.anyOf = options; } }; var intersectionProcessor = (schema, ctx, json4, params) => { const def = schema._zod.def; const a = process2(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); const b = process2(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; const allOf = [ ...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b] ]; json4.allOf = allOf; }; var tupleProcessor = (schema, ctx, _json, params) => { const json4 = _json; const def = schema._zod.def; json4.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; const prefixItems = def.items.map((x, i) => process2(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); const rest = def.rest ? process2(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; if (ctx.target === "draft-2020-12") { json4.prefixItems = prefixItems; if (rest) { json4.items = rest; } } else if (ctx.target === "openapi-3.0") { json4.items = { anyOf: prefixItems }; if (rest) { json4.items.anyOf.push(rest); } json4.minItems = prefixItems.length; if (!rest) { json4.maxItems = prefixItems.length; } } else { json4.items = prefixItems; if (rest) { json4.additionalItems = rest; } } const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json4.minItems = minimum; if (typeof maximum === "number") json4.maxItems = maximum; }; var recordProcessor = (schema, ctx, _json, params) => { const json4 = _json; const def = schema._zod.def; json4.type = "object"; const keyType = def.keyType; const keyBag = keyType._zod.bag; const patterns = keyBag?.patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { const valueSchema = process2(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json4.patternProperties = {}; for (const pattern of patterns) { json4.patternProperties[pattern.source] = valueSchema; } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { json4.propertyNames = process2(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); } json4.additionalProperties = process2(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; if (keyValues) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { json4.required = validKeyValues; } } }; var nullableProcessor = (schema, ctx, json4, params) => { const def = schema._zod.def; const inner = process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; json4.nullable = true; } else { json4.anyOf = [inner, { type: "null" }]; } }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var defaultProcessor = (schema, ctx, json4, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json4.default = JSON.parse(JSON.stringify(def.defaultValue)); }; var prefaultProcessor = (schema, ctx, json4, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; if (ctx.io === "input") json4._prefault = JSON.parse(JSON.stringify(def.defaultValue)); }; var catchProcessor = (schema, ctx, json4, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { throw new Error("Dynamic catch values are not supported in JSON Schema"); } json4.default = catchValue; }; var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const inIsTransform = def.in._zod.traits.has("$ZodTransform"); const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; process2(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json4, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json4.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; process2(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var allProcessors = { string: stringProcessor, number: numberProcessor, boolean: booleanProcessor, bigint: bigintProcessor, symbol: symbolProcessor, null: nullProcessor, undefined: undefinedProcessor, void: voidProcessor, never: neverProcessor, any: anyProcessor, unknown: unknownProcessor, date: dateProcessor, enum: enumProcessor, literal: literalProcessor, nan: nanProcessor, template_literal: templateLiteralProcessor, file: fileProcessor, success: successProcessor, custom: customProcessor, function: functionProcessor, transform: transformProcessor, map: mapProcessor, set: setProcessor, array: arrayProcessor, object: objectProcessor, union: unionProcessor, intersection: intersectionProcessor, tuple: tupleProcessor, record: recordProcessor, nullable: nullableProcessor, nonoptional: nonoptionalProcessor, default: defaultProcessor, prefault: prefaultProcessor, catch: catchProcessor, pipe: pipeProcessor, readonly: readonlyProcessor, promise: promiseProcessor, optional: optionalProcessor, lazy: lazyProcessor }; function toJSONSchema(input, params) { if ("_idmap" in input) { const registry3 = input; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry3._idmap.entries()) { const [_, schema] = entry; process2(schema, ctx2); } const schemas = {}; const external = { registry: registry3, uri: params?.uri, defs }; ctx2.external = external; for (const entry of registry3._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); schemas[key] = finalize(ctx2, schema); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; schemas.__shared = { [defsSegment]: defs }; } return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); process2(input, ctx); extractDefs(ctx, input); return finalize(ctx, input); } var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { return this.ctx.metadataRegistry; } /** @deprecated Access via ctx instead */ get target() { return this.ctx.target; } /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; } /** @deprecated Access via ctx instead */ get override() { return this.ctx.override; } /** @deprecated Access via ctx instead */ get io() { return this.ctx.io; } /** @deprecated Access via ctx instead */ get counter() { return this.ctx.counter; } set counter(value) { this.ctx.counter = value; } /** @deprecated Access via ctx instead */ get seen() { return this.ctx.seen; } constructor(params) { let normalizedTarget = params?.target ?? "draft-2020-12"; if (normalizedTarget === "draft-4") normalizedTarget = "draft-04"; if (normalizedTarget === "draft-7") normalizedTarget = "draft-07"; this.ctx = initializeContext({ processors: allProcessors, target: normalizedTarget, ...params?.metadata && { metadata: params.metadata }, ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, ...params?.override && { override: params.override }, ...params?.io && { io: params.io } }); } /** * Process a schema to prepare it for JSON Schema generation. * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { return process2(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. * Must call process() first. */ emit(schema, _params) { if (_params) { if (_params.cycles) this.ctx.cycles = _params.cycles; if (_params.reused) this.ctx.reused = _params.reused; if (_params.external) this.ctx.external = _params.external; } extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; return plainResult; } }; var json_schema_exports = {}; var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny2, ZodArray: () => ZodArray2, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt2, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean2, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch2, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate2, ZodDefault: () => ZodDefault2, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum2, ZodExactOptional: () => ZodExactOptional, ZodFile: () => ZodFile, ZodFunction: () => ZodFunction2, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodIntersection: () => ZodIntersection2, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy2, ZodLiteral: () => ZodLiteral2, ZodMAC: () => ZodMAC, ZodMap: () => ZodMap2, ZodNaN: () => ZodNaN2, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever2, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull2, ZodNullable: () => ZodNullable2, ZodNumber: () => ZodNumber2, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject2, ZodOptional: () => ZodOptional2, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPreprocess: () => ZodPreprocess, ZodPromise: () => ZodPromise2, ZodReadonly: () => ZodReadonly2, ZodRecord: () => ZodRecord2, ZodSet: () => ZodSet2, ZodString: () => ZodString2, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol2, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple2, ZodType: () => ZodType2, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined2, ZodUnion: () => ZodUnion2, ZodUnknown: () => ZodUnknown2, ZodVoid: () => ZodVoid2, ZodXID: () => ZodXID, ZodXor: () => ZodXor, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom2, date: () => date3, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, enum: () => _enum2, exactOptional: () => exactOptional, file: () => file, float32: () => float32, float64: () => float64, function: () => _function, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, invertCodec: () => invertCodec, ipv4: () => ipv42, ipv6: () => ipv62, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, literal: () => literal, looseObject: () => looseObject, looseRecord: () => looseRecord, mac: () => mac2, map: () => map, meta: () => meta2, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, never: () => never, nonoptional: () => nonoptional, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object2, optional: () => optional, partialRecord: () => partialRecord, pipe: () => pipe, prefault: () => prefault, preprocess: () => preprocess, promise: () => promise, readonly: () => readonly, record: () => record, refine: () => refine, set: () => set, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol17, templateLiteral: () => templateLiteral, transform: () => transform, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, url: () => url, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2, xor: () => xor }); var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, gt: () => _gt, gte: () => _gte, includes: () => _includes, length: () => _length, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, maxLength: () => _maxLength, maxSize: () => _maxSize, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, negative: () => _negative, nonnegative: () => _nonnegative, nonpositive: () => _nonpositive, normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, property: () => _property, regex: () => _regex, size: () => _size, slugify: () => _slugify, startsWith: () => _startsWith, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, trim: () => _trim, uppercase: () => _uppercase }); var iso_exports = {}; __export(iso_exports, { ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, date: () => date2, datetime: () => datetime2, duration: () => duration2, time: () => time2 }); var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { $ZodISODateTime.init(inst, def); ZodStringFormat.init(inst, def); }); function datetime2(params) { return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params); } var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { $ZodISODate.init(inst, def); ZodStringFormat.init(inst, def); }); function date2(params) { return /* @__PURE__ */ _isoDate(ZodISODate, params); } var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { $ZodISOTime.init(inst, def); ZodStringFormat.init(inst, def); }); function time2(params) { return /* @__PURE__ */ _isoTime(ZodISOTime, params); } var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { $ZodISODuration.init(inst, def); ZodStringFormat.init(inst, def); }); function duration2(params) { return /* @__PURE__ */ _isoDuration(ZodISODuration, params); } var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError(inst, mapper) // enumerable: false, }, flatten: { value: (mapper) => flattenError(inst, mapper) // enumerable: false, }, addIssue: { value: (issue3) => { inst.issues.push(issue3); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, addIssues: { value: (issues2) => { inst.issues.push(...issues2); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; } // enumerable: false, } }); }; var ZodError2 = /* @__PURE__ */ $constructor("ZodError", initializer2); var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { Parent: Error }); var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); var encode2 = /* @__PURE__ */ _encode(ZodRealError); var decode2 = /* @__PURE__ */ _decode(ZodRealError); var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); var _installedGroups = /* @__PURE__ */ new WeakMap(); function _installLazyMethods(inst, group, methods) { const proto = Object.getPrototypeOf(inst); let installed = _installedGroups.get(proto); if (!installed) { installed = /* @__PURE__ */ new Set(); _installedGroups.set(proto, installed); } if (installed.has(group)) return; installed.add(group); for (const key in methods) { const fn = methods[key]; Object.defineProperty(proto, key, { configurable: true, enumerable: false, get() { const bound = fn.bind(this); Object.defineProperty(this, key, { configurable: true, writable: true, enumerable: true, value: bound }); return bound; }, set(v) { Object.defineProperty(this, key, { configurable: true, writable: true, enumerable: true, value: v }); } }); } } var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); Object.assign(inst["~standard"], { jsonSchema: { input: createStandardJSONSchemaMethod(inst, "input"), output: createStandardJSONSchemaMethod(inst, "output") } }); inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; Object.defineProperty(inst, "_def", { value: def }); inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse2(inst, data, params); inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); inst.spa = inst.safeParseAsync; inst.encode = (data, params) => encode2(inst, data, params); inst.decode = (data, params) => decode2(inst, data, params); inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); inst.safeEncode = (data, params) => safeEncode2(inst, data, params); inst.safeDecode = (data, params) => safeDecode2(inst, data, params); inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); _installLazyMethods(inst, "ZodType", { check(...chks) { const def2 = this.def; return this.clone(util_exports.mergeDefs(def2, { checks: [ ...def2.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) ] }), { parent: true }); }, with(...chks) { return this.check(...chks); }, clone(def2, params) { return clone(this, def2, params); }, brand() { return this; }, register(reg, meta3) { reg.add(this, meta3); return this; }, refine(check3, params) { return this.check(refine(check3, params)); }, superRefine(refinement, params) { return this.check(superRefine(refinement, params)); }, overwrite(fn) { return this.check(/* @__PURE__ */ _overwrite(fn)); }, optional() { return optional(this); }, exactOptional() { return exactOptional(this); }, nullable() { return nullable(this); }, nullish() { return optional(nullable(this)); }, nonoptional(params) { return nonoptional(this, params); }, array() { return array(this); }, or(arg) { return union([this, arg]); }, and(arg) { return intersection(this, arg); }, transform(tx) { return pipe(this, transform(tx)); }, default(d) { return _default2(this, d); }, prefault(d) { return prefault(this, d); }, catch(params) { return _catch2(this, params); }, pipe(target) { return pipe(this, target); }, readonly() { return readonly(this); }, describe(description) { const cl = this.clone(); globalRegistry.add(cl, { description }); return cl; }, meta(...args) { if (args.length === 0) return globalRegistry.get(this); const cl = this.clone(); globalRegistry.add(cl, args[0]); return cl; }, isOptional() { return this.safeParse(void 0).success; }, isNullable() { return this.safeParse(null).success; }, apply(fn) { return fn(this); } }); Object.defineProperty(inst, "description", { get() { return globalRegistry.get(inst)?.description; }, configurable: true }); return inst; }); var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { $ZodString.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => stringProcessor(inst, ctx, json4); const bag = inst._zod.bag; inst.format = bag.format ?? null; inst.minLength = bag.minimum ?? null; inst.maxLength = bag.maximum ?? null; _installLazyMethods(inst, "_ZodString", { regex(...args) { return this.check(/* @__PURE__ */ _regex(...args)); }, includes(...args) { return this.check(/* @__PURE__ */ _includes(...args)); }, startsWith(...args) { return this.check(/* @__PURE__ */ _startsWith(...args)); }, endsWith(...args) { return this.check(/* @__PURE__ */ _endsWith(...args)); }, min(...args) { return this.check(/* @__PURE__ */ _minLength(...args)); }, max(...args) { return this.check(/* @__PURE__ */ _maxLength(...args)); }, length(...args) { return this.check(/* @__PURE__ */ _length(...args)); }, nonempty(...args) { return this.check(/* @__PURE__ */ _minLength(1, ...args)); }, lowercase(params) { return this.check(/* @__PURE__ */ _lowercase(params)); }, uppercase(params) { return this.check(/* @__PURE__ */ _uppercase(params)); }, trim() { return this.check(/* @__PURE__ */ _trim()); }, normalize(...args) { return this.check(/* @__PURE__ */ _normalize(...args)); }, toLowerCase() { return this.check(/* @__PURE__ */ _toLowerCase()); }, toUpperCase() { return this.check(/* @__PURE__ */ _toUpperCase()); }, slugify() { return this.check(/* @__PURE__ */ _slugify()); } }); }); var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); inst.email = (params) => inst.check(/* @__PURE__ */ _email(ZodEmail, params)); inst.url = (params) => inst.check(/* @__PURE__ */ _url(ZodURL, params)); inst.jwt = (params) => inst.check(/* @__PURE__ */ _jwt(ZodJWT, params)); inst.emoji = (params) => inst.check(/* @__PURE__ */ _emoji2(ZodEmoji, params)); inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); inst.uuid = (params) => inst.check(/* @__PURE__ */ _uuid(ZodUUID, params)); inst.uuidv4 = (params) => inst.check(/* @__PURE__ */ _uuidv4(ZodUUID, params)); inst.uuidv6 = (params) => inst.check(/* @__PURE__ */ _uuidv6(ZodUUID, params)); inst.uuidv7 = (params) => inst.check(/* @__PURE__ */ _uuidv7(ZodUUID, params)); inst.nanoid = (params) => inst.check(/* @__PURE__ */ _nanoid(ZodNanoID, params)); inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); inst.cuid = (params) => inst.check(/* @__PURE__ */ _cuid(ZodCUID, params)); inst.cuid2 = (params) => inst.check(/* @__PURE__ */ _cuid2(ZodCUID2, params)); inst.ulid = (params) => inst.check(/* @__PURE__ */ _ulid(ZodULID, params)); inst.base64 = (params) => inst.check(/* @__PURE__ */ _base64(ZodBase64, params)); inst.base64url = (params) => inst.check(/* @__PURE__ */ _base64url(ZodBase64URL, params)); inst.xid = (params) => inst.check(/* @__PURE__ */ _xid(ZodXID, params)); inst.ksuid = (params) => inst.check(/* @__PURE__ */ _ksuid(ZodKSUID, params)); inst.ipv4 = (params) => inst.check(/* @__PURE__ */ _ipv4(ZodIPv4, params)); inst.ipv6 = (params) => inst.check(/* @__PURE__ */ _ipv6(ZodIPv6, params)); inst.cidrv4 = (params) => inst.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params)); inst.cidrv6 = (params) => inst.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params)); inst.e164 = (params) => inst.check(/* @__PURE__ */ _e164(ZodE164, params)); inst.datetime = (params) => inst.check(datetime2(params)); inst.date = (params) => inst.check(date2(params)); inst.time = (params) => inst.check(time2(params)); inst.duration = (params) => inst.check(duration2(params)); }); function string2(params) { return /* @__PURE__ */ _string(ZodString2, params); } var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); function email2(params) { return /* @__PURE__ */ _email(ZodEmail, params); } var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { $ZodGUID.init(inst, def); ZodStringFormat.init(inst, def); }); function guid2(params) { return /* @__PURE__ */ _guid(ZodGUID, params); } var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); function uuid2(params) { return /* @__PURE__ */ _uuid(ZodUUID, params); } function uuidv4(params) { return /* @__PURE__ */ _uuidv4(ZodUUID, params); } function uuidv6(params) { return /* @__PURE__ */ _uuidv6(ZodUUID, params); } function uuidv7(params) { return /* @__PURE__ */ _uuidv7(ZodUUID, params); } var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); function url(params) { return /* @__PURE__ */ _url(ZodURL, params); } function httpUrl(params) { return /* @__PURE__ */ _url(ZodURL, { protocol: regexes_exports.httpProtocol, hostname: regexes_exports.domain, ...util_exports.normalizeParams(params) }); } var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { $ZodEmoji.init(inst, def); ZodStringFormat.init(inst, def); }); function emoji2(params) { return /* @__PURE__ */ _emoji2(ZodEmoji, params); } var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { $ZodNanoID.init(inst, def); ZodStringFormat.init(inst, def); }); function nanoid2(params) { return /* @__PURE__ */ _nanoid(ZodNanoID, params); } var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { $ZodCUID.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid3(params) { return /* @__PURE__ */ _cuid(ZodCUID, params); } var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { $ZodCUID2.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid22(params) { return /* @__PURE__ */ _cuid2(ZodCUID2, params); } var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { $ZodULID.init(inst, def); ZodStringFormat.init(inst, def); }); function ulid2(params) { return /* @__PURE__ */ _ulid(ZodULID, params); } var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { $ZodXID.init(inst, def); ZodStringFormat.init(inst, def); }); function xid2(params) { return /* @__PURE__ */ _xid(ZodXID, params); } var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { $ZodKSUID.init(inst, def); ZodStringFormat.init(inst, def); }); function ksuid2(params) { return /* @__PURE__ */ _ksuid(ZodKSUID, params); } var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { $ZodIPv4.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv42(params) { return /* @__PURE__ */ _ipv4(ZodIPv4, params); } var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { $ZodMAC.init(inst, def); ZodStringFormat.init(inst, def); }); function mac2(params) { return /* @__PURE__ */ _mac(ZodMAC, params); } var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { $ZodIPv6.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv62(params) { return /* @__PURE__ */ _ipv6(ZodIPv6, params); } var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { $ZodCIDRv4.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv42(params) { return /* @__PURE__ */ _cidrv4(ZodCIDRv4, params); } var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { $ZodCIDRv6.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv62(params) { return /* @__PURE__ */ _cidrv6(ZodCIDRv6, params); } var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); function base642(params) { return /* @__PURE__ */ _base64(ZodBase64, params); } var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { $ZodBase64URL.init(inst, def); ZodStringFormat.init(inst, def); }); function base64url2(params) { return /* @__PURE__ */ _base64url(ZodBase64URL, params); } var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { $ZodE164.init(inst, def); ZodStringFormat.init(inst, def); }); function e1642(params) { return /* @__PURE__ */ _e164(ZodE164, params); } var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); }); function jwt(params) { return /* @__PURE__ */ _jwt(ZodJWT, params); } var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { $ZodCustomStringFormat.init(inst, def); ZodStringFormat.init(inst, def); }); function stringFormat(format, fnOrRegex, _params = {}) { return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); } function hex2(_params) { return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; const format = `${alg}_${enc}`; const regex = regexes_exports[format]; if (!regex) throw new Error(`Unrecognized hash format: ${format}`); return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format, regex, params); } var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { $ZodNumber.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => numberProcessor(inst, ctx, json4); _installLazyMethods(inst, "ZodNumber", { gt(value, params) { return this.check(/* @__PURE__ */ _gt(value, params)); }, gte(value, params) { return this.check(/* @__PURE__ */ _gte(value, params)); }, min(value, params) { return this.check(/* @__PURE__ */ _gte(value, params)); }, lt(value, params) { return this.check(/* @__PURE__ */ _lt(value, params)); }, lte(value, params) { return this.check(/* @__PURE__ */ _lte(value, params)); }, max(value, params) { return this.check(/* @__PURE__ */ _lte(value, params)); }, int(params) { return this.check(int(params)); }, safe(params) { return this.check(int(params)); }, positive(params) { return this.check(/* @__PURE__ */ _gt(0, params)); }, nonnegative(params) { return this.check(/* @__PURE__ */ _gte(0, params)); }, negative(params) { return this.check(/* @__PURE__ */ _lt(0, params)); }, nonpositive(params) { return this.check(/* @__PURE__ */ _lte(0, params)); }, multipleOf(value, params) { return this.check(/* @__PURE__ */ _multipleOf(value, params)); }, step(value, params) { return this.check(/* @__PURE__ */ _multipleOf(value, params)); }, finite() { return this; } }); 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 number2(params) { return /* @__PURE__ */ _number(ZodNumber2, params); } var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); ZodNumber2.init(inst, def); }); function int(params) { return /* @__PURE__ */ _int(ZodNumberFormat, params); } function float32(params) { return /* @__PURE__ */ _float32(ZodNumberFormat, params); } function float64(params) { return /* @__PURE__ */ _float64(ZodNumberFormat, params); } function int32(params) { return /* @__PURE__ */ _int32(ZodNumberFormat, params); } function uint32(params) { return /* @__PURE__ */ _uint32(ZodNumberFormat, params); } var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => booleanProcessor(inst, ctx, json4); }); function boolean2(params) { return /* @__PURE__ */ _boolean(ZodBoolean2, params); } var ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { $ZodBigInt.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => bigintProcessor(inst, ctx); inst.gte = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params)); inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params)); inst.gt = (value, params) => inst.check(/* @__PURE__ */ _gt(value, params)); inst.gte = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params)); inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params)); inst.lt = (value, params) => inst.check(/* @__PURE__ */ _lt(value, params)); inst.lte = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params)); inst.max = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params)); inst.positive = (params) => inst.check(/* @__PURE__ */ _gt(BigInt(0), params)); inst.negative = (params) => inst.check(/* @__PURE__ */ _lt(BigInt(0), params)); inst.nonpositive = (params) => inst.check(/* @__PURE__ */ _lte(BigInt(0), params)); inst.nonnegative = (params) => inst.check(/* @__PURE__ */ _gte(BigInt(0), params)); inst.multipleOf = (value, params) => inst.check(/* @__PURE__ */ _multipleOf(value, params)); const bag = inst._zod.bag; inst.minValue = bag.minimum ?? null; inst.maxValue = bag.maximum ?? null; inst.format = bag.format ?? null; }); function bigint2(params) { return /* @__PURE__ */ _bigint(ZodBigInt2, params); } var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { $ZodBigIntFormat.init(inst, def); ZodBigInt2.init(inst, def); }); function int64(params) { return /* @__PURE__ */ _int64(ZodBigIntFormat, params); } function uint64(params) { return /* @__PURE__ */ _uint64(ZodBigIntFormat, params); } var ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { $ZodSymbol.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => symbolProcessor(inst, ctx); }); function symbol17(params) { return /* @__PURE__ */ _symbol(ZodSymbol2, params); } var ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { $ZodUndefined.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => undefinedProcessor(inst, ctx); }); function _undefined3(params) { return /* @__PURE__ */ _undefined2(ZodUndefined2, params); } var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => nullProcessor(inst, ctx, json4); }); function _null3(params) { return /* @__PURE__ */ _null2(ZodNull2, params); } var ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { $ZodAny.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => anyProcessor(); }); function any() { return /* @__PURE__ */ _any(ZodAny2); } var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => unknownProcessor(); }); function unknown() { return /* @__PURE__ */ _unknown(ZodUnknown2); } var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => neverProcessor(inst, ctx, json4); }); function never(params) { return /* @__PURE__ */ _never(ZodNever2, params); } var ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { $ZodVoid.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => voidProcessor(inst, ctx); }); function _void2(params) { return /* @__PURE__ */ _void(ZodVoid2, params); } var ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { $ZodDate.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => dateProcessor(inst, ctx); inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params)); inst.max = (value, params) => inst.check(/* @__PURE__ */ _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 date3(params) { return /* @__PURE__ */ _date(ZodDate2, params); } var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => arrayProcessor(inst, ctx, json4, params); inst.element = def.element; _installLazyMethods(inst, "ZodArray", { min(n, params) { return this.check(/* @__PURE__ */ _minLength(n, params)); }, nonempty(params) { return this.check(/* @__PURE__ */ _minLength(1, params)); }, max(n, params) { return this.check(/* @__PURE__ */ _maxLength(n, params)); }, length(n, params) { return this.check(/* @__PURE__ */ _length(n, params)); }, unwrap() { return this.element; } }); }); function array(element, params) { return /* @__PURE__ */ _array(ZodArray2, element, params); } function keyof(schema) { const shape = schema._zod.def.shape; return _enum2(Object.keys(shape)); } var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { $ZodObjectJIT.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => objectProcessor(inst, ctx, json4, params); util_exports.defineLazy(inst, "shape", () => { return def.shape; }); _installLazyMethods(inst, "ZodObject", { keyof() { return _enum2(Object.keys(this._zod.def.shape)); }, catchall(catchall) { return this.clone({ ...this._zod.def, catchall }); }, passthrough() { return this.clone({ ...this._zod.def, catchall: unknown() }); }, loose() { return this.clone({ ...this._zod.def, catchall: unknown() }); }, strict() { return this.clone({ ...this._zod.def, catchall: never() }); }, strip() { return this.clone({ ...this._zod.def, catchall: void 0 }); }, extend(incoming) { return util_exports.extend(this, incoming); }, safeExtend(incoming) { return util_exports.safeExtend(this, incoming); }, merge(other) { return util_exports.merge(this, other); }, pick(mask) { return util_exports.pick(this, mask); }, omit(mask) { return util_exports.omit(this, mask); }, partial(...args) { return util_exports.partial(ZodOptional2, this, args[0]); }, required(...args) { return util_exports.required(ZodNonOptional, this, args[0]); } }); }); function object2(shape, params) { const def = { type: "object", shape: shape ?? {}, ...util_exports.normalizeParams(params) }; return new ZodObject2(def); } function strictObject(shape, params) { return new ZodObject2({ type: "object", shape, catchall: never(), ...util_exports.normalizeParams(params) }); } function looseObject(shape, params) { return new ZodObject2({ type: "object", shape, catchall: unknown(), ...util_exports.normalizeParams(params) }); } var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => unionProcessor(inst, ctx, json4, params); inst.options = def.options; }); function union(options, params) { return new ZodUnion2({ type: "union", options, ...util_exports.normalizeParams(params) }); } var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { ZodUnion2.init(inst, def); $ZodXor.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => unionProcessor(inst, ctx, json4, params); inst.options = def.options; }); function xor(options, params) { return new ZodXor({ type: "union", options, inclusive: false, ...util_exports.normalizeParams(params) }); } var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { ZodUnion2.init(inst, def); $ZodDiscriminatedUnion.init(inst, def); }); function discriminatedUnion(discriminator, options, params) { return new ZodDiscriminatedUnion2({ type: "union", options, discriminator, ...util_exports.normalizeParams(params) }); } var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => intersectionProcessor(inst, ctx, json4, params); }); function intersection(left, right) { return new ZodIntersection2({ type: "intersection", left, right }); } var ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { $ZodTuple.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => tupleProcessor(inst, ctx, json4, params); inst.rest = (rest) => inst.clone({ ...inst._zod.def, rest }); }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new ZodTuple2({ type: "tuple", items, rest, ...util_exports.normalizeParams(params) }); } var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => recordProcessor(inst, ctx, json4, params); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function record(keyType, valueType, params) { if (!valueType || !valueType._zod) { return new ZodRecord2({ type: "record", keyType: string2(), valueType: keyType, ...util_exports.normalizeParams(valueType) }); } return new ZodRecord2({ type: "record", keyType, valueType, ...util_exports.normalizeParams(params) }); } function partialRecord(keyType, valueType, params) { const k = clone(keyType); k._zod.values = void 0; return new ZodRecord2({ type: "record", keyType: k, valueType, ...util_exports.normalizeParams(params) }); } function looseRecord(keyType, valueType, params) { return new ZodRecord2({ type: "record", keyType, valueType, mode: "loose", ...util_exports.normalizeParams(params) }); } var ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { $ZodMap.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => mapProcessor(inst, ctx); inst.keyType = def.keyType; inst.valueType = def.valueType; inst.min = (...args) => inst.check(/* @__PURE__ */ _minSize(...args)); inst.nonempty = (params) => inst.check(/* @__PURE__ */ _minSize(1, params)); inst.max = (...args) => inst.check(/* @__PURE__ */ _maxSize(...args)); inst.size = (...args) => inst.check(/* @__PURE__ */ _size(...args)); }); function map(keyType, valueType, params) { return new ZodMap2({ type: "map", keyType, valueType, ...util_exports.normalizeParams(params) }); } var ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { $ZodSet.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => setProcessor(inst, ctx); inst.min = (...args) => inst.check(/* @__PURE__ */ _minSize(...args)); inst.nonempty = (params) => inst.check(/* @__PURE__ */ _minSize(1, params)); inst.max = (...args) => inst.check(/* @__PURE__ */ _maxSize(...args)); inst.size = (...args) => inst.check(/* @__PURE__ */ _size(...args)); }); function set(valueType, params) { return new ZodSet2({ type: "set", valueType, ...util_exports.normalizeParams(params) }); } var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => enumProcessor(inst, ctx, json4); 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 ZodEnum2({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; inst.exclude = (values, params) => { const newEntries = { ...def.entries }; for (const value of values) { if (keys.has(value)) { delete newEntries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum2({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; }); function _enum2(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new ZodEnum2({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } function nativeEnum(entries, params) { return new ZodEnum2({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => literalProcessor(inst, ctx, json4); 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 ZodLiteral2({ type: "literal", values: Array.isArray(value) ? value : [value], ...util_exports.normalizeParams(params) }); } var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { $ZodFile.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => fileProcessor(inst, ctx, json4); inst.min = (size, params) => inst.check(/* @__PURE__ */ _minSize(size, params)); inst.max = (size, params) => inst.check(/* @__PURE__ */ _maxSize(size, params)); inst.mime = (types, params) => inst.check(/* @__PURE__ */ _mime(Array.isArray(types) ? types : [types], params)); }); function file(params) { return /* @__PURE__ */ _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => transformProcessor(inst, ctx); inst._zod.parse = (payload, _ctx) => { if (_ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } payload.addIssue = (issue3) => { if (typeof issue3 === "string") { payload.issues.push(util_exports.issue(issue3, payload.value, def)); } else { const _issue = issue3; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; const output = def.transform(payload.value, payload); if (output instanceof Promise) { return output.then((output2) => { payload.value = output2; payload.fallback = true; return payload; }); } payload.value = output; payload.fallback = true; return payload; }; }); function transform(fn) { return new ZodTransform({ type: "transform", transform: fn }); } var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => optionalProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; }); function optional(innerType) { return new ZodOptional2({ type: "optional", innerType }); } var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { $ZodExactOptional.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => optionalProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; }); function exactOptional(innerType) { return new ZodExactOptional({ type: "optional", innerType }); } var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => nullableProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; }); function nullable(innerType) { return new ZodNullable2({ type: "nullable", innerType }); } function nullish2(innerType) { return optional(nullable(innerType)); } var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => defaultProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); function _default2(innerType, defaultValue) { return new ZodDefault2({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => prefaultProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; }); function prefault(innerType, defaultValue) { return new ZodPrefault({ type: "prefault", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => nonoptionalProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional(innerType, params) { return new ZodNonOptional({ type: "nonoptional", innerType, ...util_exports.normalizeParams(params) }); } var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { $ZodSuccess.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => successProcessor(inst, ctx, json4); inst.unwrap = () => inst._zod.def.innerType; }); function success(innerType) { return new ZodSuccess({ type: "success", innerType }); } var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => catchProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); function _catch2(innerType, catchValue) { return new ZodCatch2({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } var ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { $ZodNaN.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => nanProcessor(inst, ctx); }); function nan(params) { return /* @__PURE__ */ _nan(ZodNaN2, params); } var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => pipeProcessor(inst, ctx, json4, params); inst.in = def.in; inst.out = def.out; }); function pipe(in_, out) { return new ZodPipe({ type: "pipe", in: in_, out // ...util.normalizeParams(params), }); } var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { ZodPipe.init(inst, def); $ZodCodec.init(inst, def); }); function codec(in_, out, params) { return new ZodCodec({ type: "pipe", in: in_, out, transform: params.decode, reverseTransform: params.encode }); } function invertCodec(codec2) { const def = codec2._zod.def; return new ZodCodec({ type: "pipe", in: def.out, out: def.in, transform: def.reverseTransform, reverseTransform: def.transform }); } var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => { ZodPipe.init(inst, def); $ZodPreprocess.init(inst, def); }); var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => readonlyProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; }); function readonly(innerType) { return new ZodReadonly2({ type: "readonly", innerType }); } var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { $ZodTemplateLiteral.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => templateLiteralProcessor(inst, ctx, json4); }); function templateLiteral(parts, params) { return new ZodTemplateLiteral({ type: "template_literal", parts, ...util_exports.normalizeParams(params) }); } var ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { $ZodLazy.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => lazyProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.getter(); }); function lazy(getter) { return new ZodLazy2({ type: "lazy", getter }); } var ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { $ZodPromise.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => promiseProcessor(inst, ctx, json4, params); inst.unwrap = () => inst._zod.def.innerType; }); function promise(innerType) { return new ZodPromise2({ type: "promise", innerType }); } var ZodFunction2 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { $ZodFunction.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => functionProcessor(inst, ctx); }); function _function(params) { return new ZodFunction2({ type: "function", input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), output: params?.output ?? unknown() }); } var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => customProcessor(inst, ctx); }); function check(fn) { const ch = new $ZodCheck({ check: "custom" // ...util.normalizeParams(params), }); ch._zod.check = fn; return ch; } function custom2(fn, _params) { return /* @__PURE__ */ _custom(ZodCustom, fn ?? (() => true), _params); } function refine(fn, _params = {}) { return /* @__PURE__ */ _refine(ZodCustom, fn, _params); } function superRefine(fn, params) { return /* @__PURE__ */ _superRefine(fn, params); } var describe2 = describe; var meta2 = meta; function _instanceof(cls, params = {}) { const inst = new ZodCustom({ type: "custom", check: "custom", fn: (data) => data instanceof cls, abort: true, ...util_exports.normalizeParams(params) }); inst._zod.bag.Class = cls; inst._zod.check = (payload) => { if (!(payload.value instanceof cls)) { payload.issues.push({ code: "invalid_type", expected: cls.name, input: payload.value, inst, path: [...inst._zod.def.path ?? []] }); } }; return inst; } var stringbool = (...args) => /* @__PURE__ */ _stringbool({ Codec: ZodCodec, Boolean: ZodBoolean2, String: ZodString2 }, ...args); function json(params) { const jsonSchema42 = lazy(() => { return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema42), record(string2(), jsonSchema42)]); }); return jsonSchema42; } function preprocess(fn, schema) { return new ZodPreprocess({ type: "pipe", in: transform(fn), out: schema }); } var ZodIssueCode2 = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" }; function setErrorMap2(map3) { config({ customError: map3 }); } function getErrorMap2() { return config().customError; } var ZodFirstPartyTypeKind2; /* @__PURE__ */ (function(ZodFirstPartyTypeKind42) { })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); var z = { ...schemas_exports2, ...checks_exports2, iso: iso_exports }; var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ // Schema identification "$schema", "$ref", "$defs", "definitions", // Core schema keywords "$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor", // Type "type", "enum", "const", // Composition "anyOf", "oneOf", "allOf", "not", // Object "properties", "required", "additionalProperties", "patternProperties", "propertyNames", "minProperties", "maxProperties", // Array "items", "prefixItems", "additionalItems", "minItems", "maxItems", "uniqueItems", "contains", "minContains", "maxContains", // String "minLength", "maxLength", "pattern", "format", // Number "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", // Already handled metadata "description", "default", // Content "contentEncoding", "contentMediaType", "contentSchema", // Unsupported (error-throwing) "unevaluatedItems", "unevaluatedProperties", "if", "then", "else", "dependentSchemas", "dependentRequired", // OpenAPI "nullable", "readOnly" ]); function detectVersion(schema, defaultTarget) { const $schema = schema.$schema; if ($schema === "https://json-schema.org/draft/2020-12/schema") { return "draft-2020-12"; } if ($schema === "http://json-schema.org/draft-07/schema#") { return "draft-7"; } if ($schema === "http://json-schema.org/draft-04/schema#") { return "draft-4"; } return defaultTarget ?? "draft-2020-12"; } function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); } const path = ref.slice(1).split("/").filter(Boolean); if (path.length === 0) { return ctx.rootSchema; } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { const key = path[1]; if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } return ctx.defs[key]; } throw new Error(`Reference not found: ${ref}`); } function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { return z.never(); } throw new Error("not is not supported in Zod (except { not: {} } for never)"); } if (schema.unevaluatedItems !== void 0) { throw new Error("unevaluatedItems is not supported"); } if (schema.unevaluatedProperties !== void 0) { throw new Error("unevaluatedProperties is not supported"); } if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) { throw new Error("Conditional schemas (if/then/else) are not supported"); } if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) { throw new Error("dependentSchemas and dependentRequired are not supported"); } if (schema.$ref) { const refPath = schema.$ref; if (ctx.refs.has(refPath)) { return ctx.refs.get(refPath); } if (ctx.processing.has(refPath)) { return z.lazy(() => { if (!ctx.refs.has(refPath)) { throw new Error(`Circular reference not resolved: ${refPath}`); } return ctx.refs.get(refPath); }); } ctx.processing.add(refPath); const resolved = resolveRef(refPath, ctx); const zodSchema5 = convertSchema(resolved, ctx); ctx.refs.set(refPath, zodSchema5); ctx.processing.delete(refPath); return zodSchema5; } if (schema.enum !== void 0) { const enumValues = schema.enum; if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) { return z.null(); } if (enumValues.length === 0) { return z.never(); } if (enumValues.length === 1) { return z.literal(enumValues[0]); } if (enumValues.every((v) => typeof v === "string")) { return z.enum(enumValues); } const literalSchemas = enumValues.map((v) => z.literal(v)); if (literalSchemas.length < 2) { return literalSchemas[0]; } return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); } if (schema.const !== void 0) { return z.literal(schema.const); } const type = schema.type; if (Array.isArray(type)) { const typeSchemas = type.map((t) => { const typeSchema = { ...schema, type: t }; return convertBaseSchema(typeSchema, ctx); }); if (typeSchemas.length === 0) { return z.never(); } if (typeSchemas.length === 1) { return typeSchemas[0]; } return z.union(typeSchemas); } if (!type) { return z.any(); } let zodSchema42; switch (type) { case "string": { let stringSchema = z.string(); if (schema.format) { const format = schema.format; if (format === "email") { stringSchema = stringSchema.check(z.email()); } else if (format === "uri" || format === "uri-reference") { stringSchema = stringSchema.check(z.url()); } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { stringSchema = stringSchema.check(z.iso.datetime()); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { stringSchema = stringSchema.check(z.iso.time()); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { stringSchema = stringSchema.check(z.ipv6()); } else if (format === "mac") { stringSchema = stringSchema.check(z.mac()); } else if (format === "cidr") { stringSchema = stringSchema.check(z.cidrv4()); } else if (format === "cidr-v6") { stringSchema = stringSchema.check(z.cidrv6()); } else if (format === "base64") { stringSchema = stringSchema.check(z.base64()); } else if (format === "base64url") { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { stringSchema = stringSchema.check(z.emoji()); } else if (format === "nanoid") { stringSchema = stringSchema.check(z.nanoid()); } else if (format === "cuid") { stringSchema = stringSchema.check(z.cuid()); } else if (format === "cuid2") { stringSchema = stringSchema.check(z.cuid2()); } else if (format === "ulid") { stringSchema = stringSchema.check(z.ulid()); } else if (format === "xid") { stringSchema = stringSchema.check(z.xid()); } else if (format === "ksuid") { stringSchema = stringSchema.check(z.ksuid()); } } if (typeof schema.minLength === "number") { stringSchema = stringSchema.min(schema.minLength); } if (typeof schema.maxLength === "number") { stringSchema = stringSchema.max(schema.maxLength); } if (schema.pattern) { stringSchema = stringSchema.regex(new RegExp(schema.pattern)); } zodSchema42 = stringSchema; break; } case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); if (typeof schema.minimum === "number") { numberSchema = numberSchema.min(schema.minimum); } if (typeof schema.maximum === "number") { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { numberSchema = numberSchema.gt(schema.exclusiveMinimum); } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { numberSchema = numberSchema.gt(schema.minimum); } if (typeof schema.exclusiveMaximum === "number") { numberSchema = numberSchema.lt(schema.exclusiveMaximum); } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { numberSchema = numberSchema.lt(schema.maximum); } if (typeof schema.multipleOf === "number") { numberSchema = numberSchema.multipleOf(schema.multipleOf); } zodSchema42 = numberSchema; break; } case "boolean": { zodSchema42 = z.boolean(); break; } case "null": { zodSchema42 = z.null(); break; } case "object": { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); } if (schema.propertyNames) { const keySchema = convertSchema(schema.propertyNames, ctx); const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); if (Object.keys(shape).length === 0) { zodSchema42 = z.record(keySchema, valueSchema); break; } const objectSchema2 = z.object(shape).passthrough(); const recordSchema = z.looseRecord(keySchema, valueSchema); zodSchema42 = z.intersection(objectSchema2, recordSchema); break; } if (schema.patternProperties) { const patternProps = schema.patternProperties; const patternKeys = Object.keys(patternProps); const looseRecords = []; for (const pattern of patternKeys) { const patternValue = convertSchema(patternProps[pattern], ctx); const keySchema = z.string().regex(new RegExp(pattern)); looseRecords.push(z.looseRecord(keySchema, patternValue)); } const schemasToIntersect = []; if (Object.keys(shape).length > 0) { schemasToIntersect.push(z.object(shape).passthrough()); } schemasToIntersect.push(...looseRecords); if (schemasToIntersect.length === 0) { zodSchema42 = z.object({}).passthrough(); } else if (schemasToIntersect.length === 1) { zodSchema42 = schemasToIntersect[0]; } else { let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]); for (let i = 2; i < schemasToIntersect.length; i++) { result = z.intersection(result, schemasToIntersect[i]); } zodSchema42 = result; } break; } const objectSchema = z.object(shape); if (schema.additionalProperties === false) { zodSchema42 = objectSchema.strict(); } else if (typeof schema.additionalProperties === "object") { zodSchema42 = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); } else { zodSchema42 = objectSchema.passthrough(); } break; } case "array": { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; if (rest) { zodSchema42 = z.tuple(tupleItems).rest(rest); } else { zodSchema42 = z.tuple(tupleItems); } if (typeof schema.minItems === "number") { zodSchema42 = zodSchema42.check(z.minLength(schema.minItems)); } if (typeof schema.maxItems === "number") { zodSchema42 = zodSchema42.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { const tupleItems = items.map((item) => convertSchema(item, ctx)); const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; if (rest) { zodSchema42 = z.tuple(tupleItems).rest(rest); } else { zodSchema42 = z.tuple(tupleItems); } if (typeof schema.minItems === "number") { zodSchema42 = zodSchema42.check(z.minLength(schema.minItems)); } if (typeof schema.maxItems === "number") { zodSchema42 = zodSchema42.check(z.maxLength(schema.maxItems)); } } else if (items !== void 0) { const element = convertSchema(items, ctx); let arraySchema = z.array(element); if (typeof schema.minItems === "number") { arraySchema = arraySchema.min(schema.minItems); } if (typeof schema.maxItems === "number") { arraySchema = arraySchema.max(schema.maxItems); } zodSchema42 = arraySchema; } else { zodSchema42 = z.array(z.any()); } break; } default: throw new Error(`Unsupported type: ${type}`); } return zodSchema42; } function convertSchema(schema, ctx) { if (typeof schema === "boolean") { return schema ? z.any() : z.never(); } let baseSchema = convertBaseSchema(schema, ctx); const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0; if (schema.anyOf && Array.isArray(schema.anyOf)) { const options = schema.anyOf.map((s) => convertSchema(s, ctx)); const anyOfUnion = z.union(options); baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion; } if (schema.oneOf && Array.isArray(schema.oneOf)) { const options = schema.oneOf.map((s) => convertSchema(s, ctx)); const oneOfUnion = z.xor(options); baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion; } if (schema.allOf && Array.isArray(schema.allOf)) { if (schema.allOf.length === 0) { baseSchema = hasExplicitType ? baseSchema : z.any(); } else { let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); const startIdx = hasExplicitType ? 0 : 1; for (let i = startIdx; i < schema.allOf.length; i++) { result = z.intersection(result, convertSchema(schema.allOf[i], ctx)); } baseSchema = result; } } if (schema.nullable === true && ctx.version === "openapi-3.0") { baseSchema = z.nullable(baseSchema); } if (schema.readOnly === true) { baseSchema = z.readonly(baseSchema); } if (schema.default !== void 0) { baseSchema = baseSchema.default(schema.default); } const extraMeta = {}; const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; for (const key of coreMetadataKeys) { if (key in schema) { extraMeta[key] = schema[key]; } } const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; for (const key of contentMetadataKeys) { if (key in schema) { extraMeta[key] = schema[key]; } } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { extraMeta[key] = schema[key]; } } if (Object.keys(extraMeta).length > 0) { ctx.registry.add(baseSchema, extraMeta); } if (schema.description) { baseSchema = baseSchema.describe(schema.description); } return baseSchema; } function fromJSONSchema(schema, params) { if (typeof schema === "boolean") { return schema ? z.any() : z.never(); } let normalized; try { normalized = JSON.parse(JSON.stringify(schema)); } catch { throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas"); } const version3 = detectVersion(normalized, params?.defaultTarget); const defs = normalized.$defs || normalized.definitions || {}; const ctx = { version: version3, defs, refs: /* @__PURE__ */ new Map(), processing: /* @__PURE__ */ new Set(), rootSchema: normalized, registry: params?.registry ?? globalRegistry }; return convertSchema(normalized, ctx); } var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, boolean: () => boolean3, date: () => date4, number: () => number3, string: () => string3 }); function string3(params) { return /* @__PURE__ */ _coercedString(ZodString2, params); } function number3(params) { return /* @__PURE__ */ _coercedNumber(ZodNumber2, params); } function boolean3(params) { return /* @__PURE__ */ _coercedBoolean(ZodBoolean2, params); } function bigint3(params) { return /* @__PURE__ */ _coercedBigint(ZodBigInt2, params); } function date4(params) { return /* @__PURE__ */ _coercedDate(ZodDate2, params); } config(en_default2()); var util2; (function(util3) { util3.assertEqual = (_) => { }; function assertIs3(_arg) { } util3.assertIs = assertIs3; function assertNever3(_x) { throw new Error(); } util3.assertNever = assertNever3; util3.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util3.getValidEnumValues = (obj) => { const validKeys = util3.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util3.objectValues(filtered); }; util3.objectValues = (obj) => { return util3.objectKeys(obj).map(function(e2) { return obj[e2]; }); }; util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object62) => { const keys = []; for (const key in object62) { if (Object.prototype.hasOwnProperty.call(object62, key)) { keys.push(key); } } return keys; }; util3.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues3(array4, separator = " | ") { return array4.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util3.joinValues = joinValues3; util3.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util2 || (util2 = {})); var objectUtil2; (function(objectUtil3) { objectUtil3.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil2 || (objectUtil2 = {})); util2.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); util2.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" ]); var ZodError3 = class _ZodError2 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) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue3) { return issue3.message; }; const fieldErrors = { _errors: [] }; const processError = (error90) => { for (const issue3 of error90.issues) { if (issue3.code === "invalid_union") { issue3.unionErrors.map(processError); } else if (issue3.code === "invalid_return_type") { processError(issue3.returnTypeError); } else if (issue3.code === "invalid_arguments") { processError(issue3.argumentsError); } else if (issue3.path.length === 0) { fieldErrors._errors.push(mapper(issue3)); } else { let curr = fieldErrors; let i = 0; while (i < issue3.path.length) { const el = issue3.path[i]; const terminal = i === issue3.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue3)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError2)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue3) => issue3.message) { const fieldErrors = /* @__PURE__ */ Object.create(null); 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(); } }; ZodError3.create = (issues) => { const error90 = new ZodError3(issues); return error90; }; var errorUtil2; (function(errorUtil3) { errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil2 || (errorUtil2 = {})); var ZodFirstPartyTypeKind3; (function(ZodFirstPartyTypeKind42) { ZodFirstPartyTypeKind42["ZodString"] = "ZodString"; ZodFirstPartyTypeKind42["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind42["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind42["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind42["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind42["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind42["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind42["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind42["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind42["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind42["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind42["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind42["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind42["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind42["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind42["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind42["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind42["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind42["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind42["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind42["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind42["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind42["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind42["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind42["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind42["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind42["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind42["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind42["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind42["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind42["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind42["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind42["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind42["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind42["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind42["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind3 || (ZodFirstPartyTypeKind3 = {})); var marker17 = "vercel.ai.error"; var symbol18 = Symbol.for(marker17); var _a19; var _b; var AISDKError2 = class _AISDKError3 extends (_b = Error, _a19 = symbol18, _b) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name1422, message, cause }) { super(message); this[_a19] = true; this.name = name1422; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error90) { return _AISDKError3.hasMarker(error90, marker17); } static hasMarker(error90, marker1522) { const markerSymbol = Symbol.for(marker1522); return error90 != null && typeof error90 === "object" && markerSymbol in error90 && typeof error90[markerSymbol] === "boolean" && error90[markerSymbol] === true; } }; var name17 = "AI_APICallError"; var marker23 = `vercel.ai.error.${name17}`; var symbol23 = Symbol.for(marker23); var _a23; var _b2; var APICallError2 = class extends (_b2 = AISDKError2, _a23 = symbol23, _b2) { constructor({ message, url: url3, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name: name17, message, cause }); this[_a23] = true; this.url = url3; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker23); } }; var name23 = "AI_EmptyResponseBodyError"; var marker33 = `vercel.ai.error.${name23}`; var symbol33 = Symbol.for(marker33); var _a33; var _b3; var EmptyResponseBodyError = class extends (_b3 = AISDKError2, _a33 = symbol33, _b3) { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name23, message }); this[_a33] = true; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker33); } }; function getErrorMessage3(error90) { if (error90 == null) { return "unknown error"; } if (typeof error90 === "string") { return error90; } if (error90 instanceof Error) { return error90.message; } return JSON.stringify(error90); } var name33 = "AI_InvalidArgumentError"; var marker43 = `vercel.ai.error.${name33}`; var symbol43 = Symbol.for(marker43); var _a43; var _b4; var InvalidArgumentError3 = class extends (_b4 = AISDKError2, _a43 = symbol43, _b4) { constructor({ message, cause, argument }) { super({ name: name33, message, cause }); this[_a43] = true; this.argument = argument; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker43); } }; var name63 = "AI_JSONParseError"; var marker73 = `vercel.ai.error.${name63}`; var symbol73 = Symbol.for(marker73); var _a73; var _b7; var JSONParseError2 = class extends (_b7 = AISDKError2, _a73 = symbol73, _b7) { constructor({ text: text42, cause }) { super({ name: name63, message: `JSON parsing failed: Text: ${text42}. Error message: ${getErrorMessage3(cause)}`, cause }); this[_a73] = true; this.text = text42; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker73); } }; var name123 = "AI_TypeValidationError"; var marker133 = `vercel.ai.error.${name123}`; var symbol133 = Symbol.for(marker133); var _a133; var _b13; var TypeValidationError2 = class _TypeValidationError3 extends (_b13 = AISDKError2, _a133 = symbol133, _b13) { constructor({ value, cause }) { super({ name: name123, message: `Type validation failed: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage3(cause)}`, cause }); this[_a133] = true; this.value = value; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker133); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause }) { return _TypeValidationError3.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError3({ value, cause }); } }; var ParseError = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; var LF = 10; var CR = 13; var SPACE = 32; function noop(_arg) { } function createParser(callbacks) { if (typeof callbacks == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = []; let isFirstChunk = true, id, data = "", dataLines = 0, eventType; function feed(chunk) { if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) { const trailing2 = processLines(chunk); trailing2 !== "" && pendingFragments.push(trailing2); return; } if (chunk.indexOf(` `) === -1 && chunk.indexOf("\r") === -1) { pendingFragments.push(chunk); return; } pendingFragments.push(chunk); const input = pendingFragments.join(""); pendingFragments.length = 0; const trailing = processLines(input); trailing !== "" && pendingFragments.push(trailing); } function processLines(chunk) { let searchIndex = 0; if (chunk.indexOf("\r") === -1) { let lfIndex = chunk.indexOf(` `, searchIndex); for (; lfIndex !== -1; ) { if (searchIndex === lfIndex) { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); continue; } const firstCharCode = chunk.charCodeAt(searchIndex); if (isDataPrefix(chunk, searchIndex, firstCharCode)) { const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex); if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) { onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(` `, searchIndex); continue; } data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice( chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex ) || void 0 : parseLine(chunk, searchIndex, lfIndex); searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); } return chunk.slice(searchIndex); } for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break; parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++; } return chunk.slice(searchIndex); } function parseLine(chunk, start, end) { if (start === end) { dispatchEvent(); return; } const firstCharCode = chunk.charCodeAt(start); if (isDataPrefix(chunk, start, firstCharCode)) { const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end); data = dataLines === 0 ? value2 : `${data} ${value2}`, dataLines++; return; } if (isEventPrefix(chunk, start, firstCharCode)) { eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0; return; } if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) { const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end); id = value2.includes("\0") ? void 0 : value2; return; } if (firstCharCode === 58) { if (onComment) { const line2 = chunk.slice(start, end); onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1)); } return; } const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":"); if (fieldSeparatorIndex === -1) { processField(line, "", line); return; } const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); processField(field, value, line); } function processField(field, value, line) { switch (field) { case "event": eventType = value || void 0; break; case "data": data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line } ) ); break; } } function dispatchEvent() { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0; } function reset(options = {}) { if (options.consume && pendingFragments.length > 0) { const incompleteLine = pendingFragments.join(""); parseLine(incompleteLine, 0, incompleteLine.length); } isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0; } return { feed, reset }; } function isDataPrefix(chunk, i, firstCharCode) { return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58; } function isEventPrefix(chunk, i, firstCharCode) { return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58; } var EventSourceParserStream = class extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser({ onEvent: (event) => { controller.enqueue(event); }, onError(error90) { onError === "terminate" ? controller.error(error90) : typeof onError == "function" && onError(error90); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; function combineHeaders(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {} ); } async function delay2(delayInMs, options) { if (delayInMs == null) { return Promise.resolve(); } const signal = options == null ? void 0 : options.abortSignal; return new Promise((resolve22, reject) => { if (signal == null ? void 0 : signal.aborted) { reject(createAbortError()); return; } const timeoutId = setTimeout(() => { cleanup(); resolve22(); }, delayInMs); const cleanup = () => { clearTimeout(timeoutId); signal == null ? void 0 : signal.removeEventListener("abort", onAbort); }; const onAbort = () => { cleanup(); reject(createAbortError()); }; signal == null ? void 0 : signal.addEventListener("abort", onAbort); }); } function createAbortError() { return new DOMException("Delay was aborted", "AbortError"); } function extractResponseHeaders(response) { return Object.fromEntries([...response.headers]); } var createIdGenerator2 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i = 0; i < size; i++) { chars[i] = alphabet[Math.random() * alphabetLength | 0]; } return chars.join(""); }; if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError3({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return () => `${prefix}${separator}${generator()}`; }; createIdGenerator2(); function getErrorMessage22(error90) { if (error90 == null) { return "unknown error"; } if (typeof error90 === "string") { return error90; } if (error90 instanceof Error) { return error90.message; } return JSON.stringify(error90); } function isAbortError2(error90) { return (error90 instanceof Error || error90 instanceof DOMException) && (error90.name === "AbortError" || error90.name === "ResponseAborted" || // Next.js error90.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"]; function handleFetchError({ error: error90, url: url3, requestBodyValues }) { if (isAbortError2(error90)) { return error90; } if (error90 instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error90.message.toLowerCase())) { const cause = error90.cause; if (cause != null) { return new APICallError2({ message: `Cannot connect to API: ${cause.message}`, cause, url: url3, requestBodyValues, isRetryable: true // retry when network error }); } } return error90; } function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) { var _a224, _b2222, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a224 = globalThisAny.navigator) == null ? void 0 : _a224.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b2222 = globalThisAny.process) == null ? void 0 : _b2222.versions) == null ? void 0 : _c.node) { return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; } if (globalThisAny.EdgeRuntime) { return `runtime/vercel-edge`; } return "runtime/unknown"; } function normalizeHeaders(headers) { if (headers == null) { return {}; } const normalized = {}; if (headers instanceof Headers) { headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); } else { if (!Array.isArray(headers)) { headers = Object.entries(headers); } for (const [key, value] of headers) { if (value != null) { normalized[key.toLowerCase()] = value; } } } return normalized; } function withUserAgentSuffix(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION2 = "3.0.25"; var getOriginalFetch = () => globalThis.fetch; var getFromApi = async ({ url: url3, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch() }) => { try { const response = await fetch2(url3, { method: "GET", headers: withUserAgentSuffix( headers, `ai-sdk/provider-utils/${VERSION2}`, getRuntimeEnvironmentUserAgent() ), signal: abortSignal }); const responseHeaders = extractResponseHeaders(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url: url3, requestBodyValues: {} }); } catch (error90) { if (isAbortError2(error90) || APICallError2.isInstance(error90)) { throw error90; } throw new APICallError2({ message: "Failed to process error response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: {} }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url3, requestBodyValues: {} }); } catch (error90) { if (error90 instanceof Error) { if (isAbortError2(error90) || APICallError2.isInstance(error90)) { throw error90; } } throw new APICallError2({ message: "Failed to process successful response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: {} }); } } catch (error90) { throw handleFetchError({ error: error90, url: url3, requestBodyValues: {} }); } }; function loadOptionalSetting({ settingValue, environmentVariableName }) { if (typeof settingValue === "string") { return settingValue; } if (settingValue != null || typeof process === "undefined") { return void 0; } settingValue = process.env[environmentVariableName]; if (settingValue == null || typeof settingValue !== "string") { return void 0; } return settingValue; } var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse2(text42) { const obj = JSON.parse(text42); if (obj === null || typeof obj !== "object") { return obj; } if (suspectProtoRx.test(text42) === false && suspectConstructorRx.test(text42) === false) { return obj; } return filter(obj); } function filter(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) { throw new SyntaxError("Object contains forbidden prototype property"); } if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { throw new SyntaxError("Object contains forbidden prototype property"); } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function secureJsonParse(text42) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e2) { return _parse2(text42); } try { return _parse2(text42); } finally { Error.stackTraceLimit = stackTraceLimit; } } var validatorSymbol2 = /* @__PURE__ */ Symbol.for("vercel.ai.validator"); function validator2(validate) { return { [validatorSymbol2]: true, validate }; } function isValidator2(value) { return typeof value === "object" && value !== null && validatorSymbol2 in value && value[validatorSymbol2] === true && "validate" in value; } function lazyValidator(createValidator) { let validator22; return () => { if (validator22 == null) { validator22 = createValidator(); } return validator22; }; } function asValidator2(value) { return isValidator2(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value); } function standardSchemaValidator(standardSchema2) { return validator2(async (value) => { const result = await standardSchema2["~standard"].validate(value); return result.issues == null ? { success: true, value: result.value } : { success: false, error: new TypeValidationError2({ value, cause: result.issues }) }; }); } async function validateTypes({ value, schema }) { const result = await safeValidateTypes2({ value, schema }); if (!result.success) { throw TypeValidationError2.wrap({ value, cause: result.error }); } return result.value; } async function safeValidateTypes2({ value, schema }) { const validator22 = asValidator2(schema); try { if (validator22.validate == null) { return { success: true, value, rawValue: value }; } const result = await validator22.validate(value); if (result.success) { return { success: true, value: result.value, rawValue: value }; } return { success: false, error: TypeValidationError2.wrap({ value, cause: result.error }), rawValue: value }; } catch (error90) { return { success: false, error: TypeValidationError2.wrap({ value, cause: error90 }), rawValue: value }; } } async function parseJSON({ text: text42, schema }) { try { const value = secureJsonParse(text42); if (schema == null) { return value; } return validateTypes({ value, schema }); } catch (error90) { if (JSONParseError2.isInstance(error90) || TypeValidationError2.isInstance(error90)) { throw error90; } throw new JSONParseError2({ text: text42, cause: error90 }); } } async function safeParseJSON2({ text: text42, schema }) { try { const value = secureJsonParse(text42); if (schema == null) { return { success: true, value, rawValue: value }; } return await safeValidateTypes2({ value, schema }); } catch (error90) { return { success: false, error: JSONParseError2.isInstance(error90) ? error90 : new JSONParseError2({ text: text42, cause: error90 }), rawValue: void 0 }; } } function parseJsonEventStream({ stream, schema }) { return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough( new TransformStream({ async transform({ data }, controller) { if (data === "[DONE]") { return; } controller.enqueue(await safeParseJSON2({ text: data, schema })); } }) ); } var getOriginalFetch2 = () => globalThis.fetch; var postJsonToApi = async ({ url: url3, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi({ url: url3, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postToApi = async ({ url: url3, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() }) => { try { const response = await fetch2(url3, { method: "POST", headers: withUserAgentSuffix( headers, `ai-sdk/provider-utils/${VERSION2}`, getRuntimeEnvironmentUserAgent() ), body: body.content, signal: abortSignal }); const responseHeaders = extractResponseHeaders(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url: url3, requestBodyValues: body.values }); } catch (error90) { if (isAbortError2(error90) || APICallError2.isInstance(error90)) { throw error90; } throw new APICallError2({ message: "Failed to process error response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: body.values }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url3, requestBodyValues: body.values }); } catch (error90) { if (error90 instanceof Error) { if (isAbortError2(error90) || APICallError2.isInstance(error90)) { throw error90; } } throw new APICallError2({ message: "Failed to process successful response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: body.values }); } } catch (error90) { throw handleFetchError({ error: error90, url: url3, requestBodyValues: body.values }); } }; function tool(tool22) { return tool22; } function createProviderDefinedToolFactoryWithOutputSchema({ id, name: name224, inputSchema, outputSchema: outputSchema32 }) { return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider-defined", id, name: name224, args, inputSchema, outputSchema: outputSchema32, execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } async function resolve(value) { if (typeof value === "function") { value = value(); } return Promise.resolve(value); } var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url: url3, requestBodyValues }) => { const responseBody = await response.text(); const responseHeaders = extractResponseHeaders(response); if (responseBody.trim() === "") { return { responseHeaders, value: new APICallError2({ message: response.statusText, url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } try { const parsedError = await parseJSON({ text: responseBody, schema: errorSchema }); return { responseHeaders, value: new APICallError2({ message: errorToMessage(parsedError), url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, data: parsedError, isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) }) }; } catch (parseError) { return { responseHeaders, value: new APICallError2({ message: response.statusText, url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } }; var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => { const responseHeaders = extractResponseHeaders(response); if (response.body == null) { throw new EmptyResponseBodyError({}); } return { responseHeaders, value: parseJsonEventStream({ stream: response.body, schema: chunkSchema }) }; }; var createJsonResponseHandler = (responseSchema) => async ({ response, url: url3, requestBodyValues }) => { const responseBody = await response.text(); const parsedResult = await safeParseJSON2({ text: responseBody, schema: responseSchema }); const responseHeaders = extractResponseHeaders(response); if (!parsedResult.success) { throw new APICallError2({ message: "Invalid JSON response", cause: parsedResult.error, statusCode: response.status, responseHeaders, responseBody, url: url3, requestBodyValues }); } return { responseHeaders, value: parsedResult.value, rawValue: parsedResult.rawValue }; }; var schemaSymbol2 = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema(createSchema) { let schema; return () => { if (schema == null) { schema = createSchema(); } return schema; }; } function jsonSchema2(jsonSchema22, { validate } = {}) { return { [schemaSymbol2]: true, _type: void 0, // should never be used directly [validatorSymbol2]: true, get jsonSchema() { if (typeof jsonSchema22 === "function") { jsonSchema22 = jsonSchema22(); } return jsonSchema22; }, validate }; } function addAdditionalPropertiesToJsonSchema(jsonSchema22) { if (jsonSchema22.type === "object") { jsonSchema22.additionalProperties = false; const properties = jsonSchema22.properties; if (properties != null) { for (const property in properties) { properties[property] = addAdditionalPropertiesToJsonSchema( properties[property] ); } } } if (jsonSchema22.type === "array" && jsonSchema22.items != null) { if (Array.isArray(jsonSchema22.items)) { jsonSchema22.items = jsonSchema22.items.map( (item) => addAdditionalPropertiesToJsonSchema(item) ); } else { jsonSchema22.items = addAdditionalPropertiesToJsonSchema( jsonSchema22.items ); } } return jsonSchema22; } var ignoreOverride2 = /* @__PURE__ */ Symbol( "Let zodToJsonSchema decide on which parser to use" ); var defaultOptions2 = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions2 = (options) => typeof options === "string" ? { ...defaultOptions2, name: options } : { ...defaultOptions2, ...options }; function parseAnyDef2() { return {}; } function parseArrayDef2(def, refs) { var _a224, _b2222, _c; const res = { type: "array" }; if (((_a224 = def.type) == null ? void 0 : _a224._def) && ((_c = (_b2222 = def.type) == null ? void 0 : _b2222._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind3.ZodAny) { res.items = parseDef2(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { res.minItems = def.minLength.value; } if (def.maxLength) { res.maxItems = def.maxLength.value; } if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef2(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "min": if (check3.inclusive) { res.minimum = check3.value; } else { res.exclusiveMinimum = check3.value; } break; case "max": if (check3.inclusive) { res.maximum = check3.value; } else { res.exclusiveMaximum = check3.value; } break; case "multipleOf": res.multipleOf = check3.value; break; } } return res; } function parseBooleanDef2() { return { type: "boolean" }; } function parseBrandedDef2(_def, refs) { return parseDef2(_def.type._def, refs); } var parseCatchDef2 = (def, refs) => { return parseDef2(def.innerType._def, refs); }; function parseDateDef2(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef2(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 integerDateParser2(def); } } var integerDateParser2 = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check3 of def.checks) { switch (check3.kind) { case "min": res.minimum = check3.value; break; case "max": res.maximum = check3.value; break; } } return res; }; function parseDefaultDef2(_def, refs) { return { ...parseDef2(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef2(_def, refs) { return refs.effectStrategy === "input" ? parseDef2(_def.schema._def, refs) : parseAnyDef2(); } function parseEnumDef2(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType2 = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef2(def, refs) { const allOf = [ parseDef2(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef2(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType2(schema)) { mergedAllOf.push(...schema.allOf); } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef2(def) { const parsedType5 = typeof def.value; if (parsedType5 !== "bigint" && parsedType5 !== "number" && parsedType5 !== "boolean" && parsedType5 !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } return { type: parsedType5 === "bigint" ? "integer" : parsedType5, const: def.value }; } var emojiRegex4 = void 0; var zodPatterns2 = { /** * `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 (emojiRegex4 === void 0) { emojiRegex4 = RegExp( "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u" ); } return emojiRegex4; }, /** * 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 parseStringDef2(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check3 of def.checks) { switch (check3.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat2(res, "email", check3.message, refs); break; case "format:idn-email": addFormat2(res, "idn-email", check3.message, refs); break; case "pattern:zod": addPattern2(res, zodPatterns2.email, check3.message, refs); break; } break; case "url": addFormat2(res, "uri", check3.message, refs); break; case "uuid": addFormat2(res, "uuid", check3.message, refs); break; case "regex": addPattern2(res, check3.regex, check3.message, refs); break; case "cuid": addPattern2(res, zodPatterns2.cuid, check3.message, refs); break; case "cuid2": addPattern2(res, zodPatterns2.cuid2, check3.message, refs); break; case "startsWith": addPattern2( res, RegExp(`^${escapeLiteralCheckValue2(check3.value, refs)}`), check3.message, refs ); break; case "endsWith": addPattern2( res, RegExp(`${escapeLiteralCheckValue2(check3.value, refs)}$`), check3.message, refs ); break; case "datetime": addFormat2(res, "date-time", check3.message, refs); break; case "date": addFormat2(res, "date", check3.message, refs); break; case "time": addFormat2(res, "time", check3.message, refs); break; case "duration": addFormat2(res, "duration", check3.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value; break; case "includes": { addPattern2( res, RegExp(escapeLiteralCheckValue2(check3.value, refs)), check3.message, refs ); break; } case "ip": { if (check3.version !== "v6") { addFormat2(res, "ipv4", check3.message, refs); } if (check3.version !== "v4") { addFormat2(res, "ipv6", check3.message, refs); } break; } case "base64url": addPattern2(res, zodPatterns2.base64url, check3.message, refs); break; case "jwt": addPattern2(res, zodPatterns2.jwt, check3.message, refs); break; case "cidr": { if (check3.version !== "v6") { addPattern2(res, zodPatterns2.ipv4Cidr, check3.message, refs); } if (check3.version !== "v4") { addPattern2(res, zodPatterns2.ipv6Cidr, check3.message, refs); } break; } case "emoji": addPattern2(res, zodPatterns2.emoji(), check3.message, refs); break; case "ulid": { addPattern2(res, zodPatterns2.ulid, check3.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat2(res, "binary", check3.message, refs); break; } case "contentEncoding:base64": { res.contentEncoding = "base64"; break; } case "pattern:zod": { addPattern2(res, zodPatterns2.base64, check3.message, refs); break; } } break; } case "nanoid": { addPattern2(res, zodPatterns2.nanoid, check3.message, refs); } } } } return res; } function escapeLiteralCheckValue2(literal3, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal3) : literal3; } var ALPHA_NUMERIC2 = new Set( "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789" ); function escapeNonAlphaNumeric2(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC2.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat2(schema, value, message, refs) { var _a224; if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x) => x.format))) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format }); delete schema.format; } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { schema.format = value; } } function addPattern2(schema, regex, message, refs) { var _a224; if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x) => x.pattern))) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern }); delete schema.pattern; } schema.allOf.push({ pattern: stringifyRegExpWithFlags2(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { schema.pattern = stringifyRegExpWithFlags2(regex, refs); } } function stringifyRegExpWithFlags2(regex, refs) { var _a224; if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s") // `.` matches newlines }; 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] === "-" && ((_a224 = source[i + 2]) == null ? void 0 : _a224.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 ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } return pattern; } function parseRecordDef2(def, refs) { var _a224, _b2222, _c, _d, _e, _f; const schema = { type: "object", additionalProperties: (_a224 = parseDef2(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] })) != null ? _a224 : refs.allowedAdditionalProperties }; if (((_b2222 = def.keyType) == null ? void 0 : _b2222._def.typeName) === ZodFirstPartyTypeKind3.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) { const { type, ...keyType } = parseStringDef2(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind3.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind3.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind3.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) { const { type, ...keyType } = parseBrandedDef2( def.keyType._def, refs ); return { ...schema, propertyNames: keyType }; } return schema; } function parseMapDef2(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef2(def, refs); } const keys = parseDef2(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || parseAnyDef2(); const values = parseDef2(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || parseAnyDef2(); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } function parseNativeEnumDef2(def) { const object62 = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object62[object62[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object62[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 }; } function parseNeverDef2() { return { not: parseAnyDef2() }; } function parseNullDef2() { return { type: "null" }; } var primitiveMappings2 = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef2(def, refs) { const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every( (x) => x._def.typeName in primitiveMappings2 && (!x._def.checks || !x._def.checks.length) )) { const types = options.reduce((types2, x) => { const type = primitiveMappings2[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { 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) { 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((x2) => !acc.includes(x2)) ], [] ) }; } return asAnyOf2(def, refs); } var asAnyOf2 = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map( (x, i) => parseDef2(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 } : void 0; }; function parseNullableDef2(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes( def.innerType._def.typeName ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { return { type: [ primitiveMappings2[def.innerType._def.typeName], "null" ] }; } const base = parseDef2(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } function parseNumberDef2(def) { const res = { type: "number" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "int": res.type = "integer"; break; case "min": if (check3.inclusive) { res.minimum = check3.value; } else { res.exclusiveMinimum = check3.value; } break; case "max": if (check3.inclusive) { res.maximum = check3.value; } else { res.exclusiveMaximum = check3.value; } break; case "multipleOf": res.multipleOf = check3.value; break; } } return res; } function parseObjectDef2(def, refs) { const result = { type: "object", properties: {} }; const required3 = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } const propOptional = safeIsOptional2(propDef); const parsedDef = parseDef2(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required3.push(propName); } } if (required3.length) { result.required = required3; } const additionalProperties = decideAdditionalProperties2(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties2(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef2(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 safeIsOptional2(schema) { try { return schema.isOptional(); } catch (e2) { return true; } } var parseOptionalDef2 = (def, refs) => { var _a224; if (refs.currentPath.toString() === ((_a224 = refs.propertyPath) == null ? void 0 : _a224.toString())) { return parseDef2(def.innerType._def, refs); } const innerSchema = parseDef2(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [{ not: parseAnyDef2() }, innerSchema] } : parseAnyDef2(); }; var parsePipelineDef2 = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef2(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef2(def.out._def, refs); } const a = parseDef2(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef2(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== void 0) }; }; function parsePromiseDef2(def, refs) { return parseDef2(def.type._def, refs); } function parseSetDef2(def, refs) { const items = parseDef2(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { schema.minItems = def.minSize.value; } if (def.maxSize) { schema.maxItems = def.maxSize.value; } return schema; } function parseTupleDef2(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map( (x, i) => parseDef2(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ), additionalItems: parseDef2(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) => parseDef2(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ) }; } } function parseUndefinedDef2() { return { not: parseAnyDef2() }; } function parseUnknownDef2() { return parseAnyDef2(); } var parseReadonlyDef2 = (def, refs) => { return parseDef2(def.innerType._def, refs); }; var selectParser2 = (def, typeName, refs) => { switch (typeName) { case ZodFirstPartyTypeKind3.ZodString: return parseStringDef2(def, refs); case ZodFirstPartyTypeKind3.ZodNumber: return parseNumberDef2(def); case ZodFirstPartyTypeKind3.ZodObject: return parseObjectDef2(def, refs); case ZodFirstPartyTypeKind3.ZodBigInt: return parseBigintDef2(def); case ZodFirstPartyTypeKind3.ZodBoolean: return parseBooleanDef2(); case ZodFirstPartyTypeKind3.ZodDate: return parseDateDef2(def, refs); case ZodFirstPartyTypeKind3.ZodUndefined: return parseUndefinedDef2(); case ZodFirstPartyTypeKind3.ZodNull: return parseNullDef2(); case ZodFirstPartyTypeKind3.ZodArray: return parseArrayDef2(def, refs); case ZodFirstPartyTypeKind3.ZodUnion: case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion: return parseUnionDef2(def, refs); case ZodFirstPartyTypeKind3.ZodIntersection: return parseIntersectionDef2(def, refs); case ZodFirstPartyTypeKind3.ZodTuple: return parseTupleDef2(def, refs); case ZodFirstPartyTypeKind3.ZodRecord: return parseRecordDef2(def, refs); case ZodFirstPartyTypeKind3.ZodLiteral: return parseLiteralDef2(def); case ZodFirstPartyTypeKind3.ZodEnum: return parseEnumDef2(def); case ZodFirstPartyTypeKind3.ZodNativeEnum: return parseNativeEnumDef2(def); case ZodFirstPartyTypeKind3.ZodNullable: return parseNullableDef2(def, refs); case ZodFirstPartyTypeKind3.ZodOptional: return parseOptionalDef2(def, refs); case ZodFirstPartyTypeKind3.ZodMap: return parseMapDef2(def, refs); case ZodFirstPartyTypeKind3.ZodSet: return parseSetDef2(def, refs); case ZodFirstPartyTypeKind3.ZodLazy: return () => def.getter()._def; case ZodFirstPartyTypeKind3.ZodPromise: return parsePromiseDef2(def, refs); case ZodFirstPartyTypeKind3.ZodNaN: case ZodFirstPartyTypeKind3.ZodNever: return parseNeverDef2(); case ZodFirstPartyTypeKind3.ZodEffects: return parseEffectsDef2(def, refs); case ZodFirstPartyTypeKind3.ZodAny: return parseAnyDef2(); case ZodFirstPartyTypeKind3.ZodUnknown: return parseUnknownDef2(); case ZodFirstPartyTypeKind3.ZodDefault: return parseDefaultDef2(def, refs); case ZodFirstPartyTypeKind3.ZodBranded: return parseBrandedDef2(def, refs); case ZodFirstPartyTypeKind3.ZodReadonly: return parseReadonlyDef2(def, refs); case ZodFirstPartyTypeKind3.ZodCatch: return parseCatchDef2(def, refs); case ZodFirstPartyTypeKind3.ZodPipeline: return parsePipelineDef2(def, refs); case ZodFirstPartyTypeKind3.ZodFunction: case ZodFirstPartyTypeKind3.ZodVoid: case ZodFirstPartyTypeKind3.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_) => void 0)(); } }; var getRelativePath2 = (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("/"); }; function parseDef2(def, refs, forceResolution = false) { var _a224; const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = (_a224 = refs.override) == null ? void 0 : _a224.call( refs, def, refs, seenItem, forceResolution ); if (overrideResult !== ignoreOverride2) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref2(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser2(def, def.typeName, refs); const jsonSchema22 = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema22) { addMeta2(def, refs, jsonSchema22); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema22, def, refs); newItem.jsonSchema = jsonSchema22; return postProcessResult; } newItem.jsonSchema = jsonSchema22; return jsonSchema22; } var get$ref2 = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath2(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 parseAnyDef2(); } return refs.$refStrategy === "seen" ? parseAnyDef2() : void 0; } } }; var addMeta2 = (def, refs, jsonSchema22) => { if (def.description) { jsonSchema22.description = def.description; } return jsonSchema22; }; var getRefs2 = (options) => { const _options = getDefaultOptions2(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: void 0, seen: new Map( Object.entries(_options.definitions).map(([name224, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name224], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ]) ) }; }; var zodToJsonSchema2 = (schema, options) => { var _a224; const refs = getRefs2(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce( (acc, [name324, schema2]) => { var _a324; return { ...acc, [name324]: (_a324 = parseDef2( schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name324] }, true )) != null ? _a324 : parseAnyDef2() }; }, {} ) : void 0; const name224 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name; const main = (_a224 = parseDef2( schema._def, name224 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name224] }, false )) != null ? _a224 : parseAnyDef2(); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main.title = title; } const combined = name224 === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name224 ].join("/"), [refs.definitionPath]: { ...definitions, [name224]: main } }; combined.$schema = "http://json-schema.org/draft-07/schema#"; return combined; }; var zod_to_json_schema_default = zodToJsonSchema2; function zod3Schema(zodSchema22, options) { var _a224; const useReferences = (_a224 = void 0) != null ? _a224 : false; return jsonSchema2( // defer json schema creation to avoid unnecessary computation when only validation is needed () => zod_to_json_schema_default(zodSchema22, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => { const result = await zodSchema22.safeParseAsync(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function zod4Schema(zodSchema22, options) { var _a224; const useReferences = (_a224 = void 0) != null ? _a224 : false; return jsonSchema2( // defer json schema creation to avoid unnecessary computation when only validation is needed () => addAdditionalPropertiesToJsonSchema( toJSONSchema(zodSchema22, { target: "draft-7", io: "input", reused: useReferences ? "ref" : "inline" }) ), { validate: async (value) => { const result = await safeParseAsync2(zodSchema22, value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function isZod4Schema(zodSchema22) { return "_zod" in zodSchema22; } function zodSchema2(zodSchema22, options) { if (isZod4Schema(zodSchema22)) { return zod4Schema(zodSchema22); } else { return zod3Schema(zodSchema22); } } function isSchema2(value) { return typeof value === "object" && value !== null && schemaSymbol2 in value && value[schemaSymbol2] === true && "jsonSchema" in value && "validate" in value; } function asSchema2(schema) { return schema == null ? jsonSchema2({ properties: {}, additionalProperties: false }) : isSchema2(schema) ? schema : typeof schema === "function" ? schema() : zodSchema2(schema); } function withoutTrailingSlash(url3) { return url3 == null ? void 0 : url3.replace(/\/$/, ""); } function getContext() { return { headers: {} }; } async function getVercelOidcToken() { if (process.env.VERCEL_OIDC_TOKEN) { return process.env.VERCEL_OIDC_TOKEN ?? ""; } throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead."); } var marker18 = "vercel.ai.gateway.error"; var symbol19 = Symbol.for(marker18); var _a20; var _b16; var GatewayError = class _GatewayError extends (_b16 = Error, _a20 = symbol19, _b16) { constructor({ message, statusCode = 500, cause }) { super(message); this[_a20] = true; this.statusCode = statusCode; this.cause = cause; } /** * Checks if the given error is a Gateway Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is a Gateway Error, false otherwise. */ static isInstance(error90) { return _GatewayError.hasMarker(error90); } static hasMarker(error90) { return typeof error90 === "object" && error90 !== null && symbol19 in error90 && error90[symbol19] === true; } }; var name18 = "GatewayAuthenticationError"; var marker24 = `vercel.ai.gateway.error.${name18}`; var symbol24 = Symbol.for(marker24); var _a24; var _b22; var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b22 = GatewayError, _a24 = symbol24, _b22) { constructor({ message = "Authentication failed", statusCode = 401, cause } = {}) { super({ message, statusCode, cause }); this[_a24] = true; this.name = name18; this.type = "authentication_error"; } static isInstance(error90) { return GatewayError.hasMarker(error90) && symbol24 in error90; } /** * Creates a contextual error message when authentication fails */ static createContextualError({ apiKeyProvided, oidcTokenProvided, message = "Authentication failed", statusCode = 401, cause }) { let contextualMessage; if (apiKeyProvided) { contextualMessage = `AI Gateway authentication failed: Invalid API key. Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`; } else if (oidcTokenProvided) { contextualMessage = `AI Gateway authentication failed: Invalid OIDC token. Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token. Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`; } else { contextualMessage = `AI Gateway authentication failed: No authentication provided. Option 1 - API key: Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable. Option 2 - OIDC token: Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`; } return new _GatewayAuthenticationError({ message: contextualMessage, statusCode, cause }); } }; var name24 = "GatewayInvalidRequestError"; var marker34 = `vercel.ai.gateway.error.${name24}`; var symbol34 = Symbol.for(marker34); var _a34; var _b32; var GatewayInvalidRequestError = class extends (_b32 = GatewayError, _a34 = symbol34, _b32) { constructor({ message = "Invalid request", statusCode = 400, cause } = {}) { super({ message, statusCode, cause }); this[_a34] = true; this.name = name24; this.type = "invalid_request_error"; } static isInstance(error90) { return GatewayError.hasMarker(error90) && symbol34 in error90; } }; var name34 = "GatewayRateLimitError"; var marker44 = `vercel.ai.gateway.error.${name34}`; var symbol44 = Symbol.for(marker44); var _a44; var _b42; var GatewayRateLimitError = class extends (_b42 = GatewayError, _a44 = symbol44, _b42) { constructor({ message = "Rate limit exceeded", statusCode = 429, cause } = {}) { super({ message, statusCode, cause }); this[_a44] = true; this.name = name34; this.type = "rate_limit_exceeded"; } static isInstance(error90) { return GatewayError.hasMarker(error90) && symbol44 in error90; } }; var name44 = "GatewayModelNotFoundError"; var marker54 = `vercel.ai.gateway.error.${name44}`; var symbol54 = Symbol.for(marker54); var modelNotFoundParamSchema = lazyValidator( () => zodSchema2( external_exports2.object({ modelId: external_exports2.string() }) ) ); var _a54; var _b52; var GatewayModelNotFoundError = class extends (_b52 = GatewayError, _a54 = symbol54, _b52) { constructor({ message = "Model not found", statusCode = 404, modelId, cause } = {}) { super({ message, statusCode, cause }); this[_a54] = true; this.name = name44; this.type = "model_not_found"; this.modelId = modelId; } static isInstance(error90) { return GatewayError.hasMarker(error90) && symbol54 in error90; } }; var name54 = "GatewayInternalServerError"; var marker64 = `vercel.ai.gateway.error.${name54}`; var symbol64 = Symbol.for(marker64); var _a64; var _b62; var GatewayInternalServerError = class extends (_b62 = GatewayError, _a64 = symbol64, _b62) { constructor({ message = "Internal server error", statusCode = 500, cause } = {}) { super({ message, statusCode, cause }); this[_a64] = true; this.name = name54; this.type = "internal_server_error"; } static isInstance(error90) { return GatewayError.hasMarker(error90) && symbol64 in error90; } }; var name64 = "GatewayResponseError"; var marker74 = `vercel.ai.gateway.error.${name64}`; var symbol74 = Symbol.for(marker74); var _a74; var _b72; var GatewayResponseError = class extends (_b72 = GatewayError, _a74 = symbol74, _b72) { constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause } = {}) { super({ message, statusCode, cause }); this[_a74] = true; this.name = name64; this.type = "response_error"; this.response = response; this.validationError = validationError; } static isInstance(error90) { return GatewayError.hasMarker(error90) && symbol74 in error90; } }; async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) { const parseResult = await safeValidateTypes2({ value: response, schema: gatewayErrorResponseSchema }); if (!parseResult.success) { return new GatewayResponseError({ message: `Invalid error response format: ${defaultMessage}`, statusCode, response, validationError: parseResult.error, cause }); } const validatedResponse = parseResult.value; const errorType = validatedResponse.error.type; const message = validatedResponse.error.message; switch (errorType) { case "authentication_error": return GatewayAuthenticationError.createContextualError({ apiKeyProvided: authMethod === "api-key", oidcTokenProvided: authMethod === "oidc", statusCode, cause }); case "invalid_request_error": return new GatewayInvalidRequestError({ message, statusCode, cause }); case "rate_limit_exceeded": return new GatewayRateLimitError({ message, statusCode, cause }); case "model_not_found": { const modelResult = await safeValidateTypes2({ value: validatedResponse.error.param, schema: modelNotFoundParamSchema }); return new GatewayModelNotFoundError({ message, statusCode, modelId: modelResult.success ? modelResult.value.modelId : void 0, cause }); } case "internal_server_error": return new GatewayInternalServerError({ message, statusCode, cause }); default: return new GatewayInternalServerError({ message, statusCode, cause }); } } var gatewayErrorResponseSchema = lazyValidator( () => zodSchema2( external_exports2.object({ error: external_exports2.object({ message: external_exports2.string(), type: external_exports2.string().nullish(), param: external_exports2.unknown().nullish(), code: external_exports2.union([external_exports2.string(), external_exports2.number()]).nullish() }) }) ) ); function extractApiCallResponse(error90) { if (error90.data !== void 0) { return error90.data; } if (error90.responseBody != null) { try { return JSON.parse(error90.responseBody); } catch (e2) { return error90.responseBody; } } return {}; } var name74 = "GatewayTimeoutError"; var marker84 = `vercel.ai.gateway.error.${name74}`; var symbol84 = Symbol.for(marker84); var _a84; var _b82; var GatewayTimeoutError = class _GatewayTimeoutError extends (_b82 = GatewayError, _a84 = symbol84, _b82) { constructor({ message = "Request timed out", statusCode = 408, cause } = {}) { super({ message, statusCode, cause }); this[_a84] = true; this.name = name74; this.type = "timeout_error"; } static isInstance(error90) { return GatewayError.hasMarker(error90) && symbol84 in error90; } /** * Creates a helpful timeout error message with troubleshooting guidance */ static createTimeoutError({ originalMessage, statusCode = 408, cause }) { const message = `Gateway request timed out: ${originalMessage} This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`; return new _GatewayTimeoutError({ message, statusCode, cause }); } }; function isTimeoutError(error90) { if (!(error90 instanceof Error)) { return false; } const errorCode = error90.code; if (typeof errorCode === "string") { const undiciTimeoutCodes = [ "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT" ]; return undiciTimeoutCodes.includes(errorCode); } return false; } async function asGatewayError(error90, authMethod) { var _a932; if (GatewayError.isInstance(error90)) { return error90; } if (isTimeoutError(error90)) { return GatewayTimeoutError.createTimeoutError({ originalMessage: error90 instanceof Error ? error90.message : "Unknown error", cause: error90 }); } if (APICallError2.isInstance(error90)) { if (error90.cause && isTimeoutError(error90.cause)) { return GatewayTimeoutError.createTimeoutError({ originalMessage: error90.message, cause: error90 }); } return await createGatewayErrorFromResponse({ response: extractApiCallResponse(error90), statusCode: (_a932 = error90.statusCode) != null ? _a932 : 500, defaultMessage: "Gateway request failed", cause: error90, authMethod }); } return await createGatewayErrorFromResponse({ response: {}, statusCode: 500, defaultMessage: error90 instanceof Error ? `Gateway request failed: ${error90.message}` : "Unknown Gateway error", cause: error90, authMethod }); } var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method"; async function parseAuthMethod(headers) { const result = await safeValidateTypes2({ value: headers[GATEWAY_AUTH_METHOD_HEADER], schema: gatewayAuthMethodSchema }); return result.success ? result.value : void 0; } var gatewayAuthMethodSchema = lazyValidator( () => zodSchema2(external_exports2.union([external_exports2.literal("api-key"), external_exports2.literal("oidc")])) ); var KNOWN_MODEL_TYPES = ["embedding", "image", "language"]; var GatewayFetchMetadata = class { constructor(config3) { this.config = config3; } async getAvailableModels() { try { const { value } = await getFromApi({ url: `${this.config.baseURL}/config`, headers: await resolve(this.config.headers()), successfulResponseHandler: createJsonResponseHandler( gatewayAvailableModelsResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError(error90); } } async getCredits() { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi({ url: `${baseUrl.origin}/v1/credits`, headers: await resolve(this.config.headers()), successfulResponseHandler: createJsonResponseHandler( gatewayCreditsResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError(error90); } } }; var gatewayAvailableModelsResponseSchema = lazyValidator( () => zodSchema2( external_exports2.object({ models: external_exports2.array( external_exports2.object({ id: external_exports2.string(), name: external_exports2.string(), description: external_exports2.string().nullish(), pricing: external_exports2.object({ input: external_exports2.string(), output: external_exports2.string(), input_cache_read: external_exports2.string().nullish(), input_cache_write: external_exports2.string().nullish() }).transform( ({ input, output, input_cache_read, input_cache_write }) => ({ input, output, ...input_cache_read ? { cachedInputTokens: input_cache_read } : {}, ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {} }) ).nullish(), specification: external_exports2.object({ specificationVersion: external_exports2.literal("v2"), provider: external_exports2.string(), modelId: external_exports2.string() }), modelType: external_exports2.string().nullish() }) ).transform( (models) => models.filter( (m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType) ) ) }) ) ); var gatewayCreditsResponseSchema = lazyValidator( () => zodSchema2( external_exports2.object({ balance: external_exports2.string(), total_used: external_exports2.string() }).transform(({ balance, total_used }) => ({ balance, totalUsed: total_used })) ) ); var GatewaySpendReport = class { constructor(config3) { this.config = config3; } async getSpendReport(params) { try { const baseUrl = new URL(this.config.baseURL); const searchParams = new URLSearchParams(); searchParams.set("start_date", params.startDate); searchParams.set("end_date", params.endDate); if (params.groupBy) { searchParams.set("group_by", params.groupBy); } if (params.datePart) { searchParams.set("date_part", params.datePart); } if (params.userId) { searchParams.set("user_id", params.userId); } if (params.model) { searchParams.set("model", params.model); } if (params.provider) { searchParams.set("provider", params.provider); } if (params.credentialType) { searchParams.set("credential_type", params.credentialType); } if (params.tags && params.tags.length > 0) { searchParams.set("tags", params.tags.join(",")); } const { value } = await getFromApi({ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`, headers: await resolve(this.config.headers()), successfulResponseHandler: createJsonResponseHandler( gatewaySpendReportResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError(error90); } } }; var gatewaySpendReportResponseSchema = lazySchema( () => zodSchema2( external_exports2.object({ results: external_exports2.array( external_exports2.object({ day: external_exports2.string().optional(), hour: external_exports2.string().optional(), user: external_exports2.string().optional(), model: external_exports2.string().optional(), tag: external_exports2.string().optional(), provider: external_exports2.string().optional(), credential_type: external_exports2.enum(["byok", "system"]).optional(), total_cost: external_exports2.number(), market_cost: external_exports2.number().optional(), input_tokens: external_exports2.number().optional(), output_tokens: external_exports2.number().optional(), cached_input_tokens: external_exports2.number().optional(), cache_creation_input_tokens: external_exports2.number().optional(), reasoning_tokens: external_exports2.number().optional(), request_count: external_exports2.number().optional() }).transform( ({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({ ...rest, ...credential_type !== void 0 ? { credentialType: credential_type } : {}, totalCost: total_cost, ...market_cost !== void 0 ? { marketCost: market_cost } : {}, ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {}, ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {}, ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {}, ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {}, ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {}, ...request_count !== void 0 ? { requestCount: request_count } : {} }) ) ) }) ) ); var GatewayGenerationInfoFetcher = class { constructor(config3) { this.config = config3; } async getGenerationInfo(params) { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi({ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`, headers: await resolve(this.config.headers()), successfulResponseHandler: createJsonResponseHandler( gatewayGenerationInfoResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError(error90); } } }; var gatewayGenerationInfoResponseSchema = lazySchema( () => zodSchema2( external_exports2.object({ data: external_exports2.object({ id: external_exports2.string(), total_cost: external_exports2.number(), upstream_inference_cost: external_exports2.number(), usage: external_exports2.number(), created_at: external_exports2.string(), model: external_exports2.string(), is_byok: external_exports2.boolean(), provider_name: external_exports2.string(), streamed: external_exports2.boolean(), finish_reason: external_exports2.string(), latency: external_exports2.number(), generation_time: external_exports2.number(), native_tokens_prompt: external_exports2.number(), native_tokens_completion: external_exports2.number(), native_tokens_reasoning: external_exports2.number(), native_tokens_cached: external_exports2.number(), native_tokens_cache_creation: external_exports2.number(), billable_web_search_calls: external_exports2.number() }).transform( ({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({ ...rest, totalCost: total_cost, upstreamInferenceCost: upstream_inference_cost, createdAt: created_at, isByok: is_byok, providerName: provider_name, finishReason: finish_reason, generationTime: generation_time, promptTokens: native_tokens_prompt, completionTokens: native_tokens_completion, reasoningTokens: native_tokens_reasoning, cachedTokens: native_tokens_cached, cacheCreationTokens: native_tokens_cache_creation, billableWebSearchCalls: billable_web_search_calls }) ) }).transform(({ data }) => data) ) ); var GatewayLanguageModel = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v2"; this.supportedUrls = { "*/*": [/.*/] }; } get provider() { return this.config.provider; } async getArgs(options) { const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options; return { args: this.maybeEncodeFileParts(optionsWithoutSignal), warnings: [] }; } async doGenerate(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = await resolve(this.config.headers()); try { const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createJsonResponseHandler(external_exports2.any()), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { ...responseBody, request: { body: args }, response: { headers: responseHeaders, body: rawResponse }, warnings }; } catch (error90) { throw await asGatewayError(error90, await parseAuthMethod(resolvedHeaders)); } } async doStream(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = await resolve(this.config.headers()); try { const { value: response, responseHeaders } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createEventSourceResponseHandler(external_exports2.any()), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { stream: response.pipeThrough( new TransformStream({ start(controller) { if (warnings.length > 0) { controller.enqueue({ type: "stream-start", warnings }); } }, transform(chunk, controller) { if (chunk.success) { const streamPart = chunk.value; if (streamPart.type === "raw" && !options.includeRawChunks) { return; } if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") { streamPart.timestamp = new Date(streamPart.timestamp); } controller.enqueue(streamPart); } else { controller.error( chunk.error ); } } }) ), request: { body: args }, response: { headers: responseHeaders } }; } catch (error90) { throw await asGatewayError(error90, await parseAuthMethod(resolvedHeaders)); } } isFilePart(part) { return part && typeof part === "object" && "type" in part && part.type === "file"; } /** * Encodes file parts in the prompt to base64. Mutates the passed options * instance directly to avoid copying the file data. * @param options - The options to encode. * @returns The options with the file parts encoded. */ maybeEncodeFileParts(options) { for (const message of options.prompt) { for (const part of message.content) { if (this.isFilePart(part)) { const filePart = part; if (filePart.data instanceof Uint8Array) { const buffer = Uint8Array.from(filePart.data); const base64Data = Buffer.from(buffer).toString("base64"); filePart.data = new URL( `data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}` ); } } } } return options; } getUrl() { return `${this.config.baseURL}/language-model`; } getModelConfigHeaders(modelId, streaming) { return { "ai-language-model-specification-version": "2", "ai-language-model-id": modelId, "ai-language-model-streaming": String(streaming) }; } }; var GatewayEmbeddingModel = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v2"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a932; const resolvedHeaders = await resolve(this.config.headers()); try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ), body: { input: values.length === 1 ? values[0] : values, ...providerOptions ? { providerOptions } : {} }, successfulResponseHandler: createJsonResponseHandler( gatewayEmbeddingResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { embeddings: responseBody.embeddings, usage: (_a932 = responseBody.usage) != null ? _a932 : void 0, providerMetadata: responseBody.providerMetadata, response: { headers: responseHeaders, body: rawValue } }; } catch (error90) { throw await asGatewayError(error90, await parseAuthMethod(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/embedding-model`; } getModelConfigHeaders() { return { "ai-embedding-model-specification-version": "2", "ai-model-id": this.modelId }; } }; var gatewayEmbeddingResponseSchema = lazyValidator( () => zodSchema2( external_exports2.object({ embeddings: external_exports2.array(external_exports2.array(external_exports2.number())), usage: external_exports2.object({ tokens: external_exports2.number() }).nullish(), providerMetadata: external_exports2.record(external_exports2.string(), external_exports2.record(external_exports2.string(), external_exports2.unknown())).optional() }) ) ); var GatewayImageModel = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v2"; this.maxImagesPerCall = Number.MAX_SAFE_INTEGER; } get provider() { return this.config.provider; } async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) { var _a932, _b93, _c, _d; const resolvedHeaders = await resolve(this.config.headers()); try { const { responseHeaders, value: responseBody } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders) ), body: { prompt, n, ...size && { size }, ...aspectRatio && { aspectRatio }, ...seed && { seed }, ...providerOptions && { providerOptions } }, successfulResponseHandler: createJsonResponseHandler( gatewayImageResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: external_exports2.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { images: responseBody.images, // Always base64 strings from server warnings: (_a932 = responseBody.warnings) != null ? _a932 : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders }, ...responseBody.usage != null && { usage: { inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0, outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0, totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0 } } }; } catch (error90) { throw await asGatewayError(error90, await parseAuthMethod(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/image-model`; } getModelConfigHeaders() { return { "ai-image-model-specification-version": "2", "ai-model-id": this.modelId }; } }; var providerMetadataEntrySchema = external_exports2.object({ images: external_exports2.array(external_exports2.unknown()).optional() }).catchall(external_exports2.unknown()); var gatewayImageUsageSchema = external_exports2.object({ inputTokens: external_exports2.number().nullish(), outputTokens: external_exports2.number().nullish(), totalTokens: external_exports2.number().nullish() }); var gatewayImageResponseSchema = external_exports2.object({ images: external_exports2.array(external_exports2.string()), // Always base64 strings over the wire warnings: external_exports2.array( external_exports2.object({ type: external_exports2.literal("other"), message: external_exports2.string() }) ).optional(), providerMetadata: external_exports2.record(external_exports2.string(), providerMetadataEntrySchema).optional(), usage: gatewayImageUsageSchema.optional() }); var parallelSearchInputSchema = lazySchema( () => zodSchema2( external_exports2.object({ objective: external_exports2.string().describe( "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters." ), search_queries: external_exports2.array(external_exports2.string()).optional().describe( "Optional search queries to supplement the objective. Maximum 200 characters per query." ), mode: external_exports2.enum(["one-shot", "agentic"]).optional().describe( 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.' ), max_results: external_exports2.number().optional().describe( "Maximum number of results to return (1-20). Defaults to 10 if not specified." ), source_policy: external_exports2.object({ include_domains: external_exports2.array(external_exports2.string()).optional().describe("List of domains to include in search results."), exclude_domains: external_exports2.array(external_exports2.string()).optional().describe("List of domains to exclude from search results."), after_date: external_exports2.string().optional().describe( "Only include results published after this date (ISO 8601 format)." ) }).optional().describe( "Source policy for controlling which domains to include/exclude and freshness." ), excerpts: external_exports2.object({ max_chars_per_result: external_exports2.number().optional().describe("Maximum characters per result."), max_chars_total: external_exports2.number().optional().describe("Maximum total characters across all results.") }).optional().describe("Excerpt configuration for controlling result length."), fetch_policy: external_exports2.object({ max_age_seconds: external_exports2.number().optional().describe( "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content." ) }).optional().describe("Fetch policy for controlling content freshness.") }) ) ); var parallelSearchOutputSchema = lazySchema( () => zodSchema2( external_exports2.union([ // Success response external_exports2.object({ searchId: external_exports2.string(), results: external_exports2.array( external_exports2.object({ url: external_exports2.string(), title: external_exports2.string(), excerpt: external_exports2.string(), publishDate: external_exports2.string().nullable().optional(), relevanceScore: external_exports2.number().optional() }) ) }), // Error response external_exports2.object({ error: external_exports2.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "configuration_error", "unknown" ]), statusCode: external_exports2.number().optional(), message: external_exports2.string() }) ]) ) ); var parallelSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({ id: "gateway.parallel_search", name: "parallel_search", inputSchema: parallelSearchInputSchema, outputSchema: parallelSearchOutputSchema }); var parallelSearch = (config3 = {}) => parallelSearchToolFactory(config3); var perplexitySearchInputSchema = lazySchema( () => zodSchema2( external_exports2.object({ query: external_exports2.union([external_exports2.string(), external_exports2.array(external_exports2.string())]).describe( "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries." ), max_results: external_exports2.number().optional().describe( "Maximum number of search results to return (1-20, default: 10)" ), max_tokens_per_page: external_exports2.number().optional().describe( "Maximum number of tokens to extract per search result page (256-2048, default: 2048)" ), max_tokens: external_exports2.number().optional().describe( "Maximum total tokens across all search results (default: 25000, max: 1000000)" ), country: external_exports2.string().optional().describe( "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')" ), search_domain_filter: external_exports2.array(external_exports2.string()).optional().describe( "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']" ), search_language_filter: external_exports2.array(external_exports2.string()).optional().describe( "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']" ), search_after_date: external_exports2.string().optional().describe( "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter." ), search_before_date: external_exports2.string().optional().describe( "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter." ), last_updated_after_filter: external_exports2.string().optional().describe( "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter." ), last_updated_before_filter: external_exports2.string().optional().describe( "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter." ), search_recency_filter: external_exports2.enum(["day", "week", "month", "year"]).optional().describe( "Filter results by relative time period. Cannot be used with search_after_date or search_before_date." ) }) ) ); var perplexitySearchOutputSchema = lazySchema( () => zodSchema2( external_exports2.union([ // Success response external_exports2.object({ results: external_exports2.array( external_exports2.object({ title: external_exports2.string(), url: external_exports2.string(), snippet: external_exports2.string(), date: external_exports2.string().optional(), lastUpdated: external_exports2.string().optional() }) ), id: external_exports2.string() }), // Error response external_exports2.object({ error: external_exports2.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "unknown" ]), statusCode: external_exports2.number().optional(), message: external_exports2.string() }) ]) ) ); var perplexitySearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({ id: "gateway.perplexity_search", name: "perplexity_search", inputSchema: perplexitySearchInputSchema, outputSchema: perplexitySearchOutputSchema }); var perplexitySearch = (config3 = {}) => perplexitySearchToolFactory(config3); var gatewayTools = { /** * Search the web using Parallel AI's Search API for LLM-optimized excerpts. * * Takes a natural language objective and returns relevant excerpts, * replacing multiple keyword searches with a single call for broad * or complex queries. Supports different search types for depth vs * breadth tradeoffs. */ parallelSearch, /** * Search the web using Perplexity's Search API for real-time information, * news, research papers, and articles. * * Provides ranked search results with advanced filtering options including * domain, language, date range, and recency filters. */ perplexitySearch }; async function getVercelRequestId() { var _a932; return (_a932 = getContext().headers) == null ? void 0 : _a932["x-vercel-id"]; } var VERSION3 = "2.0.88"; var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1"; function createGatewayProvider(options = {}) { var _a932, _b93; let pendingMetadata = null; let metadataCache = null; const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5; let lastFetchTime = 0; const baseURL = (_b93 = withoutTrailingSlash(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v1/ai"; const getHeaders = async () => { const auth = await getGatewayAuthToken(options); if (auth) { return withUserAgentSuffix( { Authorization: `Bearer ${auth.token}`, "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION, [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod, ...options.headers }, `ai-sdk/gateway/${VERSION3}` ); } throw GatewayAuthenticationError.createContextualError({ apiKeyProvided: false, oidcTokenProvided: false, statusCode: 401 }); }; const createO11yHeaders = () => { const deploymentId = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_DEPLOYMENT_ID" }); const environment = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_ENV" }); const region = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_REGION" }); const projectId = loadOptionalSetting({ settingValue: void 0, environmentVariableName: "VERCEL_PROJECT_ID" }); return async () => { const requestId = await getVercelRequestId(); return { ...deploymentId && { "ai-o11y-deployment-id": deploymentId }, ...environment && { "ai-o11y-environment": environment }, ...region && { "ai-o11y-region": region }, ...requestId && { "ai-o11y-request-id": requestId }, ...projectId && { "ai-o11y-project-id": projectId } }; }; }; const createLanguageModel = (modelId) => { return new GatewayLanguageModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; const getAvailableModels = async () => { var _a1022, _b103, _c; const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now(); if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) { lastFetchTime = now2; pendingMetadata = new GatewayFetchMetadata({ baseURL, headers: getHeaders, fetch: options.fetch }).getAvailableModels().then((metadata) => { metadataCache = metadata; return metadata; }).catch(async (error90) => { throw await asGatewayError( error90, await parseAuthMethod(await getHeaders()) ); }); } return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata; }; const getCredits = async () => { return new GatewayFetchMetadata({ baseURL, headers: getHeaders, fetch: options.fetch }).getCredits().catch(async (error90) => { throw await asGatewayError( error90, await parseAuthMethod(await getHeaders()) ); }); }; const getSpendReport = async (params) => { return new GatewaySpendReport({ baseURL, headers: getHeaders, fetch: options.fetch }).getSpendReport(params).catch(async (error90) => { throw await asGatewayError( error90, await parseAuthMethod(await getHeaders()) ); }); }; const getGenerationInfo = async (params) => { return new GatewayGenerationInfoFetcher({ baseURL, headers: getHeaders, fetch: options.fetch }).getGenerationInfo(params).catch(async (error90) => { throw await asGatewayError( error90, await parseAuthMethod(await getHeaders()) ); }); }; const provider = function(modelId) { if (new.target) { throw new Error( "The Gateway Provider model function cannot be called with the new keyword." ); } return createLanguageModel(modelId); }; provider.getAvailableModels = getAvailableModels; provider.getCredits = getCredits; provider.getSpendReport = getSpendReport; provider.getGenerationInfo = getGenerationInfo; provider.imageModel = (modelId) => { return new GatewayImageModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.languageModel = createLanguageModel; provider.textEmbeddingModel = (modelId) => { return new GatewayEmbeddingModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.tools = gatewayTools; return provider; } var gateway = createGatewayProvider(); async function getGatewayAuthToken(options) { const apiKey = loadOptionalSetting({ settingValue: options.apiKey, environmentVariableName: "AI_GATEWAY_API_KEY" }); if (apiKey) { return { token: apiKey, authMethod: "api-key" }; } try { const oidcToken = await getVercelOidcToken(); return { token: oidcToken, authMethod: "oidc" }; } catch (e2) { return null; } } var _globalThis2 = typeof globalThis === "object" ? globalThis : global; var VERSION22 = "1.9.0"; var re2 = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; function _makeCompatibilityCheck2(ownVersion) { var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); var rejectedVersions = /* @__PURE__ */ new Set(); var myVersionMatch = ownVersion.match(re2); if (!myVersionMatch) { return function() { return false; }; } var ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], prerelease: myVersionMatch[4] }; if (ownVersionParsed.prerelease != null) { return function isExactmatch(globalVersion) { return globalVersion === ownVersion; }; } function _reject(v) { rejectedVersions.add(v); return false; } function _accept(v) { acceptedVersions.add(v); return true; } return function isCompatible22(globalVersion) { if (acceptedVersions.has(globalVersion)) { return true; } if (rejectedVersions.has(globalVersion)) { return false; } var globalVersionMatch = globalVersion.match(re2); if (!globalVersionMatch) { return _reject(globalVersion); } var globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], prerelease: globalVersionMatch[4] }; if (globalVersionParsed.prerelease != null) { return _reject(globalVersion); } if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); } if (ownVersionParsed.major === 0) { if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { return _accept(globalVersion); } return _reject(globalVersion); } if (ownVersionParsed.minor <= globalVersionParsed.minor) { return _accept(globalVersion); } return _reject(globalVersion); }; } var isCompatible2 = _makeCompatibilityCheck2(VERSION22); var major2 = VERSION22.split(".")[0]; var GLOBAL_OPENTELEMETRY_API_KEY2 = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major2); var _global2 = _globalThis2; function registerGlobal2(type, instance, diag, allowOverride) { var _a163; if (allowOverride === void 0) { allowOverride = false; } var api = _global2[GLOBAL_OPENTELEMETRY_API_KEY2] = (_a163 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) !== null && _a163 !== void 0 ? _a163 : { version: VERSION22 }; if (!allowOverride && api[type]) { var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); diag.error(err.stack || err.message); return false; } if (api.version !== VERSION22) { var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION22); diag.error(err.stack || err.message); return false; } api[type] = instance; diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION22 + "."); return true; } function getGlobal2(type) { var _a163, _b93; var globalVersion = (_a163 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _a163 === void 0 ? void 0 : _a163.version; if (!globalVersion || !isCompatible2(globalVersion)) { return; } return (_b93 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _b93 === void 0 ? void 0 : _b93[type]; } function unregisterGlobal2(type, diag) { diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION22 + "."); var api = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]; if (api) { delete api[type]; } } var __read5 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray5 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var DiagComponentLogger2 = ( /** @class */ (function() { function DiagComponentLogger22(props) { this._namespace = props.namespace || "DiagComponentLogger"; } DiagComponentLogger22.prototype.debug = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy2("debug", this._namespace, args); }; DiagComponentLogger22.prototype.error = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy2("error", this._namespace, args); }; DiagComponentLogger22.prototype.info = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy2("info", this._namespace, args); }; DiagComponentLogger22.prototype.warn = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy2("warn", this._namespace, args); }; DiagComponentLogger22.prototype.verbose = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy2("verbose", this._namespace, args); }; return DiagComponentLogger22; })() ); function logProxy2(funcName, namespace, args) { var logger = getGlobal2("diag"); if (!logger) { return; } args.unshift(namespace); return logger[funcName].apply(logger, __spreadArray5([], __read5(args), false)); } var DiagLogLevel2; (function(DiagLogLevel22) { DiagLogLevel22[DiagLogLevel22["NONE"] = 0] = "NONE"; DiagLogLevel22[DiagLogLevel22["ERROR"] = 30] = "ERROR"; DiagLogLevel22[DiagLogLevel22["WARN"] = 50] = "WARN"; DiagLogLevel22[DiagLogLevel22["INFO"] = 60] = "INFO"; DiagLogLevel22[DiagLogLevel22["DEBUG"] = 70] = "DEBUG"; DiagLogLevel22[DiagLogLevel22["VERBOSE"] = 80] = "VERBOSE"; DiagLogLevel22[DiagLogLevel22["ALL"] = 9999] = "ALL"; })(DiagLogLevel2 || (DiagLogLevel2 = {})); function createLogLevelDiagLogger2(maxLevel, logger) { if (maxLevel < DiagLogLevel2.NONE) { maxLevel = DiagLogLevel2.NONE; } else if (maxLevel > DiagLogLevel2.ALL) { maxLevel = DiagLogLevel2.ALL; } logger = logger || {}; function _filterFunc(funcName, theLevel) { var theFunc = logger[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { return theFunc.bind(logger); } return function() { }; } return { error: _filterFunc("error", DiagLogLevel2.ERROR), warn: _filterFunc("warn", DiagLogLevel2.WARN), info: _filterFunc("info", DiagLogLevel2.INFO), debug: _filterFunc("debug", DiagLogLevel2.DEBUG), verbose: _filterFunc("verbose", DiagLogLevel2.VERBOSE) }; } var __read22 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray22 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME4 = "diag"; var DiagAPI2 = ( /** @class */ (function() { function DiagAPI22() { function _logProxy(funcName) { return function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var logger = getGlobal2("diag"); if (!logger) return; return logger[funcName].apply(logger, __spreadArray22([], __read22(args), false)); }; } var self = this; var setLogger = function(logger, optionsOrLogLevel) { var _a163, _b93, _c; if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel2.INFO }; } if (logger === self) { var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self.error((_a163 = err.stack) !== null && _a163 !== void 0 ? _a163 : err.message); return false; } if (typeof optionsOrLogLevel === "number") { optionsOrLogLevel = { logLevel: optionsOrLogLevel }; } var oldLogger = getGlobal2("diag"); var newLogger = createLogLevelDiagLogger2((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel2.INFO, logger); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn("Current logger will be overwritten from " + stack); newLogger.warn("Current logger will overwrite one already registered from " + stack); } return registerGlobal2("diag", newLogger, self, true); }; self.setLogger = setLogger; self.disable = function() { unregisterGlobal2(API_NAME4, self); }; self.createComponentLogger = function(options) { return new DiagComponentLogger2(options); }; self.verbose = _logProxy("verbose"); self.debug = _logProxy("debug"); self.info = _logProxy("info"); self.warn = _logProxy("warn"); self.error = _logProxy("error"); } DiagAPI22.instance = function() { if (!this._instance) { this._instance = new DiagAPI22(); } return this._instance; }; return DiagAPI22; })() ); function createContextKey2(description) { return Symbol.for(description); } var BaseContext2 = ( /** @class */ /* @__PURE__ */ (function() { function BaseContext22(parentContext) { var self = this; self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); self.getValue = function(key) { return self._currentContext.get(key); }; self.setValue = function(key, value) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.set(key, value); return context2; }; self.deleteValue = function(key) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.delete(key); return context2; }; } return BaseContext22; })() ); var ROOT_CONTEXT2 = new BaseContext2(); var __read32 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray32 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var NoopContextManager2 = ( /** @class */ (function() { function NoopContextManager22() { } NoopContextManager22.prototype.active = function() { return ROOT_CONTEXT2; }; NoopContextManager22.prototype.with = function(_context, fn, thisArg) { var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return fn.call.apply(fn, __spreadArray32([thisArg], __read32(args), false)); }; NoopContextManager22.prototype.bind = function(_context, target) { return target; }; NoopContextManager22.prototype.enable = function() { return this; }; NoopContextManager22.prototype.disable = function() { return this; }; return NoopContextManager22; })() ); var __read42 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray42 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME22 = "context"; var NOOP_CONTEXT_MANAGER2 = new NoopContextManager2(); var ContextAPI2 = ( /** @class */ (function() { function ContextAPI22() { } ContextAPI22.getInstance = function() { if (!this._instance) { this._instance = new ContextAPI22(); } return this._instance; }; ContextAPI22.prototype.setGlobalContextManager = function(contextManager) { return registerGlobal2(API_NAME22, contextManager, DiagAPI2.instance()); }; ContextAPI22.prototype.active = function() { return this._getContextManager().active(); }; ContextAPI22.prototype.with = function(context2, fn, thisArg) { var _a163; var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return (_a163 = this._getContextManager()).with.apply(_a163, __spreadArray42([context2, fn, thisArg], __read42(args), false)); }; ContextAPI22.prototype.bind = function(context2, target) { return this._getContextManager().bind(context2, target); }; ContextAPI22.prototype._getContextManager = function() { return getGlobal2(API_NAME22) || NOOP_CONTEXT_MANAGER2; }; ContextAPI22.prototype.disable = function() { this._getContextManager().disable(); unregisterGlobal2(API_NAME22, DiagAPI2.instance()); }; return ContextAPI22; })() ); var TraceFlags2; (function(TraceFlags22) { TraceFlags22[TraceFlags22["NONE"] = 0] = "NONE"; TraceFlags22[TraceFlags22["SAMPLED"] = 1] = "SAMPLED"; })(TraceFlags2 || (TraceFlags2 = {})); var INVALID_SPANID2 = "0000000000000000"; var INVALID_TRACEID2 = "00000000000000000000000000000000"; var INVALID_SPAN_CONTEXT2 = { traceId: INVALID_TRACEID2, spanId: INVALID_SPANID2, traceFlags: TraceFlags2.NONE }; var NonRecordingSpan2 = ( /** @class */ (function() { function NonRecordingSpan22(_spanContext) { if (_spanContext === void 0) { _spanContext = INVALID_SPAN_CONTEXT2; } this._spanContext = _spanContext; } NonRecordingSpan22.prototype.spanContext = function() { return this._spanContext; }; NonRecordingSpan22.prototype.setAttribute = function(_key, _value) { return this; }; NonRecordingSpan22.prototype.setAttributes = function(_attributes) { return this; }; NonRecordingSpan22.prototype.addEvent = function(_name, _attributes) { return this; }; NonRecordingSpan22.prototype.addLink = function(_link) { return this; }; NonRecordingSpan22.prototype.addLinks = function(_links) { return this; }; NonRecordingSpan22.prototype.setStatus = function(_status) { return this; }; NonRecordingSpan22.prototype.updateName = function(_name) { return this; }; NonRecordingSpan22.prototype.end = function(_endTime) { }; NonRecordingSpan22.prototype.isRecording = function() { return false; }; NonRecordingSpan22.prototype.recordException = function(_exception, _time) { }; return NonRecordingSpan22; })() ); var SPAN_KEY2 = createContextKey2("OpenTelemetry Context Key SPAN"); function getSpan2(context2) { return context2.getValue(SPAN_KEY2) || void 0; } function getActiveSpan2() { return getSpan2(ContextAPI2.getInstance().active()); } function setSpan2(context2, span) { return context2.setValue(SPAN_KEY2, span); } function deleteSpan2(context2) { return context2.deleteValue(SPAN_KEY2); } function setSpanContext2(context2, spanContext) { return setSpan2(context2, new NonRecordingSpan2(spanContext)); } function getSpanContext2(context2) { var _a163; return (_a163 = getSpan2(context2)) === null || _a163 === void 0 ? void 0 : _a163.spanContext(); } var VALID_TRACEID_REGEX2 = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX2 = /^[0-9a-f]{16}$/i; function isValidTraceId2(traceId) { return VALID_TRACEID_REGEX2.test(traceId) && traceId !== INVALID_TRACEID2; } function isValidSpanId2(spanId) { return VALID_SPANID_REGEX2.test(spanId) && spanId !== INVALID_SPANID2; } function isSpanContextValid2(spanContext) { return isValidTraceId2(spanContext.traceId) && isValidSpanId2(spanContext.spanId); } function wrapSpanContext2(spanContext) { return new NonRecordingSpan2(spanContext); } var contextApi2 = ContextAPI2.getInstance(); var NoopTracer2 = ( /** @class */ (function() { function NoopTracer22() { } NoopTracer22.prototype.startSpan = function(name163, options, context2) { if (context2 === void 0) { context2 = contextApi2.active(); } var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan2(); } var parentFromContext = context2 && getSpanContext2(context2); if (isSpanContext2(parentFromContext) && isSpanContextValid2(parentFromContext)) { return new NonRecordingSpan2(parentFromContext); } else { return new NonRecordingSpan2(); } }; NoopTracer22.prototype.startActiveSpan = function(name163, arg2, arg3, arg4) { var opts; var ctx; var fn; if (arguments.length < 2) { return; } else if (arguments.length === 2) { fn = arg2; } else if (arguments.length === 3) { opts = arg2; fn = arg3; } else { opts = arg2; ctx = arg3; fn = arg4; } var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi2.active(); var span = this.startSpan(name163, opts, parentContext); var contextWithSpanSet = setSpan2(parentContext, span); return contextApi2.with(contextWithSpanSet, fn, void 0, span); }; return NoopTracer22; })() ); function isSpanContext2(spanContext) { return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; } var NOOP_TRACER2 = new NoopTracer2(); var ProxyTracer2 = ( /** @class */ (function() { function ProxyTracer22(_provider, name163, version3, options) { this._provider = _provider; this.name = name163; this.version = version3; this.options = options; } ProxyTracer22.prototype.startSpan = function(name163, options, context2) { return this._getTracer().startSpan(name163, options, context2); }; ProxyTracer22.prototype.startActiveSpan = function(_name, _options, _context, _fn) { var tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); }; ProxyTracer22.prototype._getTracer = function() { if (this._delegate) { return this._delegate; } var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER2; } this._delegate = tracer; return this._delegate; }; return ProxyTracer22; })() ); var NoopTracerProvider2 = ( /** @class */ (function() { function NoopTracerProvider22() { } NoopTracerProvider22.prototype.getTracer = function(_name, _version, _options) { return new NoopTracer2(); }; return NoopTracerProvider22; })() ); var NOOP_TRACER_PROVIDER2 = new NoopTracerProvider2(); var ProxyTracerProvider2 = ( /** @class */ (function() { function ProxyTracerProvider22() { } ProxyTracerProvider22.prototype.getTracer = function(name163, version3, options) { var _a163; return (_a163 = this.getDelegateTracer(name163, version3, options)) !== null && _a163 !== void 0 ? _a163 : new ProxyTracer2(this, name163, version3, options); }; ProxyTracerProvider22.prototype.getDelegate = function() { var _a163; return (_a163 = this._delegate) !== null && _a163 !== void 0 ? _a163 : NOOP_TRACER_PROVIDER2; }; ProxyTracerProvider22.prototype.setDelegate = function(delegate) { this._delegate = delegate; }; ProxyTracerProvider22.prototype.getDelegateTracer = function(name163, version3, options) { var _a163; return (_a163 = this._delegate) === null || _a163 === void 0 ? void 0 : _a163.getTracer(name163, version3, options); }; return ProxyTracerProvider22; })() ); var SpanStatusCode2; (function(SpanStatusCode22) { SpanStatusCode22[SpanStatusCode22["UNSET"] = 0] = "UNSET"; SpanStatusCode22[SpanStatusCode22["OK"] = 1] = "OK"; SpanStatusCode22[SpanStatusCode22["ERROR"] = 2] = "ERROR"; })(SpanStatusCode2 || (SpanStatusCode2 = {})); var API_NAME32 = "trace"; var TraceAPI2 = ( /** @class */ (function() { function TraceAPI22() { this._proxyTracerProvider = new ProxyTracerProvider2(); this.wrapSpanContext = wrapSpanContext2; this.isSpanContextValid = isSpanContextValid2; this.deleteSpan = deleteSpan2; this.getSpan = getSpan2; this.getActiveSpan = getActiveSpan2; this.getSpanContext = getSpanContext2; this.setSpan = setSpan2; this.setSpanContext = setSpanContext2; } TraceAPI22.getInstance = function() { if (!this._instance) { this._instance = new TraceAPI22(); } return this._instance; }; TraceAPI22.prototype.setGlobalTracerProvider = function(provider) { var success3 = registerGlobal2(API_NAME32, this._proxyTracerProvider, DiagAPI2.instance()); if (success3) { this._proxyTracerProvider.setDelegate(provider); } return success3; }; TraceAPI22.prototype.getTracerProvider = function() { return getGlobal2(API_NAME32) || this._proxyTracerProvider; }; TraceAPI22.prototype.getTracer = function(name163, version3) { return this.getTracerProvider().getTracer(name163, version3); }; TraceAPI22.prototype.disable = function() { unregisterGlobal2(API_NAME32, DiagAPI2.instance()); this._proxyTracerProvider = new ProxyTracerProvider2(); }; return TraceAPI22; })() ); var trace2 = TraceAPI2.getInstance(); var __defProp3 = Object.defineProperty; var __export3 = (target, all) => { for (var name163 in all) __defProp3(target, name163, { get: all[name163], enumerable: true }); }; var name222 = "AI_InvalidArgumentError"; var marker222 = `vercel.ai.error.${name222}`; var symbol222 = Symbol.for(marker222); var _a222; var InvalidArgumentError22 = class extends AISDKError2 { constructor({ parameter, value, message }) { super({ name: name222, message: `Invalid argument for parameter ${parameter}: ${message}` }); this[_a222] = true; this.parameter = parameter; this.value = value; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker222); } }; _a222 = symbol222; var name622 = "AI_NoObjectGeneratedError"; var marker622 = `vercel.ai.error.${name622}`; var symbol622 = Symbol.for(marker622); var _a622; var NoObjectGeneratedError2 = class extends AISDKError2 { constructor({ message = "No object generated.", cause, text: text22, response, usage, finishReason }) { super({ name: name622, message, cause }); this[_a622] = true; this.text = text22; this.response = response; this.usage = usage; this.finishReason = finishReason; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker622); } }; _a622 = symbol622; var UnsupportedModelVersionError2 = class extends AISDKError2 { constructor(options) { super({ name: "AI_UnsupportedModelVersionError", message: `Unsupported model version ${options.version} for provider "${options.provider}" and model "${options.modelId}". AI SDK 5 only supports models that implement specification version "v2".` }); this.version = options.version; this.provider = options.provider; this.modelId = options.modelId; } }; var name143 = "AI_RetryError"; var marker144 = `vercel.ai.error.${name143}`; var symbol144 = Symbol.for(marker144); var _a144; var RetryError2 = class extends AISDKError2 { constructor({ message, reason, errors }) { super({ name: name143, message }); this[_a144] = true; this.reason = reason; this.errors = errors; this.lastError = errors[errors.length - 1]; } static isInstance(error90) { return AISDKError2.hasMarker(error90, marker144); } }; _a144 = symbol144; function resolveEmbeddingModel(model) { if (typeof model !== "string") { if (model.specificationVersion !== "v2") { throw new UnsupportedModelVersionError2({ version: model.specificationVersion, provider: model.provider, modelId: model.modelId }); } return model; } return getGlobalProvider().textEmbeddingModel( model ); } function getGlobalProvider() { var _a163; return (_a163 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a163 : gateway; } var VERSION32 = "5.0.186"; var dataContentSchema2 = external_exports2.union([ external_exports2.string(), external_exports2.instanceof(Uint8Array), external_exports2.instanceof(ArrayBuffer), external_exports2.custom( // Buffer might not be available in some environments such as CloudFlare: (value) => { var _a163, _b93; return (_b93 = (_a163 = globalThis.Buffer) == null ? void 0 : _a163.isBuffer(value)) != null ? _b93 : false; }, { message: "Must be a Buffer" } ) ]); var jsonValueSchema2 = external_exports2.lazy( () => external_exports2.union([ external_exports2.null(), external_exports2.string(), external_exports2.number(), external_exports2.boolean(), external_exports2.record(external_exports2.string(), jsonValueSchema2), external_exports2.array(jsonValueSchema2) ]) ); var providerMetadataSchema2 = external_exports2.record( external_exports2.string(), external_exports2.record(external_exports2.string(), jsonValueSchema2) ); var textPartSchema2 = external_exports2.object({ type: external_exports2.literal("text"), text: external_exports2.string(), providerOptions: providerMetadataSchema2.optional() }); var imagePartSchema2 = external_exports2.object({ type: external_exports2.literal("image"), image: external_exports2.union([dataContentSchema2, external_exports2.instanceof(URL)]), mediaType: external_exports2.string().optional(), providerOptions: providerMetadataSchema2.optional() }); var filePartSchema2 = external_exports2.object({ type: external_exports2.literal("file"), data: external_exports2.union([dataContentSchema2, external_exports2.instanceof(URL)]), filename: external_exports2.string().optional(), mediaType: external_exports2.string(), providerOptions: providerMetadataSchema2.optional() }); var reasoningPartSchema2 = external_exports2.object({ type: external_exports2.literal("reasoning"), text: external_exports2.string(), providerOptions: providerMetadataSchema2.optional() }); var toolCallPartSchema2 = external_exports2.object({ type: external_exports2.literal("tool-call"), toolCallId: external_exports2.string(), toolName: external_exports2.string(), input: external_exports2.unknown(), providerOptions: providerMetadataSchema2.optional(), providerExecuted: external_exports2.boolean().optional() }); var outputSchema = external_exports2.discriminatedUnion("type", [ external_exports2.object({ type: external_exports2.literal("text"), value: external_exports2.string() }), external_exports2.object({ type: external_exports2.literal("json"), value: jsonValueSchema2 }), external_exports2.object({ type: external_exports2.literal("error-text"), value: external_exports2.string() }), external_exports2.object({ type: external_exports2.literal("error-json"), value: jsonValueSchema2 }), external_exports2.object({ type: external_exports2.literal("content"), value: external_exports2.array( external_exports2.union([ external_exports2.object({ type: external_exports2.literal("text"), text: external_exports2.string() }), external_exports2.object({ type: external_exports2.literal("media"), data: external_exports2.string(), mediaType: external_exports2.string() }) ]) ) }) ]); var toolResultPartSchema2 = external_exports2.object({ type: external_exports2.literal("tool-result"), toolCallId: external_exports2.string(), toolName: external_exports2.string(), output: outputSchema, providerOptions: providerMetadataSchema2.optional() }); var systemModelMessageSchema = external_exports2.object( { role: external_exports2.literal("system"), content: external_exports2.string(), providerOptions: providerMetadataSchema2.optional() } ); var userModelMessageSchema = external_exports2.object({ role: external_exports2.literal("user"), content: external_exports2.union([ external_exports2.string(), external_exports2.array(external_exports2.union([textPartSchema2, imagePartSchema2, filePartSchema2])) ]), providerOptions: providerMetadataSchema2.optional() }); var assistantModelMessageSchema = external_exports2.object({ role: external_exports2.literal("assistant"), content: external_exports2.union([ external_exports2.string(), external_exports2.array( external_exports2.union([ textPartSchema2, filePartSchema2, reasoningPartSchema2, toolCallPartSchema2, toolResultPartSchema2 ]) ) ]), providerOptions: providerMetadataSchema2.optional() }); var toolModelMessageSchema = external_exports2.object({ role: external_exports2.literal("tool"), content: external_exports2.array(toolResultPartSchema2), providerOptions: providerMetadataSchema2.optional() }); external_exports2.union([ systemModelMessageSchema, userModelMessageSchema, assistantModelMessageSchema, toolModelMessageSchema ]); function assembleOperationName2({ operationId, telemetry }) { return { // standardized operation and resource name: "operation.name": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`, "resource.name": telemetry == null ? void 0 : telemetry.functionId, // detailed, AI SDK specific data: "ai.operationId": operationId, "ai.telemetry.functionId": telemetry == null ? void 0 : telemetry.functionId }; } function getBaseTelemetryAttributes2({ model, settings, telemetry, headers }) { var _a163; return { "ai.model.provider": model.provider, "ai.model.id": model.modelId, // settings: ...Object.entries(settings).reduce((attributes, [key, value]) => { attributes[`ai.settings.${key}`] = value; return attributes; }, {}), // add metadata as attributes: ...Object.entries((_a163 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a163 : {}).reduce( (attributes, [key, value]) => { attributes[`ai.telemetry.metadata.${key}`] = value; return attributes; }, {} ), // request headers ...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => { if (value !== void 0) { attributes[`ai.request.headers.${key}`] = value; } return attributes; }, {}) }; } var noopTracer2 = { startSpan() { return noopSpan2; }, startActiveSpan(name163, arg1, arg2, arg3) { if (typeof arg1 === "function") { return arg1(noopSpan2); } if (typeof arg2 === "function") { return arg2(noopSpan2); } if (typeof arg3 === "function") { return arg3(noopSpan2); } } }; var noopSpan2 = { spanContext() { return noopSpanContext2; }, setAttribute() { return this; }, setAttributes() { return this; }, addEvent() { return this; }, addLink() { return this; }, addLinks() { return this; }, setStatus() { return this; }, updateName() { return this; }, end() { return this; }, isRecording() { return false; }, recordException() { return this; } }; var noopSpanContext2 = { traceId: "", spanId: "", traceFlags: 0 }; function getTracer2({ isEnabled = false, tracer } = {}) { if (!isEnabled) { return noopTracer2; } if (tracer) { return tracer; } return trace2.getTracer("ai"); } function recordSpan2({ name: name163, tracer, attributes, fn, endWhenDone = true }) { return tracer.startActiveSpan(name163, { attributes }, async (span) => { try { const result = await fn(span); if (endWhenDone) { span.end(); } return result; } catch (error90) { try { recordErrorOnSpan2(span, error90); } finally { span.end(); } throw error90; } }); } function recordErrorOnSpan2(span, error90) { if (error90 instanceof Error) { span.recordException({ name: error90.name, message: error90.message, stack: error90.stack }); span.setStatus({ code: SpanStatusCode2.ERROR, message: error90.message }); } else { span.setStatus({ code: SpanStatusCode2.ERROR }); } } function selectTelemetryAttributes2({ telemetry, attributes }) { if ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) { return {}; } return Object.entries(attributes).reduce((attributes2, [key, value]) => { if (value == null) { return attributes2; } if (typeof value === "object" && "input" in value && typeof value.input === "function") { if ((telemetry == null ? void 0 : telemetry.recordInputs) === false) { return attributes2; } const result = value.input(); return result == null ? attributes2 : { ...attributes2, [key]: result }; } if (typeof value === "object" && "output" in value && typeof value.output === "function") { if ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) { return attributes2; } const result = value.output(); return result == null ? attributes2 : { ...attributes2, [key]: result }; } return { ...attributes2, [key]: value }; }, {}); } function getRetryDelayInMs({ error: error90, exponentialBackoffDelay }) { const headers = error90.responseHeaders; if (!headers) return exponentialBackoffDelay; let ms; const retryAfterMs = headers["retry-after-ms"]; if (retryAfterMs) { const timeoutMs = parseFloat(retryAfterMs); if (!Number.isNaN(timeoutMs)) { ms = timeoutMs; } } const retryAfter = headers["retry-after"]; if (retryAfter && ms === void 0) { const timeoutSeconds = parseFloat(retryAfter); if (!Number.isNaN(timeoutSeconds)) { ms = timeoutSeconds * 1e3; } else { ms = Date.parse(retryAfter) - Date.now(); } } if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) { return ms; } return exponentialBackoffDelay; } var retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal } = {}) => async (f) => _retryWithExponentialBackoff2(f, { maxRetries, delayInMs: initialDelayInMs, backoffFactor, abortSignal }); async function _retryWithExponentialBackoff2(f, { maxRetries, delayInMs, backoffFactor, abortSignal }, errors = []) { try { return await f(); } catch (error90) { if (isAbortError2(error90)) { throw error90; } if (maxRetries === 0) { throw error90; } const errorMessage = getErrorMessage22(error90); const newErrors = [...errors, error90]; const tryNumber = newErrors.length; if (tryNumber > maxRetries) { throw new RetryError2({ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`, reason: "maxRetriesExceeded", errors: newErrors }); } if (error90 instanceof Error && APICallError2.isInstance(error90) && error90.isRetryable === true && tryNumber <= maxRetries) { await delay2( getRetryDelayInMs({ error: error90, exponentialBackoffDelay: delayInMs }), { abortSignal } ); return _retryWithExponentialBackoff2( f, { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor, abortSignal }, newErrors ); } if (tryNumber === 1) { throw error90; } throw new RetryError2({ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`, reason: "errorNotRetryable", errors: newErrors }); } } function prepareRetries2({ maxRetries, abortSignal }) { if (maxRetries != null) { if (!Number.isInteger(maxRetries)) { throw new InvalidArgumentError22({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be an integer" }); } if (maxRetries < 0) { throw new InvalidArgumentError22({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be >= 0" }); } } const maxRetriesResult = maxRetries != null ? maxRetries : 2; return { maxRetries: maxRetriesResult, retry: retryWithExponentialBackoffRespectingRetryHeaders({ maxRetries: maxRetriesResult, abortSignal }) }; } createIdGenerator2({ prefix: "aitxt", size: 24 }); function fixJson2(input) { const stack = ["ROOT"]; let lastValidIndex = -1; let literalStart = null; function processValueStart(char, i, swapState) { { switch (char) { case '"': { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_STRING"); break; } case "f": case "t": case "n": { lastValidIndex = i; literalStart = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_LITERAL"); break; } case "-": { stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "{": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_OBJECT_START"); break; } case "[": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_ARRAY_START"); break; } } } } function processAfterObjectValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_COMMA"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } } function processAfterArrayValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } } } for (let i = 0; i < input.length; i++) { const char = input[i]; const currentState = stack[stack.length - 1]; switch (currentState) { case "ROOT": processValueStart(char, i, "FINISH"); break; case "INSIDE_OBJECT_START": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } break; } case "INSIDE_OBJECT_AFTER_COMMA": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } } break; } case "INSIDE_OBJECT_KEY": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_KEY"); break; } } break; } case "INSIDE_OBJECT_AFTER_KEY": { switch (char) { case ":": { stack.pop(); stack.push("INSIDE_OBJECT_BEFORE_VALUE"); break; } } break; } case "INSIDE_OBJECT_BEFORE_VALUE": { processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE"); break; } case "INSIDE_OBJECT_AFTER_VALUE": { processAfterObjectValue(char, i); break; } case "INSIDE_STRING": { switch (char) { case '"': { stack.pop(); lastValidIndex = i; break; } case "\\": { stack.push("INSIDE_STRING_ESCAPE"); break; } default: { lastValidIndex = i; } } break; } case "INSIDE_ARRAY_START": { switch (char) { case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } } break; } case "INSIDE_ARRAY_AFTER_VALUE": { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; break; } } break; } case "INSIDE_ARRAY_AFTER_COMMA": { processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } case "INSIDE_STRING_ESCAPE": { stack.pop(); lastValidIndex = i; break; } case "INSIDE_NUMBER": { switch (char) { case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; break; } case "e": case "E": case "-": case ".": { break; } case ",": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "}": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "]": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } break; } default: { stack.pop(); break; } } break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, i + 1); if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } } else { lastValidIndex = i; } break; } } } let result = input.slice(0, lastValidIndex + 1); for (let i = stack.length - 1; i >= 0; i--) { const state = stack[i]; switch (state) { case "INSIDE_STRING": { result += '"'; break; } case "INSIDE_OBJECT_KEY": case "INSIDE_OBJECT_AFTER_KEY": case "INSIDE_OBJECT_AFTER_COMMA": case "INSIDE_OBJECT_START": case "INSIDE_OBJECT_BEFORE_VALUE": case "INSIDE_OBJECT_AFTER_VALUE": { result += "}"; break; } case "INSIDE_ARRAY_START": case "INSIDE_ARRAY_AFTER_COMMA": case "INSIDE_ARRAY_AFTER_VALUE": { result += "]"; break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, input.length); if ("true".startsWith(partialLiteral)) { result += "true".slice(partialLiteral.length); } else if ("false".startsWith(partialLiteral)) { result += "false".slice(partialLiteral.length); } else if ("null".startsWith(partialLiteral)) { result += "null".slice(partialLiteral.length); } } } } return result; } async function parsePartialJson2(jsonText) { if (jsonText === void 0) { return { value: void 0, state: "undefined-input" }; } let result = await safeParseJSON2({ text: jsonText }); if (result.success) { return { value: result.value, state: "successful-parse" }; } result = await safeParseJSON2({ text: fixJson2(jsonText) }); if (result.success) { return { value: result.value, state: "repaired-parse" }; } return { value: void 0, state: "failed-parse" }; } createIdGenerator2({ prefix: "aitxt", size: 24 }); function splitArray2(array4, chunkSize) { if (chunkSize <= 0) { throw new Error("chunkSize must be greater than 0"); } const result = []; for (let i = 0; i < array4.length; i += chunkSize) { result.push(array4.slice(i, i + chunkSize)); } return result; } async function embedMany2({ model: modelArg, values, maxParallelCalls = Infinity, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry }) { const model = resolveEmbeddingModel(modelArg); const { maxRetries, retry } = prepareRetries2({ maxRetries: maxRetriesArg, abortSignal }); const headersWithUserAgent = withUserAgentSuffix( headers != null ? headers : {}, `ai/${VERSION32}` ); const baseTelemetryAttributes = getBaseTelemetryAttributes2({ model, telemetry, headers: headersWithUserAgent, settings: { maxRetries } }); const tracer = getTracer2(telemetry); return recordSpan2({ name: "ai.embedMany", attributes: selectTelemetryAttributes2({ telemetry, attributes: { ...assembleOperationName2({ operationId: "ai.embedMany", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => values.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (span) => { var _a163; const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([ model.maxEmbeddingsPerCall, model.supportsParallelCalls ]); if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) { const { embeddings: embeddings2, usage, response, providerMetadata: providerMetadata2 } = await retry( () => { return recordSpan2({ name: "ai.embedMany.doEmbed", attributes: selectTelemetryAttributes2({ telemetry, attributes: { ...assembleOperationName2({ operationId: "ai.embedMany.doEmbed", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => values.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (doEmbedSpan) => { var _a173; const modelResponse = await model.doEmbed({ values, abortSignal, headers: headersWithUserAgent, providerOptions }); const embeddings3 = modelResponse.embeddings; const usage2 = (_a173 = modelResponse.usage) != null ? _a173 : { tokens: NaN }; doEmbedSpan.setAttributes( selectTelemetryAttributes2({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings3.map( (embedding) => JSON.stringify(embedding) ) }, "ai.usage.tokens": usage2.tokens } }) ); return { embeddings: embeddings3, usage: usage2, providerMetadata: modelResponse.providerMetadata, response: modelResponse.response }; } }); } ); span.setAttributes( selectTelemetryAttributes2({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": usage.tokens } }) ); return new DefaultEmbedManyResult2({ values, embeddings: embeddings2, usage, providerMetadata: providerMetadata2, responses: [response] }); } const valueChunks = splitArray2(values, maxEmbeddingsPerCall); const embeddings = []; const responses = []; let tokens = 0; let providerMetadata; const parallelChunks = splitArray2( valueChunks, supportsParallelCalls ? maxParallelCalls : 1 ); for (const parallelChunk of parallelChunks) { const results = await Promise.all( parallelChunk.map((chunk) => { return retry(() => { return recordSpan2({ name: "ai.embedMany.doEmbed", attributes: selectTelemetryAttributes2({ telemetry, attributes: { ...assembleOperationName2({ operationId: "ai.embedMany.doEmbed", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => chunk.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (doEmbedSpan) => { var _a173; const modelResponse = await model.doEmbed({ values: chunk, abortSignal, headers: headersWithUserAgent, providerOptions }); const embeddings2 = modelResponse.embeddings; const usage = (_a173 = modelResponse.usage) != null ? _a173 : { tokens: NaN }; doEmbedSpan.setAttributes( selectTelemetryAttributes2({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings2.map( (embedding) => JSON.stringify(embedding) ) }, "ai.usage.tokens": usage.tokens } }) ); return { embeddings: embeddings2, usage, providerMetadata: modelResponse.providerMetadata, response: modelResponse.response }; } }); }); }) ); for (const result of results) { embeddings.push(...result.embeddings); responses.push(result.response); tokens += result.usage.tokens; if (result.providerMetadata) { if (!providerMetadata) { providerMetadata = { ...result.providerMetadata }; } else { for (const [providerName, metadata] of Object.entries( result.providerMetadata )) { providerMetadata[providerName] = { ...(_a163 = providerMetadata[providerName]) != null ? _a163 : {}, ...metadata }; } } } } } span.setAttributes( selectTelemetryAttributes2({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": tokens } }) ); return new DefaultEmbedManyResult2({ values, embeddings, usage: { tokens }, providerMetadata, responses }); } }); } var DefaultEmbedManyResult2 = class { constructor(options) { this.values = options.values; this.embeddings = options.embeddings; this.usage = options.usage; this.providerMetadata = options.providerMetadata; this.responses = options.responses; } }; createIdGenerator2({ prefix: "aiobj", size: 24 }); createIdGenerator2({ prefix: "aiobj", size: 24 }); var output_exports2 = {}; __export3(output_exports2, { object: () => object3, text: () => text2 }); var text2 = () => ({ type: "text", responseFormat: { type: "text" }, async parsePartial({ text: text22 }) { return { partial: text22 }; }, async parseOutput({ text: text22 }) { return text22; } }); var object3 = ({ schema: inputSchema }) => { const schema = asSchema2(inputSchema); return { type: "object", responseFormat: { type: "json", schema: schema.jsonSchema }, async parsePartial({ text: text22 }) { const result = await parsePartialJson2(text22); switch (result.state) { case "failed-parse": case "undefined-input": return void 0; case "repaired-parse": case "successful-parse": return { // Note: currently no validation of partial results: partial: result.value }; default: { const _exhaustiveCheck = result.state; throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`); } } }, async parseOutput({ text: text22 }, context2) { const parseResult = await safeParseJSON2({ text: text22 }); if (!parseResult.success) { throw new NoObjectGeneratedError2({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } const validationResult = await safeValidateTypes2({ value: parseResult.value, schema }); if (!validationResult.success) { throw new NoObjectGeneratedError2({ message: "No object generated: response did not match schema.", cause: validationResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } return validationResult.value; } }; }; var external_exports3 = {}; __export(external_exports3, { $brand: () => $brand2, $input: () => $input2, $output: () => $output2, NEVER: () => NEVER3, TimePrecision: () => TimePrecision2, ZodAny: () => ZodAny4, ZodArray: () => ZodArray4, ZodBase64: () => ZodBase642, ZodBase64URL: () => ZodBase64URL2, ZodBigInt: () => ZodBigInt4, ZodBigIntFormat: () => ZodBigIntFormat2, ZodBoolean: () => ZodBoolean4, ZodCIDRv4: () => ZodCIDRv42, ZodCIDRv6: () => ZodCIDRv62, ZodCUID: () => ZodCUID3, ZodCUID2: () => ZodCUID22, ZodCatch: () => ZodCatch4, ZodCustom: () => ZodCustom2, ZodCustomStringFormat: () => ZodCustomStringFormat2, ZodDate: () => ZodDate4, ZodDefault: () => ZodDefault4, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion4, ZodE164: () => ZodE1642, ZodEmail: () => ZodEmail2, ZodEmoji: () => ZodEmoji2, ZodEnum: () => ZodEnum4, ZodError: () => ZodError4, ZodFile: () => ZodFile2, ZodGUID: () => ZodGUID2, ZodIPv4: () => ZodIPv42, ZodIPv6: () => ZodIPv62, ZodISODate: () => ZodISODate2, ZodISODateTime: () => ZodISODateTime2, ZodISODuration: () => ZodISODuration2, ZodISOTime: () => ZodISOTime2, ZodIntersection: () => ZodIntersection4, ZodIssueCode: () => ZodIssueCode4, ZodJWT: () => ZodJWT2, ZodKSUID: () => ZodKSUID2, ZodLazy: () => ZodLazy4, ZodLiteral: () => ZodLiteral4, ZodMap: () => ZodMap4, ZodNaN: () => ZodNaN4, ZodNanoID: () => ZodNanoID2, ZodNever: () => ZodNever4, ZodNonOptional: () => ZodNonOptional2, ZodNull: () => ZodNull4, ZodNullable: () => ZodNullable4, ZodNumber: () => ZodNumber4, ZodNumberFormat: () => ZodNumberFormat2, ZodObject: () => ZodObject4, ZodOptional: () => ZodOptional4, ZodPipe: () => ZodPipe2, ZodPrefault: () => ZodPrefault2, ZodPromise: () => ZodPromise4, ZodReadonly: () => ZodReadonly4, ZodRealError: () => ZodRealError2, ZodRecord: () => ZodRecord4, ZodSet: () => ZodSet4, ZodString: () => ZodString4, ZodStringFormat: () => ZodStringFormat2, ZodSuccess: () => ZodSuccess2, ZodSymbol: () => ZodSymbol4, ZodTemplateLiteral: () => ZodTemplateLiteral2, ZodTransform: () => ZodTransform2, ZodTuple: () => ZodTuple4, ZodType: () => ZodType4, ZodULID: () => ZodULID2, ZodURL: () => ZodURL2, ZodUUID: () => ZodUUID2, ZodUndefined: () => ZodUndefined4, ZodUnion: () => ZodUnion4, ZodUnknown: () => ZodUnknown4, ZodVoid: () => ZodVoid4, ZodXID: () => ZodXID2, _ZodString: () => _ZodString2, _default: () => _default4, any: () => any2, array: () => array2, base64: () => base644, base64url: () => base64url4, bigint: () => bigint5, boolean: () => boolean5, catch: () => _catch4, check: () => check2, cidrv4: () => cidrv44, cidrv6: () => cidrv64, clone: () => clone2, coerce: () => coerce_exports2, config: () => config2, core: () => core_exports4, cuid: () => cuid5, cuid2: () => cuid24, custom: () => custom3, date: () => date7, discriminatedUnion: () => discriminatedUnion2, e164: () => e1644, email: () => email4, emoji: () => emoji4, endsWith: () => _endsWith2, enum: () => _enum4, file: () => file2, flattenError: () => flattenError2, float32: () => float322, float64: () => float642, formatError: () => formatError2, function: () => _function2, getErrorMap: () => getErrorMap4, globalRegistry: () => globalRegistry2, gt: () => _gt2, gte: () => _gte2, guid: () => guid4, includes: () => _includes2, instanceof: () => _instanceof2, int: () => int2, int32: () => int322, int64: () => int642, intersection: () => intersection2, ipv4: () => ipv44, ipv6: () => ipv64, iso: () => iso_exports2, json: () => json2, jwt: () => jwt2, keyof: () => keyof2, ksuid: () => ksuid4, lazy: () => lazy2, length: () => _length2, literal: () => literal2, locales: () => locales_exports2, looseObject: () => looseObject2, lowercase: () => _lowercase2, lt: () => _lt2, lte: () => _lte2, map: () => map2, maxLength: () => _maxLength2, maxSize: () => _maxSize2, mime: () => _mime2, minLength: () => _minLength2, minSize: () => _minSize2, multipleOf: () => _multipleOf2, nan: () => nan2, nanoid: () => nanoid4, nativeEnum: () => nativeEnum2, negative: () => _negative2, never: () => never2, nonnegative: () => _nonnegative2, nonoptional: () => nonoptional2, nonpositive: () => _nonpositive2, normalize: () => _normalize2, null: () => _null6, nullable: () => nullable2, nullish: () => nullish4, number: () => number5, object: () => object4, optional: () => optional2, overwrite: () => _overwrite2, parse: () => parse4, parseAsync: () => parseAsync4, partialRecord: () => partialRecord2, pipe: () => pipe2, positive: () => _positive2, prefault: () => prefault2, preprocess: () => preprocess2, prettifyError: () => prettifyError2, promise: () => promise2, property: () => _property2, readonly: () => readonly2, record: () => record2, refine: () => refine2, regex: () => _regex2, regexes: () => regexes_exports2, registry: () => registry2, safeParse: () => safeParse4, safeParseAsync: () => safeParseAsync4, set: () => set2, setErrorMap: () => setErrorMap3, size: () => _size2, startsWith: () => _startsWith2, strictObject: () => strictObject2, string: () => string5, stringFormat: () => stringFormat2, stringbool: () => stringbool2, success: () => success2, superRefine: () => superRefine2, symbol: () => symbol20, templateLiteral: () => templateLiteral2, toJSONSchema: () => toJSONSchema2, toLowerCase: () => _toLowerCase2, toUpperCase: () => _toUpperCase2, transform: () => transform2, treeifyError: () => treeifyError2, trim: () => _trim2, tuple: () => tuple2, uint32: () => uint322, uint64: () => uint642, ulid: () => ulid4, undefined: () => _undefined6, union: () => union2, unknown: () => unknown2, uppercase: () => _uppercase2, url: () => url2, uuid: () => uuid5, uuidv4: () => uuidv42, uuidv6: () => uuidv62, uuidv7: () => uuidv72, void: () => _void4, xid: () => xid4 }); var core_exports4 = {}; __export(core_exports4, { $ZodAny: () => $ZodAny2, $ZodArray: () => $ZodArray2, $ZodAsyncError: () => $ZodAsyncError2, $ZodBase64: () => $ZodBase642, $ZodBase64URL: () => $ZodBase64URL2, $ZodBigInt: () => $ZodBigInt2, $ZodBigIntFormat: () => $ZodBigIntFormat2, $ZodBoolean: () => $ZodBoolean2, $ZodCIDRv4: () => $ZodCIDRv42, $ZodCIDRv6: () => $ZodCIDRv62, $ZodCUID: () => $ZodCUID3, $ZodCUID2: () => $ZodCUID22, $ZodCatch: () => $ZodCatch2, $ZodCheck: () => $ZodCheck2, $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat2, $ZodCheckEndsWith: () => $ZodCheckEndsWith2, $ZodCheckGreaterThan: () => $ZodCheckGreaterThan2, $ZodCheckIncludes: () => $ZodCheckIncludes2, $ZodCheckLengthEquals: () => $ZodCheckLengthEquals2, $ZodCheckLessThan: () => $ZodCheckLessThan2, $ZodCheckLowerCase: () => $ZodCheckLowerCase2, $ZodCheckMaxLength: () => $ZodCheckMaxLength2, $ZodCheckMaxSize: () => $ZodCheckMaxSize2, $ZodCheckMimeType: () => $ZodCheckMimeType2, $ZodCheckMinLength: () => $ZodCheckMinLength2, $ZodCheckMinSize: () => $ZodCheckMinSize2, $ZodCheckMultipleOf: () => $ZodCheckMultipleOf2, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat2, $ZodCheckOverwrite: () => $ZodCheckOverwrite2, $ZodCheckProperty: () => $ZodCheckProperty2, $ZodCheckRegex: () => $ZodCheckRegex2, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals2, $ZodCheckStartsWith: () => $ZodCheckStartsWith2, $ZodCheckStringFormat: () => $ZodCheckStringFormat2, $ZodCheckUpperCase: () => $ZodCheckUpperCase2, $ZodCustom: () => $ZodCustom2, $ZodCustomStringFormat: () => $ZodCustomStringFormat2, $ZodDate: () => $ZodDate2, $ZodDefault: () => $ZodDefault2, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion2, $ZodE164: () => $ZodE1642, $ZodEmail: () => $ZodEmail2, $ZodEmoji: () => $ZodEmoji2, $ZodEnum: () => $ZodEnum2, $ZodError: () => $ZodError2, $ZodFile: () => $ZodFile2, $ZodFunction: () => $ZodFunction2, $ZodGUID: () => $ZodGUID2, $ZodIPv4: () => $ZodIPv42, $ZodIPv6: () => $ZodIPv62, $ZodISODate: () => $ZodISODate2, $ZodISODateTime: () => $ZodISODateTime2, $ZodISODuration: () => $ZodISODuration2, $ZodISOTime: () => $ZodISOTime2, $ZodIntersection: () => $ZodIntersection2, $ZodJWT: () => $ZodJWT2, $ZodKSUID: () => $ZodKSUID2, $ZodLazy: () => $ZodLazy2, $ZodLiteral: () => $ZodLiteral2, $ZodMap: () => $ZodMap2, $ZodNaN: () => $ZodNaN2, $ZodNanoID: () => $ZodNanoID2, $ZodNever: () => $ZodNever2, $ZodNonOptional: () => $ZodNonOptional2, $ZodNull: () => $ZodNull2, $ZodNullable: () => $ZodNullable2, $ZodNumber: () => $ZodNumber2, $ZodNumberFormat: () => $ZodNumberFormat2, $ZodObject: () => $ZodObject2, $ZodOptional: () => $ZodOptional2, $ZodPipe: () => $ZodPipe2, $ZodPrefault: () => $ZodPrefault2, $ZodPromise: () => $ZodPromise2, $ZodReadonly: () => $ZodReadonly2, $ZodRealError: () => $ZodRealError2, $ZodRecord: () => $ZodRecord2, $ZodRegistry: () => $ZodRegistry2, $ZodSet: () => $ZodSet2, $ZodString: () => $ZodString2, $ZodStringFormat: () => $ZodStringFormat2, $ZodSuccess: () => $ZodSuccess2, $ZodSymbol: () => $ZodSymbol2, $ZodTemplateLiteral: () => $ZodTemplateLiteral2, $ZodTransform: () => $ZodTransform2, $ZodTuple: () => $ZodTuple2, $ZodType: () => $ZodType2, $ZodULID: () => $ZodULID2, $ZodURL: () => $ZodURL2, $ZodUUID: () => $ZodUUID2, $ZodUndefined: () => $ZodUndefined2, $ZodUnion: () => $ZodUnion2, $ZodUnknown: () => $ZodUnknown2, $ZodVoid: () => $ZodVoid2, $ZodXID: () => $ZodXID2, $brand: () => $brand2, $constructor: () => $constructor2, $input: () => $input2, $output: () => $output2, Doc: () => Doc2, JSONSchema: () => json_schema_exports2, JSONSchemaGenerator: () => JSONSchemaGenerator2, NEVER: () => NEVER3, TimePrecision: () => TimePrecision2, _any: () => _any2, _array: () => _array2, _base64: () => _base642, _base64url: () => _base64url2, _bigint: () => _bigint2, _boolean: () => _boolean2, _catch: () => _catch3, _cidrv4: () => _cidrv42, _cidrv6: () => _cidrv62, _coercedBigint: () => _coercedBigint2, _coercedBoolean: () => _coercedBoolean2, _coercedDate: () => _coercedDate2, _coercedNumber: () => _coercedNumber2, _coercedString: () => _coercedString2, _cuid: () => _cuid3, _cuid2: () => _cuid22, _custom: () => _custom2, _date: () => _date2, _default: () => _default3, _discriminatedUnion: () => _discriminatedUnion2, _e164: () => _e1642, _email: () => _email2, _emoji: () => _emoji4, _endsWith: () => _endsWith2, _enum: () => _enum3, _file: () => _file2, _float32: () => _float322, _float64: () => _float642, _gt: () => _gt2, _gte: () => _gte2, _guid: () => _guid2, _includes: () => _includes2, _int: () => _int2, _int32: () => _int322, _int64: () => _int642, _intersection: () => _intersection2, _ipv4: () => _ipv42, _ipv6: () => _ipv62, _isoDate: () => _isoDate2, _isoDateTime: () => _isoDateTime2, _isoDuration: () => _isoDuration2, _isoTime: () => _isoTime2, _jwt: () => _jwt2, _ksuid: () => _ksuid2, _lazy: () => _lazy2, _length: () => _length2, _literal: () => _literal2, _lowercase: () => _lowercase2, _lt: () => _lt2, _lte: () => _lte2, _map: () => _map2, _max: () => _lte2, _maxLength: () => _maxLength2, _maxSize: () => _maxSize2, _mime: () => _mime2, _min: () => _gte2, _minLength: () => _minLength2, _minSize: () => _minSize2, _multipleOf: () => _multipleOf2, _nan: () => _nan2, _nanoid: () => _nanoid2, _nativeEnum: () => _nativeEnum2, _negative: () => _negative2, _never: () => _never2, _nonnegative: () => _nonnegative2, _nonoptional: () => _nonoptional2, _nonpositive: () => _nonpositive2, _normalize: () => _normalize2, _null: () => _null5, _nullable: () => _nullable2, _number: () => _number2, _optional: () => _optional2, _overwrite: () => _overwrite2, _parse: () => _parse3, _parseAsync: () => _parseAsync2, _pipe: () => _pipe2, _positive: () => _positive2, _promise: () => _promise2, _property: () => _property2, _readonly: () => _readonly2, _record: () => _record2, _refine: () => _refine2, _regex: () => _regex2, _safeParse: () => _safeParse2, _safeParseAsync: () => _safeParseAsync2, _set: () => _set2, _size: () => _size2, _startsWith: () => _startsWith2, _string: () => _string2, _stringFormat: () => _stringFormat2, _stringbool: () => _stringbool2, _success: () => _success2, _symbol: () => _symbol2, _templateLiteral: () => _templateLiteral2, _toLowerCase: () => _toLowerCase2, _toUpperCase: () => _toUpperCase2, _transform: () => _transform2, _trim: () => _trim2, _tuple: () => _tuple2, _uint32: () => _uint322, _uint64: () => _uint642, _ulid: () => _ulid2, _undefined: () => _undefined5, _union: () => _union2, _unknown: () => _unknown2, _uppercase: () => _uppercase2, _url: () => _url2, _uuid: () => _uuid2, _uuidv4: () => _uuidv42, _uuidv6: () => _uuidv62, _uuidv7: () => _uuidv72, _void: () => _void3, _xid: () => _xid2, clone: () => clone2, config: () => config2, flattenError: () => flattenError2, formatError: () => formatError2, function: () => _function2, globalConfig: () => globalConfig2, globalRegistry: () => globalRegistry2, isValidBase64: () => isValidBase642, isValidBase64URL: () => isValidBase64URL2, isValidJWT: () => isValidJWT4, locales: () => locales_exports2, parse: () => parse3, parseAsync: () => parseAsync3, prettifyError: () => prettifyError2, regexes: () => regexes_exports2, registry: () => registry2, safeParse: () => safeParse3, safeParseAsync: () => safeParseAsync3, toDotPath: () => toDotPath2, toJSONSchema: () => toJSONSchema2, treeifyError: () => treeifyError2, util: () => util_exports2, version: () => version2 }); var NEVER3 = Object.freeze({ status: "aborted" }); // @__NO_SIDE_EFFECTS__ function $constructor2(name21, initializer5, params) { function init(inst, def) { var _a282; Object.defineProperty(inst, "_zod", { value: inst._zod ?? {}, enumerable: false }); (_a282 = inst._zod).traits ?? (_a282.traits = /* @__PURE__ */ new Set()); inst._zod.traits.add(name21); initializer5(inst, def); 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; } const Parent = params?.Parent ?? Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name21 }); function _(def) { var _a282; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a282 = inst._zod).deferred ?? (_a282.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(name21); } }); Object.defineProperty(_, "name", { value: name21 }); return _; } var $brand2 = /* @__PURE__ */ Symbol("zod_brand"); var $ZodAsyncError2 = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; var globalConfig2 = {}; function config2(newConfig) { if (newConfig) Object.assign(globalConfig2, newConfig); return globalConfig2; } var util_exports2 = {}; __export(util_exports2, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES2, Class: () => Class2, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES2, aborted: () => aborted2, allowsEval: () => allowsEval2, assert: () => assert2, assertEqual: () => assertEqual2, assertIs: () => assertIs2, assertNever: () => assertNever2, assertNotEqual: () => assertNotEqual2, assignProp: () => assignProp2, cached: () => cached2, captureStackTrace: () => captureStackTrace2, cleanEnum: () => cleanEnum2, cleanRegex: () => cleanRegex2, clone: () => clone2, createTransparentProxy: () => createTransparentProxy2, defineLazy: () => defineLazy2, esc: () => esc2, escapeRegex: () => escapeRegex2, extend: () => extend2, finalizeIssue: () => finalizeIssue2, floatSafeRemainder: () => floatSafeRemainder4, getElementAtPath: () => getElementAtPath2, getEnumValues: () => getEnumValues2, getLengthableOrigin: () => getLengthableOrigin2, getParsedType: () => getParsedType4, getSizableOrigin: () => getSizableOrigin2, isObject: () => isObject2, isPlainObject: () => isPlainObject2, issue: () => issue2, joinValues: () => joinValues2, jsonStringifyReplacer: () => jsonStringifyReplacer2, merge: () => merge2, normalizeParams: () => normalizeParams2, nullish: () => nullish3, numKeys: () => numKeys2, omit: () => omit2, optionalKeys: () => optionalKeys2, partial: () => partial2, pick: () => pick2, prefixIssues: () => prefixIssues2, primitiveTypes: () => primitiveTypes2, promiseAllObject: () => promiseAllObject2, propertyKeyTypes: () => propertyKeyTypes2, randomString: () => randomString2, required: () => required2, stringifyPrimitive: () => stringifyPrimitive2, unwrapMessage: () => unwrapMessage2 }); function assertEqual2(val) { return val; } function assertNotEqual2(val) { return val; } function assertIs2(_arg) { } function assertNever2(_x) { throw new Error(); } function assert2(_) { } function getEnumValues2(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 joinValues2(array4, separator = "|") { return array4.map((val) => stringifyPrimitive2(val)).join(separator); } function jsonStringifyReplacer2(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached2(getter) { return { get value() { { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } } }; } function nullish3(input) { return input === null || input === void 0; } function cleanRegex2(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function floatSafeRemainder4(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 defineLazy2(object62, key, getter) { Object.defineProperty(object62, key, { get() { { const value = getter(); object62[key] = value; return value; } }, set(v) { Object.defineProperty(object62, key, { value: v // configurable: true, }); }, configurable: true }); } function assignProp2(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } function getElementAtPath2(obj, path) { if (!path) return obj; return path.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject2(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 randomString2(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 esc2(str) { return JSON.stringify(str); } var captureStackTrace2 = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { }; function isObject2(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval2 = cached2(() => { if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { return false; } try { const F2 = Function; new F2(""); return true; } catch (_) { return false; } }); function isPlainObject2(o) { if (isObject2(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; const prot = ctor.prototype; if (isObject2(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function numKeys2(data) { let keyCount = 0; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { keyCount++; } } return keyCount; } var getParsedType4 = (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}`); } }; var propertyKeyTypes2 = /* @__PURE__ */ new Set(["string", "number", "symbol"]); var primitiveTypes2 = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); function escapeRegex2(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function clone2(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams2(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== void 0) { if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function createTransparentProxy2(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 stringifyPrimitive2(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys2(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } var NUMBER_FORMAT_RANGES2 = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; var BIGINT_FORMAT_RANGES2 = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick2(schema, mask) { const newShape = {}; const currDef = schema._zod.def; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; newShape[key] = currDef.shape[key]; } return clone2(schema, { ...schema._zod.def, shape: newShape, checks: [] }); } function omit2(schema, mask) { const newShape = { ...schema._zod.def.shape }; const currDef = schema._zod.def; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } return clone2(schema, { ...schema._zod.def, shape: newShape, checks: [] }); } function extend2(schema, shape) { if (!isPlainObject2(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 }; assignProp2(this, "shape", _shape); return _shape; }, checks: [] // delete existing checks }; return clone2(schema, def); } function merge2(a, b) { return clone2(a, { ...a._zod.def, get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; assignProp2(this, "shape", _shape); return _shape; }, catchall: b._zod.def.catchall, checks: [] // delete existing checks }); } function partial2(Class3, 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; shape[key] = Class3 ? new Class3({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } else { for (const key in oldShape) { shape[key] = Class3 ? new Class3({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } return clone2(schema, { ...schema._zod.def, shape, checks: [] }); } function required2(Class3, 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; shape[key] = new Class3({ type: "nonoptional", innerType: oldShape[key] }); } } else { for (const key in oldShape) { shape[key] = new Class3({ type: "nonoptional", innerType: oldShape[key] }); } } return clone2(schema, { ...schema._zod.def, shape, // optional: [], checks: [] }); } function aborted2(x, startIndex = 0) { for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue !== true) return true; } return false; } function prefixIssues2(path, issues) { return issues.map((iss) => { var _a282; (_a282 = iss).path ?? (_a282.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage2(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue2(iss, ctx, config3) { const full = { ...iss, path: iss.path ?? [] }; if (!iss.message) { const message = unwrapMessage2(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage2(ctx?.error?.(iss)) ?? unwrapMessage2(config3.customError?.(iss)) ?? unwrapMessage2(config3.localeError?.(iss)) ?? "Invalid input"; full.message = message; } delete full.inst; delete full.continue; if (!ctx?.reportInput) { delete full.input; } return full; } function getSizableOrigin2(input) { if (input instanceof Set) return "set"; if (input instanceof Map) return "map"; if (input instanceof File) return "file"; return "unknown"; } function getLengthableOrigin2(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function issue2(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst }; } return { ...iss }; } function cleanEnum2(obj) { return Object.entries(obj).filter(([k, _]) => { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } var Class2 = class { constructor(..._args) { } }; var initializer3 = (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, jsonStringifyReplacer2, 2); }, enumerable: true // configurable: false, }); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false }); }; var $ZodError2 = /* @__PURE__ */ $constructor2("$ZodError", initializer3); var $ZodRealError2 = /* @__PURE__ */ $constructor2("$ZodError", initializer3, { Parent: Error }); function flattenError2(error90, mapper = (issue3) => issue3.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error90.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 formatError2(error90, _mapper) { const mapper = _mapper || function(issue3) { return issue3.message; }; const fieldErrors = { _errors: [] }; const processError = (error91) => { for (const issue3 of error91.issues) { if (issue3.code === "invalid_union" && issue3.errors.length) { issue3.errors.map((issues) => processError({ issues })); } else if (issue3.code === "invalid_key") { processError({ issues: issue3.issues }); } else if (issue3.code === "invalid_element") { processError({ issues: issue3.issues }); } else if (issue3.path.length === 0) { fieldErrors._errors.push(mapper(issue3)); } else { let curr = fieldErrors; let i = 0; while (i < issue3.path.length) { const el = issue3.path[i]; const terminal = i === issue3.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue3)); } curr = curr[el]; i++; } } } }; processError(error90); return fieldErrors; } function treeifyError2(error90, _mapper) { const mapper = _mapper || function(issue3) { return issue3.message; }; const result = { errors: [] }; const processError = (error91, path = []) => { var _a282, _b19; for (const issue3 of error91.issues) { if (issue3.code === "invalid_union" && issue3.errors.length) { issue3.errors.map((issues) => processError({ issues }, issue3.path)); } else if (issue3.code === "invalid_key") { processError({ issues: issue3.issues }, issue3.path); } else if (issue3.code === "invalid_element") { processError({ issues: issue3.issues }, issue3.path); } else { const fullpath = [...path, ...issue3.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue3)); 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 = {}); (_a282 = curr.properties)[el] ?? (_a282[el] = { errors: [] }); curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); (_b19 = curr.items)[el] ?? (_b19[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue3)); } i++; } } } }; processError(error90); return result; } function toDotPath2(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 prettifyError2(error90) { const lines = []; const issues = [...error90.issues].sort((a, b) => a.path.length - b.path.length); for (const issue3 of issues) { lines.push(`\u2716 ${issue3.message}`); if (issue3.path?.length) lines.push(` \u2192 at ${toDotPath2(issue3.path)}`); } return lines.join("\n"); } var _parse3 = (_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 $ZodAsyncError2(); } if (result.issues.length) { const e2 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))); captureStackTrace2(e2, _params?.callee); throw e2; } return result.value; }; var parse3 = /* @__PURE__ */ _parse3($ZodRealError2); var _parseAsync2 = (_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 e2 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))); captureStackTrace2(e2, params?.callee); throw e2; } return result.value; }; var parseAsync3 = /* @__PURE__ */ _parseAsync2($ZodRealError2); var _safeParse2 = (_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 $ZodAsyncError2(); } return result.issues.length ? { success: false, error: new (_Err ?? $ZodError2)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))) } : { success: true, data: result.value }; }; var safeParse3 = /* @__PURE__ */ _safeParse2($ZodRealError2); var _safeParseAsync2 = (_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) => finalizeIssue2(iss, ctx, config2()))) } : { success: true, data: result.value }; }; var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync2($ZodRealError2); var regexes_exports2 = {}; __export(regexes_exports2, { _emoji: () => _emoji3, base64: () => base643, base64url: () => base64url3, bigint: () => bigint4, boolean: () => boolean4, browserEmail: () => browserEmail2, cidrv4: () => cidrv43, cidrv6: () => cidrv63, cuid: () => cuid4, cuid2: () => cuid23, date: () => date5, datetime: () => datetime3, domain: () => domain2, duration: () => duration3, e164: () => e1643, email: () => email3, emoji: () => emoji3, extendedDuration: () => extendedDuration2, guid: () => guid3, hostname: () => hostname3, html5Email: () => html5Email2, integer: () => integer2, ipv4: () => ipv43, ipv6: () => ipv63, ksuid: () => ksuid3, lowercase: () => lowercase2, nanoid: () => nanoid3, null: () => _null4, number: () => number4, rfc5322Email: () => rfc5322Email2, string: () => string4, time: () => time3, ulid: () => ulid3, undefined: () => _undefined4, unicodeEmail: () => unicodeEmail2, uppercase: () => uppercase2, uuid: () => uuid3, uuid4: () => uuid42, uuid6: () => uuid62, uuid7: () => uuid72, xid: () => xid3 }); var cuid4 = /^[cC][^\s-]{8,}$/; var cuid23 = /^[0-9a-z]+$/; var ulid3 = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; var xid3 = /^[0-9a-vA-V]{20}$/; var ksuid3 = /^[A-Za-z0-9]{27}$/; var nanoid3 = /^[a-zA-Z0-9_-]{21}$/; var duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration2 = /^[-+]?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)?)??$/; var guid3 = /^([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})$/; var uuid3 = (version3) => { if (!version3) 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}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; var uuid42 = /* @__PURE__ */ uuid3(4); var uuid62 = /* @__PURE__ */ uuid3(6); var uuid72 = /* @__PURE__ */ uuid3(7); var email3 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email2 = /^[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])?)*$/; var rfc5322Email2 = /^(([^<>()\[\]\\.,;:\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,}))$/; var unicodeEmail2 = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var browserEmail2 = /^[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])?)*$/; var _emoji3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji3() { return new RegExp(_emoji3, "u"); } var ipv43 = /^(?:(?: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])$/; var ipv63 = /^(([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})$/; var cidrv43 = /^((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])$/; var cidrv63 = /^(([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])$/; var base643 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url3 = /^[A-Za-z0-9_-]*$/; var hostname3 = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; var domain2 = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; var e1643 = /^\+(?:[0-9]){6,14}[0-9]$/; var dateSource2 = `(?:(?:\\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])))`; var date5 = /* @__PURE__ */ new RegExp(`^${dateSource2}$`); function timeSource2(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 time3(args) { return new RegExp(`^${timeSource2(args)}$`); } function datetime3(args) { const time5 = timeSource2({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); const timeRegex3 = `${time5}(?:${opts.join("|")})`; return new RegExp(`^${dateSource2}T(?:${timeRegex3})$`); } var string4 = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; var bigint4 = /^\d+n?$/; var integer2 = /^\d+$/; var number4 = /^-?\d+(?:\.\d+)?/i; var boolean4 = /true|false/i; var _null4 = /null/i; var _undefined4 = /undefined/i; var lowercase2 = /^[^A-Z]*$/; var uppercase2 = /^[^a-z]*$/; var $ZodCheck2 = /* @__PURE__ */ $constructor2("$ZodCheck", (inst, def) => { var _a282; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a282 = inst._zod).onattach ?? (_a282.onattach = []); }); var numericOriginMap2 = { number: "number", bigint: "bigint", object: "date" }; var $ZodCheckLessThan2 = /* @__PURE__ */ $constructor2("$ZodCheckLessThan", (inst, def) => { $ZodCheck2.init(inst, def); const origin = numericOriginMap2[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckGreaterThan2 = /* @__PURE__ */ $constructor2("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck2.init(inst, def); const origin = numericOriginMap2[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckMultipleOf2 = /* @__PURE__ */ $constructor2("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck2.init(inst, def); inst._zod.onattach.push((inst2) => { var _a282; (_a282 = inst2._zod.bag).multipleOf ?? (_a282.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) : floatSafeRemainder4(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 }); }; }); var $ZodCheckNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckNumberFormat", (inst, def) => { $ZodCheck2.init(inst, def); def.format = def.format || "float64"; const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES2[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer2; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) { payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort }); } else { payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, 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 }); } }; }); var $ZodCheckBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck2.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES2[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; }); inst._zod.check = (payload) => { const input = payload.value; if (input < minimum) { payload.issues.push({ origin: "bigint", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inst }); } }; }); var $ZodCheckMaxSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxSize", (inst, def) => { var _a282; $ZodCheck2.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish3(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size <= def.maximum) return; payload.issues.push({ origin: getSizableOrigin2(input), code: "too_big", maximum: def.maximum, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMinSize", (inst, def) => { var _a282; $ZodCheck2.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish3(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size >= def.minimum) return; payload.issues.push({ origin: getSizableOrigin2(input), code: "too_small", minimum: def.minimum, input, inst, continue: !def.abort }); }; }); var $ZodCheckSizeEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckSizeEquals", (inst, def) => { var _a282; $ZodCheck2.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish3(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.size; bag.maximum = def.size; bag.size = def.size; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size === def.size) return; const tooBig = size > def.size; payload.issues.push({ origin: getSizableOrigin2(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 }); }; }); var $ZodCheckMaxLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxLength", (inst, def) => { var _a282; $ZodCheck2.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish3(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length <= def.maximum) return; const origin = getLengthableOrigin2(input); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMinLength", (inst, def) => { var _a282; $ZodCheck2.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish3(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length >= def.minimum) return; const origin = getLengthableOrigin2(input); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckLengthEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckLengthEquals", (inst, def) => { var _a282; $ZodCheck2.init(inst, def); (_a282 = inst._zod.def).when ?? (_a282.when = (payload) => { const val = payload.value; return !nullish3(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.length; bag.maximum = def.length; bag.length = def.length; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length === def.length) return; const origin = getLengthableOrigin2(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 }); }; }); var $ZodCheckStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckStringFormat", (inst, def) => { var _a282, _b19; $ZodCheck2.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; if (def.pattern) { bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(def.pattern); } }); if (def.pattern) (_a282 = inst._zod).check ?? (_a282.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 (_b19 = inst._zod).check ?? (_b19.check = () => { }); }); var $ZodCheckRegex2 = /* @__PURE__ */ $constructor2("$ZodCheckRegex", (inst, def) => { $ZodCheckStringFormat2.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 }); }; }); var $ZodCheckLowerCase2 = /* @__PURE__ */ $constructor2("$ZodCheckLowerCase", (inst, def) => { def.pattern ?? (def.pattern = lowercase2); $ZodCheckStringFormat2.init(inst, def); }); var $ZodCheckUpperCase2 = /* @__PURE__ */ $constructor2("$ZodCheckUpperCase", (inst, def) => { def.pattern ?? (def.pattern = uppercase2); $ZodCheckStringFormat2.init(inst, def); }); var $ZodCheckIncludes2 = /* @__PURE__ */ $constructor2("$ZodCheckIncludes", (inst, def) => { $ZodCheck2.init(inst, def); const escapedRegex = escapeRegex2(def.includes); const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); def.pattern = pattern; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: def.includes, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckStartsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckStartsWith", (inst, def) => { $ZodCheck2.init(inst, def); const pattern = new RegExp(`^${escapeRegex2(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: def.prefix, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckEndsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckEndsWith", (inst, def) => { $ZodCheck2.init(inst, def); const pattern = new RegExp(`.*${escapeRegex2(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: def.suffix, input: payload.value, inst, continue: !def.abort }); }; }); function handleCheckPropertyResult2(result, payload, property) { if (result.issues.length) { payload.issues.push(...prefixIssues2(property, result.issues)); } } var $ZodCheckProperty2 = /* @__PURE__ */ $constructor2("$ZodCheckProperty", (inst, def) => { $ZodCheck2.init(inst, def); inst._zod.check = (payload) => { const result = def.schema._zod.run({ value: payload.value[def.property], issues: [] }, {}); if (result instanceof Promise) { return result.then((result2) => handleCheckPropertyResult2(result2, payload, def.property)); } handleCheckPropertyResult2(result, payload, def.property); return; }; }); var $ZodCheckMimeType2 = /* @__PURE__ */ $constructor2("$ZodCheckMimeType", (inst, def) => { $ZodCheck2.init(inst, def); const mimeSet = new Set(def.mime); inst._zod.onattach.push((inst2) => { inst2._zod.bag.mime = def.mime; }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; payload.issues.push({ code: "invalid_value", values: def.mime, input: payload.value.type, inst }); }; }); var $ZodCheckOverwrite2 = /* @__PURE__ */ $constructor2("$ZodCheckOverwrite", (inst, def) => { $ZodCheck2.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); var Doc2 = class { constructor(args = []) { this.content = []; this.indent = 0; if (this) this.args = args; } indented(fn) { this.indent += 1; fn(this); this.indent -= 1; } write(arg) { if (typeof arg === "function") { arg(this, { execution: "sync" }); arg(this, { execution: "async" }); return; } const content = arg; const lines = content.split("\n").filter((x) => x); const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); for (const line of dedented) { this.content.push(line); } } compile() { const F2 = Function; const args = this?.args; const content = this?.content ?? [``]; const lines = [...content.map((x) => ` ${x}`)]; return new F2(...args, lines.join("\n")); } }; var version2 = { major: 4, minor: 0, patch: 0 }; var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => { var _a282; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version2; const checks = [...inst._zod.def.checks ?? []]; if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); } } if (checks.length === 0) { (_a282 = inst._zod).deferred ?? (_a282.deferred = []); inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks2, ctx) => { let isAborted3 = aborted2(payload); let asyncResult; for (const ch of checks2) { if (ch._zod.def.when) { const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted3) { continue; } const currLen = payload.issues.length; const _ = ch._zod.check(payload); if (_ instanceof Promise && ctx?.async === false) { throw new $ZodAsyncError2(); } if (asyncResult || _ instanceof Promise) { asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { await _; const nextLen = payload.issues.length; if (nextLen === currLen) return; if (!isAborted3) isAborted3 = aborted2(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted3) isAborted3 = aborted2(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 $ZodAsyncError2(); return result.then((result2) => runChecks(result2, checks, ctx)); } return runChecks(result, checks, ctx); }; } inst["~standard"] = { validate: (value) => { try { const r = safeParse3(inst, value); return r.success ? { value: r.data } : { issues: r.error?.issues }; } catch (_) { return safeParseAsync3(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } }, vendor: "zod", version: 1 }; }); var $ZodString2 = /* @__PURE__ */ $constructor2("$ZodString", (inst, def) => { $ZodType2.init(inst, def); inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string4(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_2) { } if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodStringFormat2 = /* @__PURE__ */ $constructor2("$ZodStringFormat", (inst, def) => { $ZodCheckStringFormat2.init(inst, def); $ZodString2.init(inst, def); }); var $ZodGUID2 = /* @__PURE__ */ $constructor2("$ZodGUID", (inst, def) => { def.pattern ?? (def.pattern = guid3); $ZodStringFormat2.init(inst, def); }); var $ZodUUID2 = /* @__PURE__ */ $constructor2("$ZodUUID", (inst, def) => { if (def.version) { const versionMap = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }; const v = versionMap[def.version]; if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); def.pattern ?? (def.pattern = uuid3(v)); } else def.pattern ?? (def.pattern = uuid3()); $ZodStringFormat2.init(inst, def); }); var $ZodEmail2 = /* @__PURE__ */ $constructor2("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email3); $ZodStringFormat2.init(inst, def); }); var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => { $ZodStringFormat2.init(inst, def); inst._zod.check = (payload) => { try { const orig = payload.value; const url3 = new URL(orig); const href = url3.href; if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url3.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: hostname3.source, input: payload.value, inst, continue: !def.abort }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url3.protocol.endsWith(":") ? url3.protocol.slice(0, -1) : url3.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort }); } } 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 }); } }; }); var $ZodEmoji2 = /* @__PURE__ */ $constructor2("$ZodEmoji", (inst, def) => { def.pattern ?? (def.pattern = emoji3()); $ZodStringFormat2.init(inst, def); }); var $ZodNanoID2 = /* @__PURE__ */ $constructor2("$ZodNanoID", (inst, def) => { def.pattern ?? (def.pattern = nanoid3); $ZodStringFormat2.init(inst, def); }); var $ZodCUID3 = /* @__PURE__ */ $constructor2("$ZodCUID", (inst, def) => { def.pattern ?? (def.pattern = cuid4); $ZodStringFormat2.init(inst, def); }); var $ZodCUID22 = /* @__PURE__ */ $constructor2("$ZodCUID2", (inst, def) => { def.pattern ?? (def.pattern = cuid23); $ZodStringFormat2.init(inst, def); }); var $ZodULID2 = /* @__PURE__ */ $constructor2("$ZodULID", (inst, def) => { def.pattern ?? (def.pattern = ulid3); $ZodStringFormat2.init(inst, def); }); var $ZodXID2 = /* @__PURE__ */ $constructor2("$ZodXID", (inst, def) => { def.pattern ?? (def.pattern = xid3); $ZodStringFormat2.init(inst, def); }); var $ZodKSUID2 = /* @__PURE__ */ $constructor2("$ZodKSUID", (inst, def) => { def.pattern ?? (def.pattern = ksuid3); $ZodStringFormat2.init(inst, def); }); var $ZodISODateTime2 = /* @__PURE__ */ $constructor2("$ZodISODateTime", (inst, def) => { def.pattern ?? (def.pattern = datetime3(def)); $ZodStringFormat2.init(inst, def); }); var $ZodISODate2 = /* @__PURE__ */ $constructor2("$ZodISODate", (inst, def) => { def.pattern ?? (def.pattern = date5); $ZodStringFormat2.init(inst, def); }); var $ZodISOTime2 = /* @__PURE__ */ $constructor2("$ZodISOTime", (inst, def) => { def.pattern ?? (def.pattern = time3(def)); $ZodStringFormat2.init(inst, def); }); var $ZodISODuration2 = /* @__PURE__ */ $constructor2("$ZodISODuration", (inst, def) => { def.pattern ?? (def.pattern = duration3); $ZodStringFormat2.init(inst, def); }); var $ZodIPv42 = /* @__PURE__ */ $constructor2("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv43); $ZodStringFormat2.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = `ipv4`; }); }); var $ZodIPv62 = /* @__PURE__ */ $constructor2("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv63); $ZodStringFormat2.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = `ipv6`; }); inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); } catch { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodCIDRv42 = /* @__PURE__ */ $constructor2("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv43); $ZodStringFormat2.init(inst, def); }); var $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv63); $ZodStringFormat2.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 }); } }; }); function isValidBase642(data) { if (data === "") return true; if (data.length % 4 !== 0) return false; try { atob(data); return true; } catch { return false; } } var $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => { def.pattern ?? (def.pattern = base643); $ZodStringFormat2.init(inst, def); inst._zod.onattach.push((inst2) => { inst2._zod.bag.contentEncoding = "base64"; }); inst._zod.check = (payload) => { if (isValidBase642(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort }); }; }); function isValidBase64URL2(data) { if (!base64url3.test(data)) return false; const base645 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base645.padEnd(Math.ceil(base645.length / 4) * 4, "="); return isValidBase642(padded); } var $ZodBase64URL2 = /* @__PURE__ */ $constructor2("$ZodBase64URL", (inst, def) => { def.pattern ?? (def.pattern = base64url3); $ZodStringFormat2.init(inst, def); inst._zod.onattach.push((inst2) => { inst2._zod.bag.contentEncoding = "base64url"; }); inst._zod.check = (payload) => { if (isValidBase64URL2(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64url", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodE1642 = /* @__PURE__ */ $constructor2("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e1643); $ZodStringFormat2.init(inst, def); }); function isValidJWT4(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; } } var $ZodJWT2 = /* @__PURE__ */ $constructor2("$ZodJWT", (inst, def) => { $ZodStringFormat2.init(inst, def); inst._zod.check = (payload) => { if (isValidJWT4(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", format: "jwt", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCustomStringFormat", (inst, def) => { $ZodStringFormat2.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 }); }; }); var $ZodNumber2 = /* @__PURE__ */ $constructor2("$ZodNumber", (inst, def) => { $ZodType2.init(inst, def); inst._zod.pattern = inst._zod.bag.pattern ?? number4; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...received ? { received } : {} }); return payload; }; }); var $ZodNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodNumber", (inst, def) => { $ZodCheckNumberFormat2.init(inst, def); $ZodNumber2.init(inst, def); }); var $ZodBoolean2 = /* @__PURE__ */ $constructor2("$ZodBoolean", (inst, def) => { $ZodType2.init(inst, def); inst._zod.pattern = boolean4; 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; }; }); var $ZodBigInt2 = /* @__PURE__ */ $constructor2("$ZodBigInt", (inst, def) => { $ZodType2.init(inst, def); inst._zod.pattern = bigint4; 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; }; }); var $ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodBigInt", (inst, def) => { $ZodCheckBigIntFormat2.init(inst, def); $ZodBigInt2.init(inst, def); }); var $ZodSymbol2 = /* @__PURE__ */ $constructor2("$ZodSymbol", (inst, def) => { $ZodType2.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; }; }); var $ZodUndefined2 = /* @__PURE__ */ $constructor2("$ZodUndefined", (inst, def) => { $ZodType2.init(inst, def); inst._zod.pattern = _undefined4; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.optin = "optional"; inst._zod.optout = "optional"; inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", input, inst }); return payload; }; }); var $ZodNull2 = /* @__PURE__ */ $constructor2("$ZodNull", (inst, def) => { $ZodType2.init(inst, def); inst._zod.pattern = _null4; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst }); return payload; }; }); var $ZodAny2 = /* @__PURE__ */ $constructor2("$ZodAny", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodUnknown2 = /* @__PURE__ */ $constructor2("$ZodUnknown", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodNever2 = /* @__PURE__ */ $constructor2("$ZodNever", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.issues.push({ expected: "never", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodVoid2 = /* @__PURE__ */ $constructor2("$ZodVoid", (inst, def) => { $ZodType2.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; }; }); var $ZodDate2 = /* @__PURE__ */ $constructor2("$ZodDate", (inst, def) => { $ZodType2.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 handleArrayResult2(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues2(index, result.issues)); } final.value[index] = result.value; } var $ZodArray2 = /* @__PURE__ */ $constructor2("$ZodArray", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst }); return payload; } payload.value = Array(input.length); const proms = []; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleArrayResult2(result2, payload, i))); } else { handleArrayResult2(result, payload, i); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); function handleObjectResult(result, final, key) { if (result.issues.length) { final.issues.push(...prefixIssues2(key, result.issues)); } final.value[key] = result.value; } function handleOptionalObjectResult(result, final, key, input) { if (result.issues.length) { if (input[key] === void 0) { if (key in input) { final.value[key] = void 0; } else { final.value[key] = result.value; } } else { final.issues.push(...prefixIssues2(key, result.issues)); } } else if (result.value === void 0) { if (key in input) final.value[key] = void 0; } else { final.value[key] = result.value; } } var $ZodObject2 = /* @__PURE__ */ $constructor2("$ZodObject", (inst, def) => { $ZodType2.init(inst, def); const _normalized = cached2(() => { const keys = Object.keys(def.shape); for (const k of keys) { if (!(def.shape[k] instanceof $ZodType2)) { throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } const okeys = optionalKeys2(def.shape); return { shape: def.shape, keys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; }); defineLazy2(inst._zod, "propValues", () => { const shape = def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); for (const v of field.values) propValues[key].add(v); } } return propValues; }); const generateFastpass = (shape) => { const doc = new Doc2(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key) => { const k = esc2(key); return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; }; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; for (const key of normalized.keys) { ids[key] = `key_${counter++}`; } doc.write(`const newResult = {}`); for (const key of normalized.keys) { if (normalized.optionalKeys.has(key)) { const id = ids[key]; doc.write(`const ${id} = ${parseStr(key)};`); const k = esc2(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]; 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 ? [${esc2(key)}, ...iss.path] : [${esc2(key)}] })));`); doc.write(`newResult[${esc2(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 isObject3 = isObject2; const jit = !globalConfig2.jitless; const allowsEval3 = allowsEval2; const fastEnabled = jit && allowsEval3.value; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject3(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } const proms = []; if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { 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]; 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((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); } else if (isOptional) { handleOptionalObjectResult(r, payload, key, input); } else { handleObjectResult(r, payload, key); } } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } const unrecognized = []; 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((r2) => handleObjectResult(r2, 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 handleUnionResults2(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) => finalizeIssue2(iss, ctx, config2()))) }); return final; } var $ZodUnion2 = /* @__PURE__ */ $constructor2("$ZodUnion", (inst, def) => { $ZodType2.init(inst, def); defineLazy2(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); defineLazy2(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); defineLazy2(inst._zod, "values", () => { if (def.options.every((o) => o._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); defineLazy2(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) => cleanRegex2(p.source)).join("|")})$`); } return void 0; }); 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 handleUnionResults2(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleUnionResults2(results2, payload, inst, ctx); }); }; }); var $ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("$ZodDiscriminatedUnion", (inst, def) => { $ZodUnion2.init(inst, def); const _super = inst._zod.parse; defineLazy2(inst._zod, "propValues", () => { const propValues = {}; for (const option of def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); for (const [k, v] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); for (const val of v) { propValues[k].add(val); } } } return propValues; }); const disc = cached2(() => { const opts = def.options; const map3 = /* @__PURE__ */ new Map(); for (const o of opts) { const values = o._zod.propValues[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); for (const v of values) { if (map3.has(v)) { throw new Error(`Duplicate discriminator value "${String(v)}"`); } map3.set(v, o); } } return map3; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isObject2(input)) { payload.issues.push({ code: "invalid_type", expected: "object", input, inst }); return payload; } const opt = disc.value.get(input?.[def.discriminator]); if (opt) { return opt._zod.run(payload, ctx); } if (def.unionFallback) { return _super(payload, ctx); } payload.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", input, path: [def.discriminator], inst }); return payload; }; }); var $ZodIntersection2 = /* @__PURE__ */ $constructor2("$ZodIntersection", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; const left = def.left._zod.run({ value: input, issues: [] }, ctx); const right = def.right._zod.run({ value: input, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { return handleIntersectionResults2(payload, left2, right2); }); } return handleIntersectionResults2(payload, left, right); }; }); function mergeValues4(a, b) { if (a === b) { return { valid: true, data: a }; } if (a instanceof Date && b instanceof Date && +a === +b) { return { valid: true, data: a }; } if (isPlainObject2(a) && isPlainObject2(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 = mergeValues4(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 = mergeValues4(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 handleIntersectionResults2(result, left, right) { if (left.issues.length) { result.issues.push(...left.issues); } if (right.issues.length) { result.issues.push(...right.issues); } if (aborted2(result)) return result; const merged = mergeValues4(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; return result; } var $ZodTuple2 = /* @__PURE__ */ $constructor2("$ZodTuple", (inst, def) => { $ZodType2.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((result2) => handleTupleResult2(result2, payload, i))); } else { handleTupleResult2(result, payload, i); } } if (def.rest) { const rest = input.slice(items.length); for (const el of rest) { i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleTupleResult2(result2, payload, i))); } else { handleTupleResult2(result, payload, i); } } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleTupleResult2(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues2(index, result.issues)); } final.value[index] = result.value; } var $ZodRecord2 = /* @__PURE__ */ $constructor2("$ZodRecord", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isPlainObject2(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((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues2(key, result2.issues)); } payload.value[key] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues2(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) => finalizeIssue2(iss, ctx, config2())), 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((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues2(key, result2.issues)); } payload.value[keyResult.value] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues2(key, result.issues)); } payload.value[keyResult.value] = result.value; } } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); var $ZodMap2 = /* @__PURE__ */ $constructor2("$ZodMap", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", input, inst }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Map(); for (const [key, value] of input) { const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { handleMapResult2(keyResult2, valueResult2, payload, key, input, inst, ctx); })); } else { handleMapResult2(keyResult, valueResult, payload, key, input, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleMapResult2(keyResult, valueResult, final, key, input, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes2.has(typeof key)) { final.issues.push(...prefixIssues2(key, keyResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_key", input, inst, issues: keyResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) }); } } if (valueResult.issues.length) { if (propertyKeyTypes2.has(typeof key)) { final.issues.push(...prefixIssues2(key, valueResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_element", input, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) }); } } final.value.set(keyResult.value, valueResult.value); } var $ZodSet2 = /* @__PURE__ */ $constructor2("$ZodSet", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Set)) { payload.issues.push({ input, inst, expected: "set", code: "invalid_type" }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Set(); for (const item of input) { const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult2(result2, payload))); } else handleSetResult2(result, payload); } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleSetResult2(result, final) { if (result.issues.length) { final.issues.push(...result.issues); } final.value.add(result.value); } var $ZodEnum2 = /* @__PURE__ */ $constructor2("$ZodEnum", (inst, def) => { $ZodType2.init(inst, def); const values = getEnumValues2(def.entries); inst._zod.values = new Set(values); inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes2.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex2(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; }; }); var $ZodLiteral2 = /* @__PURE__ */ $constructor2("$ZodLiteral", (inst, def) => { $ZodType2.init(inst, def); inst._zod.values = new Set(def.values); inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex2(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; }; }); var $ZodFile2 = /* @__PURE__ */ $constructor2("$ZodFile", (inst, def) => { $ZodType2.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; }; }); var $ZodTransform2 = /* @__PURE__ */ $constructor2("$ZodTransform", (inst, def) => { $ZodType2.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((output2) => { payload.value = output2; return payload; }); } if (_out instanceof Promise) { throw new $ZodAsyncError2(); } payload.value = _out; return payload; }; }); var $ZodOptional2 = /* @__PURE__ */ $constructor2("$ZodOptional", (inst, def) => { $ZodType2.init(inst, def); inst._zod.optin = "optional"; inst._zod.optout = "optional"; defineLazy2(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; }); defineLazy2(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex2(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { return payload; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable2 = /* @__PURE__ */ $constructor2("$ZodNullable", (inst, def) => { $ZodType2.init(inst, def); defineLazy2(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy2(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex2(pattern.source)}|null)$`) : void 0; }); defineLazy2(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); var $ZodDefault2 = /* @__PURE__ */ $constructor2("$ZodDefault", (inst, def) => { $ZodType2.init(inst, def); inst._zod.optin = "optional"; defineLazy2(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (payload.value === void 0) { payload.value = def.defaultValue; return payload; } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleDefaultResult2(result2, def)); } return handleDefaultResult2(result, def); }; }); function handleDefaultResult2(payload, def) { if (payload.value === void 0) { payload.value = def.defaultValue; } return payload; } var $ZodPrefault2 = /* @__PURE__ */ $constructor2("$ZodPrefault", (inst, def) => { $ZodType2.init(inst, def); inst._zod.optin = "optional"; defineLazy2(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (payload.value === void 0) { payload.value = def.defaultValue; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNonOptional2 = /* @__PURE__ */ $constructor2("$ZodNonOptional", (inst, def) => { $ZodType2.init(inst, def); defineLazy2(inst._zod, "values", () => { const v = def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleNonOptionalResult2(result2, inst)); } return handleNonOptionalResult2(result, inst); }; }); function handleNonOptionalResult2(payload, inst) { if (!payload.issues.length && payload.value === void 0) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: payload.value, inst }); } return payload; } var $ZodSuccess2 = /* @__PURE__ */ $constructor2("$ZodSuccess", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.issues.length === 0; return payload; }); } payload.value = result.issues.length === 0; return payload; }; }); var $ZodCatch2 = /* @__PURE__ */ $constructor2("$ZodCatch", (inst, def) => { $ZodType2.init(inst, def); inst._zod.optin = "optional"; defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy2(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((result2) => { payload.value = result2.value; if (result2.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result2.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) }, 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) => finalizeIssue2(iss, ctx, config2())) }, input: payload.value }); payload.issues = []; } return payload; }; }); var $ZodNaN2 = /* @__PURE__ */ $constructor2("$ZodNaN", (inst, def) => { $ZodType2.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; }; }); var $ZodPipe2 = /* @__PURE__ */ $constructor2("$ZodPipe", (inst, def) => { $ZodType2.init(inst, def); defineLazy2(inst._zod, "values", () => def.in._zod.values); defineLazy2(inst._zod, "optin", () => def.in._zod.optin); defineLazy2(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((left2) => handlePipeResult2(left2, def, ctx)); } return handlePipeResult2(left, def, ctx); }; }); function handlePipeResult2(left, def, ctx) { if (aborted2(left)) { return left; } return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodReadonly2 = /* @__PURE__ */ $constructor2("$ZodReadonly", (inst, def) => { $ZodType2.init(inst, def); defineLazy2(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy2(inst._zod, "values", () => def.innerType._zod.values); defineLazy2(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy2(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(handleReadonlyResult2); } return handleReadonlyResult2(result); }; }); function handleReadonlyResult2(payload) { payload.value = Object.freeze(payload.value); return payload; } var $ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("$ZodTemplateLiteral", (inst, def) => { $ZodType2.init(inst, def); const regexParts = []; for (const part of def.parts) { if (part instanceof $ZodType2) { if (!part._zod.pattern) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; if (!source) throw new Error(`Invalid template literal part: ${part._zod.traits}`); const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; regexParts.push(source.slice(start, end)); } else if (part === null || primitiveTypes2.has(typeof part)) { regexParts.push(escapeRegex2(`${part}`)); } else { throw new Error(`Invalid template literal part: ${part}`); } } inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "string") { payload.issues.push({ input: payload.value, inst, expected: "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; }; }); var $ZodPromise2 = /* @__PURE__ */ $constructor2("$ZodPromise", (inst, def) => { $ZodType2.init(inst, def); inst._zod.parse = (payload, ctx) => { return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); }; }); var $ZodLazy2 = /* @__PURE__ */ $constructor2("$ZodLazy", (inst, def) => { $ZodType2.init(inst, def); defineLazy2(inst._zod, "innerType", () => def.getter()); defineLazy2(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); defineLazy2(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); defineLazy2(inst._zod, "optin", () => inst._zod.innerType._zod.optin); defineLazy2(inst._zod, "optout", () => inst._zod.innerType._zod.optout); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); }; }); var $ZodCustom2 = /* @__PURE__ */ $constructor2("$ZodCustom", (inst, def) => { $ZodCheck2.init(inst, def); $ZodType2.init(inst, def); inst._zod.parse = (payload, _) => { return payload; }; inst._zod.check = (payload) => { const input = payload.value; const r = def.fn(input); if (r instanceof Promise) { return r.then((r2) => handleRefineResult2(r2, payload, input, inst)); } handleRefineResult2(r, payload, input, inst); return; }; }); function handleRefineResult2(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(issue2(_iss)); } } var locales_exports2 = {}; __export(locales_exports2, { ar: () => ar_default2, az: () => az_default2, be: () => be_default2, ca: () => ca_default2, cs: () => cs_default2, de: () => de_default2, en: () => en_default4, eo: () => eo_default2, es: () => es_default2, fa: () => fa_default2, fi: () => fi_default2, fr: () => fr_default2, frCA: () => fr_CA_default2, he: () => he_default2, hu: () => hu_default2, id: () => id_default2, it: () => it_default2, ja: () => ja_default2, kh: () => kh_default2, ko: () => ko_default2, mk: () => mk_default2, ms: () => ms_default2, nl: () => nl_default2, no: () => no_default2, ota: () => ota_default2, pl: () => pl_default2, ps: () => ps_default2, pt: () => pt_default2, ru: () => ru_default2, sl: () => sl_default2, sv: () => sv_default2, ta: () => ta_default2, th: () => th_default2, tr: () => tr_default2, ua: () => ua_default2, ur: () => ur_default2, vi: () => vi_default2, zhCN: () => zh_CN_default2, zhTW: () => zh_TW_default2 }); var error51 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0645\u062F\u062E\u0644", email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", url: "\u0631\u0627\u0628\u0637", emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${issue3.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive2(issue3.values[0])}`; return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue3.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue3.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue3.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue3.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue3.prefix}"`; if (_issue.format === "ends_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; } case "not_multiple_of": return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue3.divisor}`; case "unrecognized_keys": return `\u0645\u0639\u0631\u0641${issue3.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue3.keys.length > 1 ? "\u0629" : ""}: ${joinValues2(issue3.keys, "\u060C ")}`; case "invalid_key": return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue3.origin}`; case "invalid_union": return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; case "invalid_element": return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue3.origin}`; default: return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; } }; }; function ar_default2() { return { localeError: error51() }; } var error52 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, set: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${issue3.expected}, daxil olan ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive2(issue3.values[0])}`; return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue3.origin ?? "d\u0259y\u0259r"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue3.origin ?? "d\u0259y\u0259r"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; if (_issue.format === "ends_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; if (_issue.format === "includes") return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; if (_issue.format === "regex") return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; return `Yanl\u0131\u015F ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Yanl\u0131\u015F \u0259d\u0259d: ${issue3.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; case "unrecognized_keys": return `Tan\u0131nmayan a\xE7ar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; case "invalid_union": return "Yanl\u0131\u015F d\u0259y\u0259r"; case "invalid_element": return `${issue3.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; default: return `Yanl\u0131\u015F d\u0259y\u0259r`; } }; }; function az_default2() { return { localeError: error52() }; } function getBelarusianPlural2(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error53 = () => { const Sizable = { string: { unit: { one: "\u0441\u0456\u043C\u0432\u0430\u043B", few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u044B", many: "\u0431\u0430\u0439\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u043B\u0456\u043A"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0456\u045E"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0443\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0430\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0447\u0430\u0441", duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${issue3.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive2(issue3.values[0])}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { const maxValue = Number(issue3.maximum); const unit = getBelarusianPlural2(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue3.maximum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { const minValue = Number(issue3.minimum); const unit = getBelarusianPlural2(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue3.minimum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue3.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue3.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue3.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue3.origin}`; case "invalid_union": return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; case "invalid_element": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue3.origin}`; default: return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; } }; }; function be_default2() { return { localeError: error53() }; } var error54 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "entrada", email: "adre\xE7a electr\xF2nica", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Tipus inv\xE0lid: s'esperava ${issue3.expected}, s'ha rebut ${parsedType5(issue3.input)}`; // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive2(issue3.values[0])}`; return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues2(issue3.values, " o ")}`; case "too_big": { const adj = issue3.inclusive ? "com a m\xE0xim" : "menys de"; const sizing = getSizing(issue3.origin); if (sizing) return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} contingu\xE9s ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} fos ${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? "com a m\xEDnim" : "m\xE9s de"; const sizing = getSizing(issue3.origin); if (sizing) { return `Massa petit: s'esperava que ${issue3.origin} contingu\xE9s ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `Massa petit: s'esperava que ${issue3.origin} fos ${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; if (_issue.format === "includes") return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; if (_issue.format === "regex") return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; return `Format inv\xE0lid per a ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue3.divisor}`; case "unrecognized_keys": return `Clau${issue3.keys.length > 1 ? "s" : ""} no reconeguda${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Clau inv\xE0lida a ${issue3.origin}`; case "invalid_union": return "Entrada inv\xE0lida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general case "invalid_element": return `Element inv\xE0lid a ${issue3.origin}`; default: return `Entrada inv\xE0lida`; } }; }; function ca_default2() { return { localeError: error54() }; } var error55 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, set: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u010D\xEDslo"; } case "string": { return "\u0159et\u011Bzec"; } case "boolean": { return "boolean"; } case "bigint": { return "bigint"; } case "function": { return "funkce"; } case "symbol": { return "symbol"; } case "undefined": { return "undefined"; } case "object": { if (Array.isArray(data)) { return "pole"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "regul\xE1rn\xED v\xFDraz", email: "e-mailov\xE1 adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "datum a \u010Das ve form\xE1tu ISO", date: "datum ve form\xE1tu ISO", time: "\u010Das ve form\xE1tu ISO", duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", jwt: "JWT", template_literal: "vstup" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${issue3.expected}, obdr\u017Eeno ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive2(issue3.values[0])}`; return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue3.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue3.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue3.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue3.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; if (_issue.format === "includes") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; if (_issue.format === "regex") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; return `Neplatn\xFD form\xE1t ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue3.divisor}`; case "unrecognized_keys": return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Neplatn\xFD kl\xED\u010D v ${issue3.origin}`; case "invalid_union": return "Neplatn\xFD vstup"; case "invalid_element": return `Neplatn\xE1 hodnota v ${issue3.origin}`; default: return `Neplatn\xFD vstup`; } }; }; function cs_default2() { return { localeError: error55() }; } var error56 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "Zahl"; } case "object": { if (Array.isArray(data)) { return "Array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "Eingabe", email: "E-Mail-Adresse", url: "URL", emoji: "Emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Ung\xFCltige Eingabe: erwartet ${issue3.expected}, erhalten ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive2(issue3.values[0])}`; return `Ung\xFCltige Option: erwartet eine von ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Zu gro\xDF: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; return `Zu gro\xDF: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ist`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} hat`; } return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ist`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; if (_issue.format === "ends_with") return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; if (_issue.format === "includes") return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; if (_issue.format === "regex") return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; return `Ung\xFCltig: ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue3.divisor} sein`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Ung\xFCltiger Schl\xFCssel in ${issue3.origin}`; case "invalid_union": return "Ung\xFCltige Eingabe"; case "invalid_element": return `Ung\xFCltiger Wert in ${issue3.origin}`; default: return `Ung\xFCltige Eingabe`; } }; }; function de_default2() { return { localeError: error56() }; } var parsedType2 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; var error57 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, array: { unit: "items", verb: "to have" }, set: { unit: "items", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const Nouns = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Invalid input: expected ${issue3.expected}, received ${parsedType2(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`; return `Invalid option: expected one of ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Too big: expected ${issue3.origin ?? "value"} to have ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue3.origin ?? "value"} to be ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Too small: expected ${issue3.origin} to have ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Too small: expected ${issue3.origin} to be ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Invalid string: must start with "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`; if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`; if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Invalid number: must be a multiple of ${issue3.divisor}`; case "unrecognized_keys": return `Unrecognized key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Invalid key in ${issue3.origin}`; case "invalid_union": return "Invalid input"; case "invalid_element": return `Invalid value in ${issue3.origin}`; default: return `Invalid input`; } }; }; function en_default4() { return { localeError: error57() }; } var parsedType3 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "nombro"; } case "object": { if (Array.isArray(data)) { return "tabelo"; } if (data === null) { return "senvalora"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; var error58 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const Nouns = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emo\u011Dio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Nevalida enigo: atendi\u011Dis ${issue3.expected}, ricevi\u011Dis ${parsedType3(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive2(issue3.values[0])}`; return `Nevalida opcio: atendi\u011Dis unu el ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Tro granda: atendi\u011Dis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementojn"}`; return `Tro granda: atendi\u011Dis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Tro malgranda: atendi\u011Dis ke ${issue3.origin} havu ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Tro malgranda: atendi\u011Dis ke ${issue3.origin} estu ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; if (_issue.format === "includes") return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; if (_issue.format === "regex") return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; return `Nevalida ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Nevalida nombro: devas esti oblo de ${issue3.divisor}`; case "unrecognized_keys": return `Nekonata${issue3.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue3.keys.length > 1 ? "j" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Nevalida \u015Dlosilo en ${issue3.origin}`; case "invalid_union": return "Nevalida enigo"; case "invalid_element": return `Nevalida valoro en ${issue3.origin}`; default: return `Nevalida enigo`; } }; }; function eo_default2() { return { localeError: error58() }; } var error59 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "n\xFAmero"; } case "object": { if (Array.isArray(data)) { return "arreglo"; } if (data === null) { return "nulo"; } if (Object.getPrototypeOf(data) !== Object.prototype) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "entrada", email: "direcci\xF3n de correo electr\xF3nico", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Entrada inv\xE1lida: se esperaba ${issue3.expected}, recibido ${parsedType5(issue3.input)}`; // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive2(issue3.values[0])}`; return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Demasiado grande: se esperaba que ${issue3.origin ?? "valor"} tuviera ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Demasiado grande: se esperaba que ${issue3.origin ?? "valor"} fuera ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Demasiado peque\xF1o: se esperaba que ${issue3.origin} tuviera ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Demasiado peque\xF1o: se esperaba que ${issue3.origin} fuera ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; if (_issue.format === "includes") return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; return `Inv\xE1lido ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue3.divisor}`; case "unrecognized_keys": return `Llave${issue3.keys.length > 1 ? "s" : ""} desconocida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Llave inv\xE1lida en ${issue3.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido en ${issue3.origin}`; default: return `Entrada inv\xE1lida`; } }; }; function es_default2() { return { localeError: error59() }; } var error60 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; } case "object": { if (Array.isArray(data)) { return "\u0622\u0631\u0627\u06CC\u0647"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0648\u0631\u0648\u062F\u06CC", email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", url: "URL", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${issue3.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${parsedType5(issue3.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; case "invalid_value": if (issue3.values.length === 1) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive2(issue3.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; } return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues2(issue3.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue3.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue3.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} \u0628\u0627\u0634\u062F`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} \u0628\u0627\u0634\u062F`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; } if (_issue.format === "ends_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; } if (_issue.format === "includes") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; } if (_issue.format === "regex") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; } return `${Nouns[_issue.format] ?? issue3.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } case "not_multiple_of": return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue3.divisor} \u0628\u0627\u0634\u062F`; case "unrecognized_keys": return `\u06A9\u0644\u06CC\u062F${issue3.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue3.origin}`; case "invalid_union": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; case "invalid_element": return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue3.origin}`; default: return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } }; }; function fa_default2() { return { localeError: error60() }; } var error61 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "s\xE4\xE4nn\xF6llinen lauseke", email: "s\xE4hk\xF6postiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Virheellinen tyyppi: odotettiin ${issue3.expected}, oli ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive2(issue3.values[0])}`; return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue3.maximum.toString()} ${sizing.unit}`.trim(); } return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue3.minimum.toString()} ${sizing.unit}`.trim(); } return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; if (_issue.format === "includes") return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; if (_issue.format === "regex") { return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; } return `Virheellinen ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Virheellinen luku: t\xE4ytyy olla luvun ${issue3.divisor} monikerta`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return "Virheellinen avain tietueessa"; case "invalid_union": return "Virheellinen unioni"; case "invalid_element": return "Virheellinen arvo joukossa"; default: return `Virheellinen sy\xF6te`; } }; }; function fi_default2() { return { localeError: error61() }; } var error62 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "nombre"; } case "object": { if (Array.isArray(data)) { return "tableau"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "entr\xE9e", email: "adresse e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Entr\xE9e invalide : ${issue3.expected} attendu, ${parsedType5(issue3.input)} re\xE7u`; case "invalid_value": if (issue3.values.length === 1) return `Entr\xE9e invalide : ${stringifyPrimitive2(issue3.values[0])} attendu`; return `Option invalide : une valeur parmi ${joinValues2(issue3.values, "|")} attendue`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Trop grand : ${issue3.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; return `Trop grand : ${issue3.origin ?? "valeur"} doit \xEAtre ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Trop petit : ${issue3.origin} doit ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Trop petit : ${issue3.origin} doit \xEAtre ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue3.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue3.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue3.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_default2() { return { localeError: error62() }; } var error63 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "entr\xE9e", email: "adresse courriel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Entr\xE9e invalide : attendu ${issue3.expected}, re\xE7u ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Entr\xE9e invalide : attendu ${stringifyPrimitive2(issue3.values[0])}`; return `Option invalide : attendu l'une des valeurs suivantes ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "\u2264" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} ait ${adj}${issue3.maximum.toString()} ${sizing.unit}`; return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} soit ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? "\u2265" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Trop petit : attendu que ${issue3.origin} ait ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Trop petit : attendu que ${issue3.origin} soit ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue3.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue3.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue3.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_CA_default2() { return { localeError: error63() }; } var error64 = () => { const Sizable = { string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u05E7\u05DC\u05D8", email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", time: "\u05D6\u05DE\u05DF ISO", duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4", cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6", base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", e164: "\u05DE\u05E1\u05E4\u05E8 E.164", jwt: "JWT", template_literal: "\u05E7\u05DC\u05D8" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${issue3.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${parsedType5(issue3.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${stringifyPrimitive2(issue3.values[0])}`; return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue3.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue3.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue3.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue3.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; if (_issue.format === "regex") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } case "not_multiple_of": return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue3.divisor}`; case "unrecognized_keys": return `\u05DE\u05E4\u05EA\u05D7${issue3.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue3.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue3.origin}`; case "invalid_union": return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; case "invalid_element": return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue3.origin}`; default: return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } }; }; function he_default2() { return { localeError: error64() }; } var error65 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "sz\xE1m"; } case "object": { if (Array.isArray(data)) { return "t\xF6mb"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "bemenet", email: "email c\xEDm", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO id\u0151b\xE9lyeg", date: "ISO d\xE1tum", time: "ISO id\u0151", duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", jwt: "JWT", template_literal: "bemenet" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${issue3.expected}, a kapott \xE9rt\xE9k ${parsedType5(issue3.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive2(issue3.values[0])}`; return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `T\xFAl nagy: ${issue3.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elem"}`; return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue3.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue3.origin} m\xE9rete t\xFAl kicsi ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue3.origin} t\xFAl kicsi ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; if (_issue.format === "ends_with") return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; if (_issue.format === "includes") return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; if (_issue.format === "regex") return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; return `\xC9rv\xE9nytelen ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\xC9rv\xE9nytelen sz\xE1m: ${issue3.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; case "unrecognized_keys": return `Ismeretlen kulcs${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\xC9rv\xE9nytelen kulcs ${issue3.origin}`; case "invalid_union": return "\xC9rv\xE9nytelen bemenet"; case "invalid_element": return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue3.origin}`; default: return `\xC9rv\xE9nytelen bemenet`; } }; }; function hu_default2() { return { localeError: error65() }; } var error66 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "input", email: "alamat email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Input tidak valid: diharapkan ${issue3.expected}, diterima ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Input tidak valid: diharapkan ${stringifyPrimitive2(issue3.values[0])}`; return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} memiliki ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} menjadi ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Terlalu kecil: diharapkan ${issue3.origin} memiliki ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: diharapkan ${issue3.origin} menjadi ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak valid: harus menyertakan "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak valid: harus sesuai pola ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} tidak valid`; } case "not_multiple_of": return `Angka tidak valid: harus kelipatan dari ${issue3.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Kunci tidak valid di ${issue3.origin}`; case "invalid_union": return "Input tidak valid"; case "invalid_element": return `Nilai tidak valid di ${issue3.origin}`; default: return `Input tidak valid`; } }; }; function id_default2() { return { localeError: error66() }; } var error67 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "numero"; } case "object": { if (Array.isArray(data)) { return "vettore"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "input", email: "indirizzo email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Input non valido: atteso ${issue3.expected}, ricevuto ${parsedType5(issue3.input)}`; // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Input non valido: atteso ${stringifyPrimitive2(issue3.values[0])}`; return `Opzione non valida: atteso uno tra ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Troppo grande: ${issue3.origin ?? "valore"} deve avere ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementi"}`; return `Troppo grande: ${issue3.origin ?? "valore"} deve essere ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Troppo piccolo: ${issue3.origin} deve avere ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Troppo piccolo: ${issue3.origin} deve essere ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Stringa non valida: deve terminare con "${_issue.suffix}"`; if (_issue.format === "includes") return `Stringa non valida: deve includere "${_issue.includes}"`; if (_issue.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Numero non valido: deve essere un multiplo di ${issue3.divisor}`; case "unrecognized_keys": return `Chiav${issue3.keys.length > 1 ? "i" : "e"} non riconosciut${issue3.keys.length > 1 ? "e" : "a"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Chiave non valida in ${issue3.origin}`; case "invalid_union": return "Input non valido"; case "invalid_element": return `Valore non valido in ${issue3.origin}`; default: return `Input non valido`; } }; }; function it_default2() { return { localeError: error67() }; } var error68 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u6570\u5024"; } case "object": { if (Array.isArray(data)) { return "\u914D\u5217"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u5165\u529B\u5024", email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", url: "URL", emoji: "\u7D75\u6587\u5B57", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u6642", date: "ISO\u65E5\u4ED8", time: "ISO\u6642\u523B", duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u7121\u52B9\u306A\u5165\u529B: ${issue3.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${parsedType5(issue3.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; case "invalid_value": if (issue3.values.length === 1) return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive2(issue3.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues2(issue3.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "too_big": { const adj = issue3.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; const sizing = getSizing(issue3.origin); if (sizing) return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue3.origin ?? "\u5024"}\u306F${issue3.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue3.origin ?? "\u5024"}\u306F${issue3.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "too_small": { const adj = issue3.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; const sizing = getSizing(issue3.origin); if (sizing) return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue3.origin}\u306F${issue3.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue3.origin}\u306F${issue3.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "ends_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "includes") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "regex") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u7121\u52B9\u306A${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u7121\u52B9\u306A\u6570\u5024: ${issue3.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "unrecognized_keys": return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue3.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues2(issue3.keys, "\u3001")}`; case "invalid_key": return `${issue3.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; case "invalid_union": return "\u7121\u52B9\u306A\u5165\u529B"; case "invalid_element": return `${issue3.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; default: return `\u7121\u52B9\u306A\u5165\u529B`; } }; }; function ja_default2() { return { localeError: error68() }; } var error69 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781"; } case "object": { if (Array.isArray(data)) { return "\u17A2\u17B6\u179A\u17C1 (Array)"; } if (data === null) { return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", url: "URL", emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", time: "\u1798\u17C9\u17C4\u1784 ISO", duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive2(issue3.values[0])}`; return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin} ${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; if (_issue.format === "regex") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue3.divisor}`; case "unrecognized_keys": return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue3.origin}`; case "invalid_union": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; case "invalid_element": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue3.origin}`; default: return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; } }; }; function kh_default2() { return { localeError: error69() }; } var error70 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, set: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\uC785\uB825", email: "\uC774\uBA54\uC77C \uC8FC\uC18C", url: "URL", emoji: "\uC774\uBAA8\uC9C0", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", date: "ISO \uB0A0\uC9DC", time: "ISO \uC2DC\uAC04", duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", jwt: "JWT", template_literal: "\uC785\uB825" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${issue3.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${parsedType5(issue3.input)}\uC785\uB2C8\uB2E4`; case "invalid_value": if (issue3.values.length === 1) return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive2(issue3.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues2(issue3.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "too_big": { const adj = issue3.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue3.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue3.maximum.toString()}${unit} ${adj}${suffix}`; return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue3.maximum.toString()} ${adj}${suffix}`; } case "too_small": { const adj = issue3.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue3.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) { return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue3.minimum.toString()}${unit} ${adj}${suffix}`; } return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue3.minimum.toString()} ${adj}${suffix}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; } if (_issue.format === "ends_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "includes") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "regex") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue3.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "unrecognized_keys": return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\uC798\uBABB\uB41C \uD0A4: ${issue3.origin}`; case "invalid_union": return `\uC798\uBABB\uB41C \uC785\uB825`; case "invalid_element": return `\uC798\uBABB\uB41C \uAC12: ${issue3.origin}`; default: return `\uC798\uBABB\uB41C \uC785\uB825`; } }; }; function ko_default2() { return { localeError: error70() }; } var error71 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0431\u0440\u043E\u0458"; } case "object": { if (Array.isArray(data)) { return "\u043D\u0438\u0437\u0430"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0432\u043D\u0435\u0441", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", url: "URL", emoji: "\u0435\u043C\u043E\u045F\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0443\u043C", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${parsedType5(issue3.input)}`; // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`; return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue3.divisor}`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue3.origin}`; case "invalid_union": return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; case "invalid_element": return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue3.origin}`; default: return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; } }; }; function mk_default2() { return { localeError: error71() }; } var error72 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "nombor"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "input", email: "alamat e-mel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Input tidak sah: dijangka ${issue3.expected}, diterima ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Input tidak sah: dijangka ${stringifyPrimitive2(issue3.values[0])}`; return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} adalah ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Terlalu kecil: dijangka ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: dijangka ${issue3.origin} adalah ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak sah: mesti mengandungi "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} tidak sah`; } case "not_multiple_of": return `Nombor tidak sah: perlu gandaan ${issue3.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Kunci tidak sah dalam ${issue3.origin}`; case "invalid_union": return "Input tidak sah"; case "invalid_element": return `Nilai tidak sah dalam ${issue3.origin}`; default: return `Input tidak sah`; } }; }; function ms_default2() { return { localeError: error72() }; } var error73 = () => { const Sizable = { string: { unit: "tekens" }, file: { unit: "bytes" }, array: { unit: "elementen" }, set: { unit: "elementen" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "getal"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "invoer", email: "emailadres", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Ongeldige invoer: verwacht ${issue3.expected}, ontving ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Ongeldige invoer: verwacht ${stringifyPrimitive2(issue3.values[0])}`; return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Te lang: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`; return `Te lang: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} is`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} bevat`; } return `Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} is`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; } if (_issue.format === "ends_with") return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; if (_issue.format === "includes") return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; if (_issue.format === "regex") return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; return `Ongeldig: ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ongeldig getal: moet een veelvoud van ${issue3.divisor} zijn`; case "unrecognized_keys": return `Onbekende key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Ongeldige key in ${issue3.origin}`; case "invalid_union": return "Ongeldige invoer"; case "invalid_element": return `Ongeldige waarde in ${issue3.origin}`; default: return `Ongeldige invoer`; } }; }; function nl_default2() { return { localeError: error73() }; } var error74 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, set: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "tall"; } case "object": { if (Array.isArray(data)) { return "liste"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "input", email: "e-postadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Ugyldig input: forventet ${issue3.expected}, fikk ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Ugyldig verdi: forventet ${stringifyPrimitive2(issue3.values[0])}`; return `Ugyldig valg: forventet en av ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `For stor(t): forventet ${issue3.origin ?? "value"} til \xE5 ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor(t): forventet ${issue3.origin ?? "value"} til \xE5 ha ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `For lite(n): forventet ${issue3.origin} til \xE5 ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `For lite(n): forventet ${issue3.origin} til \xE5 ha ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue3.divisor}`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8kkel i ${issue3.origin}`; case "invalid_union": return "Ugyldig input"; case "invalid_element": return `Ugyldig verdi i ${issue3.origin}`; default: return `Ugyldig input`; } }; }; function no_default2() { return { localeError: error74() }; } var error75 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "numara"; } case "object": { if (Array.isArray(data)) { return "saf"; } if (data === null) { return "gayb"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "giren", email: "epostag\xE2h", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO heng\xE2m\u0131", date: "ISO tarihi", time: "ISO zaman\u0131", duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "giren" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `F\xE2sit giren: umulan ${issue3.expected}, al\u0131nan ${parsedType5(issue3.input)}`; // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `F\xE2sit giren: umulan ${stringifyPrimitive2(issue3.values[0])}`; return `F\xE2sit tercih: m\xFBteberler ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Fazla b\xFCy\xFCk: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; return `Fazla b\xFCy\xFCk: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} olmal\u0131yd\u0131.`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Fazla k\xFC\xE7\xFCk: ${issue3.origin}, ${adj}${issue3.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; } return `Fazla k\xFC\xE7\xFCk: ${issue3.origin}, ${adj}${issue3.minimum.toString()} olmal\u0131yd\u0131.`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; if (_issue.format === "ends_with") return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; if (_issue.format === "includes") return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; if (_issue.format === "regex") return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; return `F\xE2sit ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `F\xE2sit say\u0131: ${issue3.divisor} kat\u0131 olmal\u0131yd\u0131.`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} i\xE7in tan\u0131nmayan anahtar var.`; case "invalid_union": return "Giren tan\u0131namad\u0131."; case "invalid_element": return `${issue3.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; default: return `K\u0131ymet tan\u0131namad\u0131.`; } }; }; function ota_default2() { return { localeError: error75() }; } var error76 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; } case "object": { if (Array.isArray(data)) { return "\u0627\u0631\u06D0"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0648\u0631\u0648\u062F\u064A", email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", date: "\u0646\u06D0\u067C\u0647", time: "\u0648\u062E\u062A", duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${issue3.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${parsedType5(issue3.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; case "invalid_value": if (issue3.values.length === 1) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive2(issue3.values[0])} \u0648\u0627\u06CC`; } return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues2(issue3.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue3.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue3.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} \u0648\u064A`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} \u0648\u064A`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; } if (_issue.format === "ends_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; } if (_issue.format === "includes") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; } if (_issue.format === "regex") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; } return `${Nouns[_issue.format] ?? issue3.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; } case "not_multiple_of": return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue3.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; case "unrecognized_keys": return `\u0646\u0627\u0633\u0645 ${issue3.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue3.origin} \u06A9\u06D0`; case "invalid_union": return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; case "invalid_element": return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue3.origin} \u06A9\u06D0`; default: return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; } }; }; function ps_default2() { return { localeError: error76() }; } var error77 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, set: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "liczba"; } case "object": { if (Array.isArray(data)) { return "tablica"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "wyra\u017Cenie", email: "adres email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wej\u015Bcie" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${issue3.expected}, otrzymano ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive2(issue3.values[0])}`; return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; if (_issue.format === "includes") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; if (_issue.format === "regex") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; return `Nieprawid\u0142ow(y/a/e) ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue3.divisor}`; case "unrecognized_keys": return `Nierozpoznane klucze${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Nieprawid\u0142owy klucz w ${issue3.origin}`; case "invalid_union": return "Nieprawid\u0142owe dane wej\u015Bciowe"; case "invalid_element": return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue3.origin}`; default: return `Nieprawid\u0142owe dane wej\u015Bciowe`; } }; }; function pl_default2() { return { localeError: error77() }; } var error78 = () => { const Sizable = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "n\xFAmero"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "nulo"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "padr\xE3o", email: "endere\xE7o de e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "dura\xE7\xE3o ISO", ipv4: "endere\xE7o IPv4", ipv6: "endere\xE7o IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Tipo inv\xE1lido: esperado ${issue3.expected}, recebido ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Entrada inv\xE1lida: esperado ${stringifyPrimitive2(issue3.values[0])}`; return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Muito grande: esperado que ${issue3.origin ?? "valor"} tivesse ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Muito grande: esperado que ${issue3.origin ?? "valor"} fosse ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Muito pequeno: esperado que ${issue3.origin} tivesse ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Muito pequeno: esperado que ${issue3.origin} fosse ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue3.divisor}`; case "unrecognized_keys": return `Chave${issue3.keys.length > 1 ? "s" : ""} desconhecida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Chave inv\xE1lida em ${issue3.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido em ${issue3.origin}`; default: return `Campo inv\xE1lido`; } }; }; function pt_default2() { return { localeError: error78() }; } function getRussianPlural2(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error79 = () => { const Sizable = { string: { unit: { one: "\u0441\u0438\u043C\u0432\u043E\u043B", few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u0430", many: "\u0431\u0430\u0439\u0442" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0441\u0438\u0432"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0432\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u044F", duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${issue3.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive2(issue3.values[0])}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { const maxValue = Number(issue3.maximum); const unit = getRussianPlural2(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue3.maximum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { const minValue = Number(issue3.minimum); const unit = getRussianPlural2(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue3.minimum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue3.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue3.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue3.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u0438" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue3.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; case "invalid_element": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue3.origin}`; default: return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; } }; }; function ru_default2() { return { localeError: error79() }; } var error80 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0161tevilo"; } case "object": { if (Array.isArray(data)) { return "tabela"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "vnos", email: "e-po\u0161tni naslov", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum in \u010Das", date: "ISO datum", time: "ISO \u010Das", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", jwt: "JWT", template_literal: "vnos" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Neveljaven vnos: pri\u010Dakovano ${issue3.expected}, prejeto ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive2(issue3.values[0])}`; return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Preveliko: pri\u010Dakovano, da bo ${issue3.origin ?? "vrednost"} imelo ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementov"}`; return `Preveliko: pri\u010Dakovano, da bo ${issue3.origin ?? "vrednost"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Premajhno: pri\u010Dakovano, da bo ${issue3.origin} imelo ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Premajhno: pri\u010Dakovano, da bo ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; if (_issue.format === "includes") return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; if (_issue.format === "regex") return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; return `Neveljaven ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue3.divisor}`; case "unrecognized_keys": return `Neprepoznan${issue3.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Neveljaven klju\u010D v ${issue3.origin}`; case "invalid_union": return "Neveljaven vnos"; case "invalid_element": return `Neveljavna vrednost v ${issue3.origin}`; default: return "Neveljaven vnos"; } }; }; function sl_default2() { return { localeError: error80() }; } var error81 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, set: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "antal"; } case "object": { if (Array.isArray(data)) { return "lista"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "regulj\xE4rt uttryck", email: "e-postadress", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Ogiltig inmatning: f\xF6rv\xE4ntat ${issue3.expected}, fick ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive2(issue3.values[0])}`; return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; } return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; if (_issue.format === "regex") return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; return `Ogiltig(t) ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue3.divisor}`; case "unrecognized_keys": return `${issue3.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Ogiltig nyckel i ${issue3.origin ?? "v\xE4rdet"}`; case "invalid_union": return "Ogiltig input"; case "invalid_element": return `Ogiltigt v\xE4rde i ${issue3.origin ?? "v\xE4rdet"}`; default: return `Ogiltig input`; } }; }; function sv_default2() { return { localeError: error81() }; } var error82 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD"; } case "object": { if (Array.isArray(data)) { return "\u0B85\u0BA3\u0BBF"; } if (data === null) { return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", jwt: "JWT", template_literal: "input" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive2(issue3.values[0])}`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues2(issue3.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue3.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue3.origin} ${adj}${issue3.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "ends_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "includes") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "regex") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue3.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; case "unrecognized_keys": return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue3.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; case "invalid_union": return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; case "invalid_element": return `${issue3.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; default: return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; } }; }; function ta_default2() { return { localeError: error82() }; } var error83 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02"; } case "object": { if (Array.isArray(data)) { return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)"; } if (data === null) { return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", url: "URL", emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${issue3.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive2(issue3.values[0])}`; return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue3.origin); if (sizing) return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; if (_issue.format === "regex") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue3.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; case "unrecognized_keys": return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue3.origin}`; case "invalid_union": return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; case "invalid_element": return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue3.origin}`; default: return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; } }; }; function th_default2() { return { localeError: error83() }; } var parsedType4 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; var error84 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const Nouns = { regex: "girdi", email: "e-posta adresi", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `Ge\xE7ersiz de\u011Fer: beklenen ${issue3.expected}, al\u0131nan ${parsedType4(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive2(issue3.values[0])}`; return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ok b\xFCy\xFCk: beklenen ${issue3.origin ?? "de\u011Fer"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; return `\xC7ok b\xFCy\xFCk: beklenen ${issue3.origin ?? "de\u011Fer"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; if (_issue.format === "ends_with") return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; if (_issue.format === "includes") return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; if (_issue.format === "regex") return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; return `Ge\xE7ersiz ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `Ge\xE7ersiz say\u0131: ${issue3.divisor} ile tam b\xF6l\xFCnebilmeli`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} i\xE7inde ge\xE7ersiz anahtar`; case "invalid_union": return "Ge\xE7ersiz de\u011Fer"; case "invalid_element": return `${issue3.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; default: return `Ge\xE7ersiz de\u011Fer`; } }; }; function tr_default2() { return { localeError: error84() }; } var error85 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; } case "object": { if (Array.isArray(data)) { return "\u043C\u0430\u0441\u0438\u0432"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", date: "\u0434\u0430\u0442\u0430 ISO", time: "\u0447\u0430\u0441 ISO", duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${issue3.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${parsedType5(issue3.input)}`; // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive2(issue3.values[0])}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue3.origin} \u0431\u0443\u0434\u0435 ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue3.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u0456" : ""}: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue3.origin}`; case "invalid_union": return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; case "invalid_element": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue3.origin}`; default: return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; } }; }; function ua_default2() { return { localeError: error85() }; } var error86 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "\u0646\u0645\u0628\u0631"; } case "object": { if (Array.isArray(data)) { return "\u0622\u0631\u06D2"; } if (data === null) { return "\u0646\u0644"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0627\u0646 \u067E\u0679", email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${issue3.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${parsedType5(issue3.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; case "invalid_value": if (issue3.values.length === 1) return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive2(issue3.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues2(issue3.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue3.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue3.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue3.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue3.origin} \u06A9\u06D2 ${adj}${issue3.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; } return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue3.origin} \u06A9\u0627 ${adj}${issue3.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; } if (_issue.format === "ends_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "includes") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "regex") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; return `\u063A\u0644\u0637 ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue3.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; case "unrecognized_keys": return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue3.keys.length > 1 ? "\u0632" : ""}: ${joinValues2(issue3.keys, "\u060C ")}`; case "invalid_key": return `${issue3.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; case "invalid_union": return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; case "invalid_element": return `${issue3.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; default: return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; } }; }; function ur_default2() { return { localeError: error86() }; } var error87 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "s\u1ED1"; } case "object": { if (Array.isArray(data)) { return "m\u1EA3ng"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u0111\u1EA7u v\xE0o", email: "\u0111\u1ECBa ch\u1EC9 email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ng\xE0y gi\u1EDD ISO", date: "ng\xE0y ISO", time: "gi\u1EDD ISO", duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${issue3.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive2(issue3.values[0])}`; return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue3.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue3.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; if (_issue.format === "includes") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; if (_issue.format === "regex") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; return `${Nouns[_issue.format] ?? issue3.format} kh\xF4ng h\u1EE3p l\u1EC7`; } case "not_multiple_of": return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue3.divisor}`; case "unrecognized_keys": return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue3.origin}`; case "invalid_union": return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; case "invalid_element": return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue3.origin}`; default: return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; } }; }; function vi_default2() { return { localeError: error87() }; } var error88 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, set: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57"; } case "object": { if (Array.isArray(data)) { return "\u6570\u7EC4"; } if (data === null) { return "\u7A7A\u503C(null)"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u8F93\u5165", email: "\u7535\u5B50\u90AE\u4EF6", url: "URL", emoji: "\u8868\u60C5\u7B26\u53F7", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u671F\u65F6\u95F4", date: "ISO\u65E5\u671F", time: "ISO\u65F6\u95F4", duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", jwt: "JWT", template_literal: "\u8F93\u5165" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${issue3.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive2(issue3.values[0])}`; return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue3.origin ?? "\u503C"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue3.origin ?? "\u503C"} ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; if (_issue.format === "ends_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; if (_issue.format === "includes") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; return `\u65E0\u6548${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue3.divisor} \u7684\u500D\u6570`; case "unrecognized_keys": return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues2(issue3.keys, ", ")}`; case "invalid_key": return `${issue3.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; case "invalid_union": return "\u65E0\u6548\u8F93\u5165"; case "invalid_element": return `${issue3.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; default: return `\u65E0\u6548\u8F93\u5165`; } }; }; function zh_CN_default2() { return { localeError: error88() }; } var error89 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const parsedType5 = (data) => { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "NaN" : "number"; } case "object": { if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { return data.constructor.name; } } } return t; }; const Nouns = { regex: "\u8F38\u5165", email: "\u90F5\u4EF6\u5730\u5740", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u65E5\u671F\u6642\u9593", date: "ISO \u65E5\u671F", time: "ISO \u6642\u9593", duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", jwt: "JWT", template_literal: "\u8F38\u5165" }; return (issue3) => { switch (issue3.code) { case "invalid_type": return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${issue3.expected}\uFF0C\u4F46\u6536\u5230 ${parsedType5(issue3.input)}`; case "invalid_value": if (issue3.values.length === 1) return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive2(issue3.values[0])}`; return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues2(issue3.values, "|")}`; case "too_big": { const adj = issue3.inclusive ? "<=" : "<"; const sizing = getSizing(issue3.origin); if (sizing) return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue3.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue3.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue3.maximum.toString()}`; } case "too_small": { const adj = issue3.inclusive ? ">=" : ">"; const sizing = getSizing(issue3.origin); if (sizing) { return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue3.origin} \u61C9\u70BA ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue3.origin} \u61C9\u70BA ${adj}${issue3.minimum.toString()}`; } case "invalid_format": { const _issue = issue3; if (_issue.format === "starts_with") { return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; } if (_issue.format === "ends_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; if (_issue.format === "includes") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; return `\u7121\u6548\u7684 ${Nouns[_issue.format] ?? issue3.format}`; } case "not_multiple_of": return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue3.divisor} \u7684\u500D\u6578`; case "unrecognized_keys": return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue3.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues2(issue3.keys, "\u3001")}`; case "invalid_key": return `${issue3.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; case "invalid_union": return "\u7121\u6548\u7684\u8F38\u5165\u503C"; case "invalid_element": return `${issue3.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; default: return `\u7121\u6548\u7684\u8F38\u5165\u503C`; } }; }; function zh_TW_default2() { return { localeError: error89() }; } var $output2 = /* @__PURE__ */ Symbol("ZodOutput"); var $input2 = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry2 = class { constructor() { this._map = /* @__PURE__ */ new Map(); this._idmap = /* @__PURE__ */ new Map(); } add(schema, ..._meta) { const meta3 = _meta[0]; this._map.set(schema, meta3); if (meta3 && typeof meta3 === "object" && "id" in meta3) { if (this._idmap.has(meta3.id)) { throw new Error(`ID ${meta3.id} already exists in the registry`); } this._idmap.set(meta3.id, schema); } return this; } clear() { this._map = /* @__PURE__ */ new Map(); this._idmap = /* @__PURE__ */ new Map(); return this; } remove(schema) { const meta3 = this._map.get(schema); if (meta3 && typeof meta3 === "object" && "id" in meta3) { this._idmap.delete(meta3.id); } this._map.delete(schema); return this; } get(schema) { const p = schema._zod.parent; if (p) { const pm = { ...this.get(p) ?? {} }; delete pm.id; return { ...pm, ...this._map.get(schema) }; } return this._map.get(schema); } has(schema) { return this._map.has(schema); } }; function registry2() { return new $ZodRegistry2(); } var globalRegistry2 = /* @__PURE__ */ registry2(); function _string2(Class3, params) { return new Class3({ type: "string", ...normalizeParams2(params) }); } function _coercedString2(Class3, params) { return new Class3({ type: "string", coerce: true, ...normalizeParams2(params) }); } function _email2(Class3, params) { return new Class3({ type: "string", format: "email", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _guid2(Class3, params) { return new Class3({ type: "string", format: "guid", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _uuid2(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _uuidv42(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...normalizeParams2(params) }); } function _uuidv62(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...normalizeParams2(params) }); } function _uuidv72(Class3, params) { return new Class3({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...normalizeParams2(params) }); } function _url2(Class3, params) { return new Class3({ type: "string", format: "url", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _emoji4(Class3, params) { return new Class3({ type: "string", format: "emoji", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _nanoid2(Class3, params) { return new Class3({ type: "string", format: "nanoid", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _cuid3(Class3, params) { return new Class3({ type: "string", format: "cuid", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _cuid22(Class3, params) { return new Class3({ type: "string", format: "cuid2", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _ulid2(Class3, params) { return new Class3({ type: "string", format: "ulid", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _xid2(Class3, params) { return new Class3({ type: "string", format: "xid", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _ksuid2(Class3, params) { return new Class3({ type: "string", format: "ksuid", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _ipv42(Class3, params) { return new Class3({ type: "string", format: "ipv4", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _ipv62(Class3, params) { return new Class3({ type: "string", format: "ipv6", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _cidrv42(Class3, params) { return new Class3({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _cidrv62(Class3, params) { return new Class3({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _base642(Class3, params) { return new Class3({ type: "string", format: "base64", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _base64url2(Class3, params) { return new Class3({ type: "string", format: "base64url", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _e1642(Class3, params) { return new Class3({ type: "string", format: "e164", check: "string_format", abort: false, ...normalizeParams2(params) }); } function _jwt2(Class3, params) { return new Class3({ type: "string", format: "jwt", check: "string_format", abort: false, ...normalizeParams2(params) }); } var TimePrecision2 = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 }; function _isoDateTime2(Class3, params) { return new Class3({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...normalizeParams2(params) }); } function _isoDate2(Class3, params) { return new Class3({ type: "string", format: "date", check: "string_format", ...normalizeParams2(params) }); } function _isoTime2(Class3, params) { return new Class3({ type: "string", format: "time", check: "string_format", precision: null, ...normalizeParams2(params) }); } function _isoDuration2(Class3, params) { return new Class3({ type: "string", format: "duration", check: "string_format", ...normalizeParams2(params) }); } function _number2(Class3, params) { return new Class3({ type: "number", checks: [], ...normalizeParams2(params) }); } function _coercedNumber2(Class3, params) { return new Class3({ type: "number", coerce: true, checks: [], ...normalizeParams2(params) }); } function _int2(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "safeint", ...normalizeParams2(params) }); } function _float322(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "float32", ...normalizeParams2(params) }); } function _float642(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "float64", ...normalizeParams2(params) }); } function _int322(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "int32", ...normalizeParams2(params) }); } function _uint322(Class3, params) { return new Class3({ type: "number", check: "number_format", abort: false, format: "uint32", ...normalizeParams2(params) }); } function _boolean2(Class3, params) { return new Class3({ type: "boolean", ...normalizeParams2(params) }); } function _coercedBoolean2(Class3, params) { return new Class3({ type: "boolean", coerce: true, ...normalizeParams2(params) }); } function _bigint2(Class3, params) { return new Class3({ type: "bigint", ...normalizeParams2(params) }); } function _coercedBigint2(Class3, params) { return new Class3({ type: "bigint", coerce: true, ...normalizeParams2(params) }); } function _int642(Class3, params) { return new Class3({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...normalizeParams2(params) }); } function _uint642(Class3, params) { return new Class3({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...normalizeParams2(params) }); } function _symbol2(Class3, params) { return new Class3({ type: "symbol", ...normalizeParams2(params) }); } function _undefined5(Class3, params) { return new Class3({ type: "undefined", ...normalizeParams2(params) }); } function _null5(Class3, params) { return new Class3({ type: "null", ...normalizeParams2(params) }); } function _any2(Class3) { return new Class3({ type: "any" }); } function _unknown2(Class3) { return new Class3({ type: "unknown" }); } function _never2(Class3, params) { return new Class3({ type: "never", ...normalizeParams2(params) }); } function _void3(Class3, params) { return new Class3({ type: "void", ...normalizeParams2(params) }); } function _date2(Class3, params) { return new Class3({ type: "date", ...normalizeParams2(params) }); } function _coercedDate2(Class3, params) { return new Class3({ type: "date", coerce: true, ...normalizeParams2(params) }); } function _nan2(Class3, params) { return new Class3({ type: "nan", ...normalizeParams2(params) }); } function _lt2(value, params) { return new $ZodCheckLessThan2({ check: "less_than", ...normalizeParams2(params), value, inclusive: false }); } function _lte2(value, params) { return new $ZodCheckLessThan2({ check: "less_than", ...normalizeParams2(params), value, inclusive: true }); } function _gt2(value, params) { return new $ZodCheckGreaterThan2({ check: "greater_than", ...normalizeParams2(params), value, inclusive: false }); } function _gte2(value, params) { return new $ZodCheckGreaterThan2({ check: "greater_than", ...normalizeParams2(params), value, inclusive: true }); } function _positive2(params) { return _gt2(0, params); } function _negative2(params) { return _lt2(0, params); } function _nonpositive2(params) { return _lte2(0, params); } function _nonnegative2(params) { return _gte2(0, params); } function _multipleOf2(value, params) { return new $ZodCheckMultipleOf2({ check: "multiple_of", ...normalizeParams2(params), value }); } function _maxSize2(maximum, params) { return new $ZodCheckMaxSize2({ check: "max_size", ...normalizeParams2(params), maximum }); } function _minSize2(minimum, params) { return new $ZodCheckMinSize2({ check: "min_size", ...normalizeParams2(params), minimum }); } function _size2(size, params) { return new $ZodCheckSizeEquals2({ check: "size_equals", ...normalizeParams2(params), size }); } function _maxLength2(maximum, params) { const ch = new $ZodCheckMaxLength2({ check: "max_length", ...normalizeParams2(params), maximum }); return ch; } function _minLength2(minimum, params) { return new $ZodCheckMinLength2({ check: "min_length", ...normalizeParams2(params), minimum }); } function _length2(length, params) { return new $ZodCheckLengthEquals2({ check: "length_equals", ...normalizeParams2(params), length }); } function _regex2(pattern, params) { return new $ZodCheckRegex2({ check: "string_format", format: "regex", ...normalizeParams2(params), pattern }); } function _lowercase2(params) { return new $ZodCheckLowerCase2({ check: "string_format", format: "lowercase", ...normalizeParams2(params) }); } function _uppercase2(params) { return new $ZodCheckUpperCase2({ check: "string_format", format: "uppercase", ...normalizeParams2(params) }); } function _includes2(includes, params) { return new $ZodCheckIncludes2({ check: "string_format", format: "includes", ...normalizeParams2(params), includes }); } function _startsWith2(prefix, params) { return new $ZodCheckStartsWith2({ check: "string_format", format: "starts_with", ...normalizeParams2(params), prefix }); } function _endsWith2(suffix, params) { return new $ZodCheckEndsWith2({ check: "string_format", format: "ends_with", ...normalizeParams2(params), suffix }); } function _property2(property, schema, params) { return new $ZodCheckProperty2({ check: "property", property, schema, ...normalizeParams2(params) }); } function _mime2(types, params) { return new $ZodCheckMimeType2({ check: "mime_type", mime: types, ...normalizeParams2(params) }); } function _overwrite2(tx) { return new $ZodCheckOverwrite2({ check: "overwrite", tx }); } function _normalize2(form) { return _overwrite2((input) => input.normalize(form)); } function _trim2() { return _overwrite2((input) => input.trim()); } function _toLowerCase2() { return _overwrite2((input) => input.toLowerCase()); } function _toUpperCase2() { return _overwrite2((input) => input.toUpperCase()); } function _array2(Class3, element, params) { return new Class3({ type: "array", element, // get element() { // return element; // }, ...normalizeParams2(params) }); } function _union2(Class3, options, params) { return new Class3({ type: "union", options, ...normalizeParams2(params) }); } function _discriminatedUnion2(Class3, discriminator, options, params) { return new Class3({ type: "union", options, discriminator, ...normalizeParams2(params) }); } function _intersection2(Class3, left, right) { return new Class3({ type: "intersection", left, right }); } function _tuple2(Class3, items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType2; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new Class3({ type: "tuple", items, rest, ...normalizeParams2(params) }); } function _record2(Class3, keyType, valueType, params) { return new Class3({ type: "record", keyType, valueType, ...normalizeParams2(params) }); } function _map2(Class3, keyType, valueType, params) { return new Class3({ type: "map", keyType, valueType, ...normalizeParams2(params) }); } function _set2(Class3, valueType, params) { return new Class3({ type: "set", valueType, ...normalizeParams2(params) }); } function _enum3(Class3, values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new Class3({ type: "enum", entries, ...normalizeParams2(params) }); } function _nativeEnum2(Class3, entries, params) { return new Class3({ type: "enum", entries, ...normalizeParams2(params) }); } function _literal2(Class3, value, params) { return new Class3({ type: "literal", values: Array.isArray(value) ? value : [value], ...normalizeParams2(params) }); } function _file2(Class3, params) { return new Class3({ type: "file", ...normalizeParams2(params) }); } function _transform2(Class3, fn) { return new Class3({ type: "transform", transform: fn }); } function _optional2(Class3, innerType) { return new Class3({ type: "optional", innerType }); } function _nullable2(Class3, innerType) { return new Class3({ type: "nullable", innerType }); } function _default3(Class3, innerType, defaultValue) { return new Class3({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; } }); } function _nonoptional2(Class3, innerType, params) { return new Class3({ type: "nonoptional", innerType, ...normalizeParams2(params) }); } function _success2(Class3, innerType) { return new Class3({ type: "success", innerType }); } function _catch3(Class3, innerType, catchValue) { return new Class3({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } function _pipe2(Class3, in_, out) { return new Class3({ type: "pipe", in: in_, out }); } function _readonly2(Class3, innerType) { return new Class3({ type: "readonly", innerType }); } function _templateLiteral2(Class3, parts, params) { return new Class3({ type: "template_literal", parts, ...normalizeParams2(params) }); } function _lazy2(Class3, getter) { return new Class3({ type: "lazy", getter }); } function _promise2(Class3, innerType) { return new Class3({ type: "promise", innerType }); } function _custom2(Class3, fn, _params) { const norm = normalizeParams2(_params); norm.abort ?? (norm.abort = true); const schema = new Class3({ type: "custom", check: "custom", fn, ...norm }); return schema; } function _refine2(Class3, fn, _params) { const schema = new Class3({ type: "custom", check: "custom", fn, ...normalizeParams2(_params) }); return schema; } function _stringbool2(Classes, _params) { const params = normalizeParams2(_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 ?? $ZodPipe2; const _Boolean = Classes.Boolean ?? $ZodBoolean2; const _String = Classes.String ?? $ZodString2; const _Transform = Classes.Transform ?? $ZodTransform2; 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 }); 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 _stringFormat2(Class3, format, fnOrRegex, _params = {}) { const params = normalizeParams2(_params); const def = { ...normalizeParams2(_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 Class3(def); return inst; } var $ZodFunction2 = class { constructor(def) { this._def = def; this.def = def; } implement(func) { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } const impl = ((...args) => { const parsedArgs = this._def.input ? parse3(this._def.input, args, void 0, { callee: impl }) : args; if (!Array.isArray(parsedArgs)) { throw new Error("Invalid arguments schema: not an array or tuple schema."); } const output = func(...parsedArgs); return this._def.output ? parse3(this._def.output, output, void 0, { callee: impl }) : output; }); return impl; } implementAsync(func) { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } const impl = (async (...args) => { const parsedArgs = this._def.input ? await parseAsync3(this._def.input, args, void 0, { callee: impl }) : args; if (!Array.isArray(parsedArgs)) { throw new Error("Invalid arguments schema: not an array or tuple schema."); } const output = await func(...parsedArgs); return this._def.output ? parseAsync3(this._def.output, output, void 0, { callee: impl }) : output; }); return impl; } input(...args) { const F2 = this.constructor; if (Array.isArray(args[0])) { return new F2({ type: "function", input: new $ZodTuple2({ type: "tuple", items: args[0], rest: args[1] }), output: this._def.output }); } return new F2({ type: "function", input: args[0], output: this._def.output }); } output(output) { const F2 = this.constructor; return new F2({ type: "function", input: this._def.input, output }); } }; function _function2(params) { return new $ZodFunction2({ type: "function", input: Array.isArray(params?.input) ? _tuple2($ZodTuple2, params?.input) : params?.input ?? _array2($ZodArray2, _unknown2($ZodUnknown2)), output: params?.output ?? _unknown2($ZodUnknown2) }); } var JSONSchemaGenerator2 = class { constructor(params) { this.counter = 0; this.metadataRegistry = params?.metadata ?? globalRegistry2; this.target = params?.target ?? "draft-2020-12"; this.unrepresentable = params?.unrepresentable ?? "throw"; this.override = params?.override ?? (() => { }); this.io = params?.io ?? "output"; this.seen = /* @__PURE__ */ new Map(); } process(schema, _params = { path: [], schemaPath: [] }) { var _a282; const def = schema._zod.def; const formatMap2 = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" // do not set }; const seen = this.seen.get(schema); if (seen) { seen.count++; const isCycle = _params.schemaPath.includes(schema); if (isCycle) { seen.cycle = _params.path; } return seen.schema; } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; this.seen.set(schema, result); const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; } else { const params = { ..._params, schemaPath: [..._params.schemaPath, schema], path: _params.path }; const parent = schema._zod.parent; if (parent) { result.ref = parent; this.process(parent, params); this.seen.get(parent).isParent = true; } else { const _json = result.schema; switch (def.type) { case "string": { const json4 = _json; json4.type = "string"; const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; if (typeof minimum === "number") json4.minLength = minimum; if (typeof maximum === "number") json4.maxLength = maximum; if (format) { json4.format = formatMap2[format] ?? format; if (json4.format === "") delete json4.format; } if (contentEncoding) json4.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { const regexes = [...patterns]; if (regexes.length === 1) json4.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 json4 = _json; const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; if (typeof format === "string" && format.includes("int")) json4.type = "integer"; else json4.type = "number"; if (typeof exclusiveMinimum === "number") json4.exclusiveMinimum = exclusiveMinimum; if (typeof minimum === "number") { json4.minimum = minimum; if (typeof exclusiveMinimum === "number") { if (exclusiveMinimum >= minimum) delete json4.minimum; else delete json4.exclusiveMinimum; } } if (typeof exclusiveMaximum === "number") json4.exclusiveMaximum = exclusiveMaximum; if (typeof maximum === "number") { json4.maximum = maximum; if (typeof exclusiveMaximum === "number") { if (exclusiveMaximum <= maximum) delete json4.maximum; else delete json4.exclusiveMaximum; } } if (typeof multipleOf === "number") json4.multipleOf = multipleOf; break; } case "boolean": { const json4 = _json; json4.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 json4 = _json; const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json4.minItems = minimum; if (typeof maximum === "number") json4.maxItems = maximum; json4.type = "array"; json4.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); break; } case "object": { const json4 = _json; json4.type = "object"; json4.properties = {}; const shape = def.shape; for (const key in shape) { json4.properties[key] = this.process(shape[key], { ...params, path: [...params.path, "properties", key] }); } const allKeys = new Set(Object.keys(shape)); const requiredKeys = new Set([...allKeys].filter((key) => { const v = def.shape[key]._zod; if (this.io === "input") { return v.optin === void 0; } else { return v.optout === void 0; } })); if (requiredKeys.size > 0) { json4.required = Array.from(requiredKeys); } if (def.catchall?._zod.def.type === "never") { json4.additionalProperties = false; } else if (!def.catchall) { if (this.io === "output") json4.additionalProperties = false; } else if (def.catchall) { json4.additionalProperties = this.process(def.catchall, { ...params, path: [...params.path, "additionalProperties"] }); } break; } case "union": { const json4 = _json; json4.anyOf = def.options.map((x, i) => this.process(x, { ...params, path: [...params.path, "anyOf", i] })); break; } case "intersection": { const json4 = _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] ]; json4.allOf = allOf; break; } case "tuple": { const json4 = _json; json4.type = "array"; const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); if (this.target === "draft-2020-12") { json4.prefixItems = prefixItems; } else { json4.items = prefixItems; } if (def.rest) { const rest = this.process(def.rest, { ...params, path: [...params.path, "items"] }); if (this.target === "draft-2020-12") { json4.items = rest; } else { json4.additionalItems = rest; } } if (def.rest) { json4.items = this.process(def.rest, { ...params, path: [...params.path, "items"] }); } const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json4.minItems = minimum; if (typeof maximum === "number") json4.maxItems = maximum; break; } case "record": { const json4 = _json; json4.type = "object"; json4.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); json4.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 json4 = _json; const values = getEnumValues2(def.entries); if (values.every((v) => typeof v === "number")) json4.type = "number"; if (values.every((v) => typeof v === "string")) json4.type = "string"; json4.enum = values; break; } case "literal": { const json4 = _json; const vals = []; for (const val of def.values) { if (val === void 0) { if (this.unrepresentable === "throw") { throw new Error("Literal `undefined` cannot be represented in JSON Schema"); } } 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) ; else if (vals.length === 1) { const val = vals[0]; json4.type = val === null ? "null" : typeof val; json4.const = val; } else { if (vals.every((v) => typeof v === "number")) json4.type = "number"; if (vals.every((v) => typeof v === "string")) json4.type = "string"; if (vals.every((v) => typeof v === "boolean")) json4.type = "string"; if (vals.every((v) => v === null)) json4.type = "null"; json4.enum = vals; } break; } case "file": { const json4 = _json; const file3 = { type: "string", format: "binary", contentEncoding: "binary" }; const { minimum, maximum, mime } = schema._zod.bag; if (minimum !== void 0) file3.minLength = minimum; if (maximum !== void 0) file3.maxLength = maximum; if (mime) { if (mime.length === 1) { file3.contentMediaType = mime[0]; Object.assign(json4, file3); } else { json4.anyOf = mime.map((m) => { const mFile = { ...file3, contentMediaType: m }; return mFile; }); } } else { Object.assign(json4, file3); } 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 json4 = _json; json4.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": { this.process(def.innerType, params); result.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } 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 json4 = _json; const pattern = schema._zod.pattern; if (!pattern) throw new Error("Pattern not found in template literal"); json4.type = "string"; json4.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; } } } } const meta3 = this.metadataRegistry.get(schema); if (meta3) Object.assign(result.schema, meta3); if (this.io === "input" && isTransforming2(schema)) { delete result.schema.examples; delete result.schema.default; } if (this.io === "input" && result.schema._prefault) (_a282 = result.schema).default ?? (_a282.default = result.schema._prefault); delete result.schema._prefault; 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 ?? void 0 }; const root = this.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const makeURI = (entry) => { const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; if (params.external) { const externalId = params.external.registry.get(entry[0])?.id; const uriGenerator = params.external.uri ?? ((id2) => id2); if (externalId) { return { ref: uriGenerator(externalId) }; } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; entry[1].defId = id; return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } if (entry[1] === root) { return { ref: "#" }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; const defId = entry[1].schema.id ?? `__schema${this.counter++}`; return { defId, ref: defUriPrefix + defId }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { return; } const seen = entry[1]; const { ref, defId } = makeURI(entry); seen.def = { ...seen.schema }; if (defId) seen.defId = defId; const schema2 = seen.schema; for (const key in schema2) { delete schema2[key]; } schema2.$ref = ref; }; if (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("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); } } } for (const entry of this.seen.entries()) { const seen = entry[1]; if (schema === entry[0]) { extractToDef(entry); continue; } if (params.external) { const ext = params.external.registry.get(entry[0])?.id; if (schema !== entry[0] && ext) { extractToDef(entry); continue; } } const id = this.metadataRegistry.get(entry[0])?.id; if (id) { extractToDef(entry); continue; } if (seen.cycle) { extractToDef(entry); continue; } if (seen.count > 1) { if (params.reused === "ref") { extractToDef(entry); continue; } } } const flattenRef = (zodSchema42, params2) => { const seen = this.seen.get(zodSchema42); const schema2 = seen.def ?? seen.schema; const _cached = { ...schema2 }; if (seen.ref === null) { return; } const ref = seen.ref; seen.ref = null; if (ref) { flattenRef(ref, params2); const refSchema = this.seen.get(ref).schema; if (refSchema.$ref && params2.target === "draft-7") { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { Object.assign(schema2, refSchema); Object.assign(schema2, _cached); } } if (!seen.isParent) this.override({ zodSchema: zodSchema42, jsonSchema: schema2, 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); 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; } } if (params.external) ; else { if (Object.keys(defs).length > 0) { if (this.target === "draft-2020-12") { result.$defs = defs; } else { result.definitions = defs; } } } try { return JSON.parse(JSON.stringify(result)); } catch (_err) { throw new Error("Error converting schema to JSON."); } } }; function toJSONSchema2(input, _params) { if (input instanceof $ZodRegistry2) { const gen2 = new JSONSchemaGenerator2(_params); const defs = {}; for (const entry of input._idmap.entries()) { const [_, schema] = entry; gen2.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] = gen2.emit(schema, { ..._params, external }); } if (Object.keys(defs).length > 0) { const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; schemas.__shared = { [defsSegment]: defs }; } return { schemas }; } const gen = new JSONSchemaGenerator2(_params); gen.process(input); return gen.emit(input, _params); } function isTransforming2(_schema, _ctx) { const ctx = _ctx ?? { seen: /* @__PURE__ */ 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 isTransforming2(def.element, ctx); } case "object": { for (const key in def.shape) { if (isTransforming2(def.shape[key], ctx)) return true; } return false; } case "union": { for (const option of def.options) { if (isTransforming2(option, ctx)) return true; } return false; } case "intersection": { return isTransforming2(def.left, ctx) || isTransforming2(def.right, ctx); } case "tuple": { for (const item of def.items) { if (isTransforming2(item, ctx)) return true; } if (def.rest && isTransforming2(def.rest, ctx)) return true; return false; } case "record": { return isTransforming2(def.keyType, ctx) || isTransforming2(def.valueType, ctx); } case "map": { return isTransforming2(def.keyType, ctx) || isTransforming2(def.valueType, ctx); } case "set": { return isTransforming2(def.valueType, ctx); } // inner types case "promise": case "optional": case "nonoptional": case "nullable": case "readonly": return isTransforming2(def.innerType, ctx); case "lazy": return isTransforming2(def.getter(), ctx); case "default": { return isTransforming2(def.innerType, ctx); } case "prefault": { return isTransforming2(def.innerType, ctx); } case "custom": { return false; } case "transform": { return true; } case "pipe": { return isTransforming2(def.in, ctx) || isTransforming2(def.out, ctx); } case "success": { return false; } case "catch": { return false; } } throw new Error(`Unknown schema type: ${def.type}`); } var json_schema_exports2 = {}; var iso_exports2 = {}; __export(iso_exports2, { ZodISODate: () => ZodISODate2, ZodISODateTime: () => ZodISODateTime2, ZodISODuration: () => ZodISODuration2, ZodISOTime: () => ZodISOTime2, date: () => date6, datetime: () => datetime4, duration: () => duration4, time: () => time4 }); var ZodISODateTime2 = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => { $ZodISODateTime2.init(inst, def); ZodStringFormat2.init(inst, def); }); function datetime4(params) { return _isoDateTime2(ZodISODateTime2, params); } var ZodISODate2 = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => { $ZodISODate2.init(inst, def); ZodStringFormat2.init(inst, def); }); function date6(params) { return _isoDate2(ZodISODate2, params); } var ZodISOTime2 = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => { $ZodISOTime2.init(inst, def); ZodStringFormat2.init(inst, def); }); function time4(params) { return _isoTime2(ZodISOTime2, params); } var ZodISODuration2 = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => { $ZodISODuration2.init(inst, def); ZodStringFormat2.init(inst, def); }); function duration4(params) { return _isoDuration2(ZodISODuration2, params); } var initializer4 = (inst, issues) => { $ZodError2.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError2(inst, mapper) // enumerable: false, }, flatten: { value: (mapper) => flattenError2(inst, mapper) // enumerable: false, }, addIssue: { value: (issue3) => inst.issues.push(issue3) // enumerable: false, }, addIssues: { value: (issues2) => inst.issues.push(...issues2) // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; } // enumerable: false, } }); }; var ZodError4 = /* @__PURE__ */ $constructor2("ZodError", initializer4); var ZodRealError2 = /* @__PURE__ */ $constructor2("ZodError", initializer4, { Parent: Error }); var parse4 = /* @__PURE__ */ _parse3(ZodRealError2); var parseAsync4 = /* @__PURE__ */ _parseAsync2(ZodRealError2); var safeParse4 = /* @__PURE__ */ _safeParse2(ZodRealError2); var safeParseAsync4 = /* @__PURE__ */ _safeParseAsync2(ZodRealError2); var ZodType4 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => { $ZodType2.init(inst, def); inst.def = def; Object.defineProperty(inst, "_def", { value: def }); 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 = (def2, params) => clone2(inst, def2, params); inst.brand = () => inst; inst.register = ((reg, meta3) => { reg.add(inst, meta3); return inst; }); inst.parse = (data, params) => parse4(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse4(inst, data, params); inst.parseAsync = async (data, params) => parseAsync4(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync4(inst, data, params); inst.spa = inst.safeParseAsync; inst.refine = (check3, params) => inst.check(refine2(check3, params)); inst.superRefine = (refinement) => inst.check(superRefine2(refinement)); inst.overwrite = (fn) => inst.check(_overwrite2(fn)); inst.optional = () => optional2(inst); inst.nullable = () => nullable2(inst); inst.nullish = () => optional2(nullable2(inst)); inst.nonoptional = (params) => nonoptional2(inst, params); inst.array = () => array2(inst); inst.or = (arg) => union2([inst, arg]); inst.and = (arg) => intersection2(inst, arg); inst.transform = (tx) => pipe2(inst, transform2(tx)); inst.default = (def2) => _default4(inst, def2); inst.prefault = (def2) => prefault2(inst, def2); inst.catch = (params) => _catch4(inst, params); inst.pipe = (target) => pipe2(inst, target); inst.readonly = () => readonly2(inst); inst.describe = (description) => { const cl = inst.clone(); globalRegistry2.add(cl, { description }); return cl; }; Object.defineProperty(inst, "description", { get() { return globalRegistry2.get(inst)?.description; }, configurable: true }); inst.meta = (...args) => { if (args.length === 0) { return globalRegistry2.get(inst); } const cl = inst.clone(); globalRegistry2.add(cl, args[0]); return cl; }; inst.isOptional = () => inst.safeParse(void 0).success; inst.isNullable = () => inst.safeParse(null).success; return inst; }); var _ZodString2 = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => { $ZodString2.init(inst, def); ZodType4.init(inst, def); const bag = inst._zod.bag; inst.format = bag.format ?? null; inst.minLength = bag.minimum ?? null; inst.maxLength = bag.maximum ?? null; inst.regex = (...args) => inst.check(_regex2(...args)); inst.includes = (...args) => inst.check(_includes2(...args)); inst.startsWith = (...args) => inst.check(_startsWith2(...args)); inst.endsWith = (...args) => inst.check(_endsWith2(...args)); inst.min = (...args) => inst.check(_minLength2(...args)); inst.max = (...args) => inst.check(_maxLength2(...args)); inst.length = (...args) => inst.check(_length2(...args)); inst.nonempty = (...args) => inst.check(_minLength2(1, ...args)); inst.lowercase = (params) => inst.check(_lowercase2(params)); inst.uppercase = (params) => inst.check(_uppercase2(params)); inst.trim = () => inst.check(_trim2()); inst.normalize = (...args) => inst.check(_normalize2(...args)); inst.toLowerCase = () => inst.check(_toLowerCase2()); inst.toUpperCase = () => inst.check(_toUpperCase2()); }); var ZodString4 = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => { $ZodString2.init(inst, def); _ZodString2.init(inst, def); inst.email = (params) => inst.check(_email2(ZodEmail2, params)); inst.url = (params) => inst.check(_url2(ZodURL2, params)); inst.jwt = (params) => inst.check(_jwt2(ZodJWT2, params)); inst.emoji = (params) => inst.check(_emoji4(ZodEmoji2, params)); inst.guid = (params) => inst.check(_guid2(ZodGUID2, params)); inst.uuid = (params) => inst.check(_uuid2(ZodUUID2, params)); inst.uuidv4 = (params) => inst.check(_uuidv42(ZodUUID2, params)); inst.uuidv6 = (params) => inst.check(_uuidv62(ZodUUID2, params)); inst.uuidv7 = (params) => inst.check(_uuidv72(ZodUUID2, params)); inst.nanoid = (params) => inst.check(_nanoid2(ZodNanoID2, params)); inst.guid = (params) => inst.check(_guid2(ZodGUID2, params)); inst.cuid = (params) => inst.check(_cuid3(ZodCUID3, params)); inst.cuid2 = (params) => inst.check(_cuid22(ZodCUID22, params)); inst.ulid = (params) => inst.check(_ulid2(ZodULID2, params)); inst.base64 = (params) => inst.check(_base642(ZodBase642, params)); inst.base64url = (params) => inst.check(_base64url2(ZodBase64URL2, params)); inst.xid = (params) => inst.check(_xid2(ZodXID2, params)); inst.ksuid = (params) => inst.check(_ksuid2(ZodKSUID2, params)); inst.ipv4 = (params) => inst.check(_ipv42(ZodIPv42, params)); inst.ipv6 = (params) => inst.check(_ipv62(ZodIPv62, params)); inst.cidrv4 = (params) => inst.check(_cidrv42(ZodCIDRv42, params)); inst.cidrv6 = (params) => inst.check(_cidrv62(ZodCIDRv62, params)); inst.e164 = (params) => inst.check(_e1642(ZodE1642, params)); inst.datetime = (params) => inst.check(datetime4(params)); inst.date = (params) => inst.check(date6(params)); inst.time = (params) => inst.check(time4(params)); inst.duration = (params) => inst.check(duration4(params)); }); function string5(params) { return _string2(ZodString4, params); } var ZodStringFormat2 = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => { $ZodStringFormat2.init(inst, def); _ZodString2.init(inst, def); }); var ZodEmail2 = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => { $ZodEmail2.init(inst, def); ZodStringFormat2.init(inst, def); }); function email4(params) { return _email2(ZodEmail2, params); } var ZodGUID2 = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => { $ZodGUID2.init(inst, def); ZodStringFormat2.init(inst, def); }); function guid4(params) { return _guid2(ZodGUID2, params); } var ZodUUID2 = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => { $ZodUUID2.init(inst, def); ZodStringFormat2.init(inst, def); }); function uuid5(params) { return _uuid2(ZodUUID2, params); } function uuidv42(params) { return _uuidv42(ZodUUID2, params); } function uuidv62(params) { return _uuidv62(ZodUUID2, params); } function uuidv72(params) { return _uuidv72(ZodUUID2, params); } var ZodURL2 = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => { $ZodURL2.init(inst, def); ZodStringFormat2.init(inst, def); }); function url2(params) { return _url2(ZodURL2, params); } var ZodEmoji2 = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => { $ZodEmoji2.init(inst, def); ZodStringFormat2.init(inst, def); }); function emoji4(params) { return _emoji4(ZodEmoji2, params); } var ZodNanoID2 = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => { $ZodNanoID2.init(inst, def); ZodStringFormat2.init(inst, def); }); function nanoid4(params) { return _nanoid2(ZodNanoID2, params); } var ZodCUID3 = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => { $ZodCUID3.init(inst, def); ZodStringFormat2.init(inst, def); }); function cuid5(params) { return _cuid3(ZodCUID3, params); } var ZodCUID22 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => { $ZodCUID22.init(inst, def); ZodStringFormat2.init(inst, def); }); function cuid24(params) { return _cuid22(ZodCUID22, params); } var ZodULID2 = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => { $ZodULID2.init(inst, def); ZodStringFormat2.init(inst, def); }); function ulid4(params) { return _ulid2(ZodULID2, params); } var ZodXID2 = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => { $ZodXID2.init(inst, def); ZodStringFormat2.init(inst, def); }); function xid4(params) { return _xid2(ZodXID2, params); } var ZodKSUID2 = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => { $ZodKSUID2.init(inst, def); ZodStringFormat2.init(inst, def); }); function ksuid4(params) { return _ksuid2(ZodKSUID2, params); } var ZodIPv42 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => { $ZodIPv42.init(inst, def); ZodStringFormat2.init(inst, def); }); function ipv44(params) { return _ipv42(ZodIPv42, params); } var ZodIPv62 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => { $ZodIPv62.init(inst, def); ZodStringFormat2.init(inst, def); }); function ipv64(params) { return _ipv62(ZodIPv62, params); } var ZodCIDRv42 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => { $ZodCIDRv42.init(inst, def); ZodStringFormat2.init(inst, def); }); function cidrv44(params) { return _cidrv42(ZodCIDRv42, params); } var ZodCIDRv62 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => { $ZodCIDRv62.init(inst, def); ZodStringFormat2.init(inst, def); }); function cidrv64(params) { return _cidrv62(ZodCIDRv62, params); } var ZodBase642 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => { $ZodBase642.init(inst, def); ZodStringFormat2.init(inst, def); }); function base644(params) { return _base642(ZodBase642, params); } var ZodBase64URL2 = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => { $ZodBase64URL2.init(inst, def); ZodStringFormat2.init(inst, def); }); function base64url4(params) { return _base64url2(ZodBase64URL2, params); } var ZodE1642 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => { $ZodE1642.init(inst, def); ZodStringFormat2.init(inst, def); }); function e1644(params) { return _e1642(ZodE1642, params); } var ZodJWT2 = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => { $ZodJWT2.init(inst, def); ZodStringFormat2.init(inst, def); }); function jwt2(params) { return _jwt2(ZodJWT2, params); } var ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("ZodCustomStringFormat", (inst, def) => { $ZodCustomStringFormat2.init(inst, def); ZodStringFormat2.init(inst, def); }); function stringFormat2(format, fnOrRegex, _params = {}) { return _stringFormat2(ZodCustomStringFormat2, format, fnOrRegex, _params); } var ZodNumber4 = /* @__PURE__ */ $constructor2("ZodNumber", (inst, def) => { $ZodNumber2.init(inst, def); ZodType4.init(inst, def); inst.gt = (value, params) => inst.check(_gt2(value, params)); inst.gte = (value, params) => inst.check(_gte2(value, params)); inst.min = (value, params) => inst.check(_gte2(value, params)); inst.lt = (value, params) => inst.check(_lt2(value, params)); inst.lte = (value, params) => inst.check(_lte2(value, params)); inst.max = (value, params) => inst.check(_lte2(value, params)); inst.int = (params) => inst.check(int2(params)); inst.safe = (params) => inst.check(int2(params)); inst.positive = (params) => inst.check(_gt2(0, params)); inst.nonnegative = (params) => inst.check(_gte2(0, params)); inst.negative = (params) => inst.check(_lt2(0, params)); inst.nonpositive = (params) => inst.check(_lte2(0, params)); inst.multipleOf = (value, params) => inst.check(_multipleOf2(value, params)); inst.step = (value, params) => inst.check(_multipleOf2(value, params)); inst.finite = () => inst; const bag = inst._zod.bag; inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); inst.isFinite = true; inst.format = bag.format ?? null; }); function number5(params) { return _number2(ZodNumber4, params); } var ZodNumberFormat2 = /* @__PURE__ */ $constructor2("ZodNumberFormat", (inst, def) => { $ZodNumberFormat2.init(inst, def); ZodNumber4.init(inst, def); }); function int2(params) { return _int2(ZodNumberFormat2, params); } function float322(params) { return _float322(ZodNumberFormat2, params); } function float642(params) { return _float642(ZodNumberFormat2, params); } function int322(params) { return _int322(ZodNumberFormat2, params); } function uint322(params) { return _uint322(ZodNumberFormat2, params); } var ZodBoolean4 = /* @__PURE__ */ $constructor2("ZodBoolean", (inst, def) => { $ZodBoolean2.init(inst, def); ZodType4.init(inst, def); }); function boolean5(params) { return _boolean2(ZodBoolean4, params); } var ZodBigInt4 = /* @__PURE__ */ $constructor2("ZodBigInt", (inst, def) => { $ZodBigInt2.init(inst, def); ZodType4.init(inst, def); inst.gte = (value, params) => inst.check(_gte2(value, params)); inst.min = (value, params) => inst.check(_gte2(value, params)); inst.gt = (value, params) => inst.check(_gt2(value, params)); inst.gte = (value, params) => inst.check(_gte2(value, params)); inst.min = (value, params) => inst.check(_gte2(value, params)); inst.lt = (value, params) => inst.check(_lt2(value, params)); inst.lte = (value, params) => inst.check(_lte2(value, params)); inst.max = (value, params) => inst.check(_lte2(value, params)); inst.positive = (params) => inst.check(_gt2(BigInt(0), params)); inst.negative = (params) => inst.check(_lt2(BigInt(0), params)); inst.nonpositive = (params) => inst.check(_lte2(BigInt(0), params)); inst.nonnegative = (params) => inst.check(_gte2(BigInt(0), params)); inst.multipleOf = (value, params) => inst.check(_multipleOf2(value, params)); const bag = inst._zod.bag; inst.minValue = bag.minimum ?? null; inst.maxValue = bag.maximum ?? null; inst.format = bag.format ?? null; }); function bigint5(params) { return _bigint2(ZodBigInt4, params); } var ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("ZodBigIntFormat", (inst, def) => { $ZodBigIntFormat2.init(inst, def); ZodBigInt4.init(inst, def); }); function int642(params) { return _int642(ZodBigIntFormat2, params); } function uint642(params) { return _uint642(ZodBigIntFormat2, params); } var ZodSymbol4 = /* @__PURE__ */ $constructor2("ZodSymbol", (inst, def) => { $ZodSymbol2.init(inst, def); ZodType4.init(inst, def); }); function symbol20(params) { return _symbol2(ZodSymbol4, params); } var ZodUndefined4 = /* @__PURE__ */ $constructor2("ZodUndefined", (inst, def) => { $ZodUndefined2.init(inst, def); ZodType4.init(inst, def); }); function _undefined6(params) { return _undefined5(ZodUndefined4, params); } var ZodNull4 = /* @__PURE__ */ $constructor2("ZodNull", (inst, def) => { $ZodNull2.init(inst, def); ZodType4.init(inst, def); }); function _null6(params) { return _null5(ZodNull4, params); } var ZodAny4 = /* @__PURE__ */ $constructor2("ZodAny", (inst, def) => { $ZodAny2.init(inst, def); ZodType4.init(inst, def); }); function any2() { return _any2(ZodAny4); } var ZodUnknown4 = /* @__PURE__ */ $constructor2("ZodUnknown", (inst, def) => { $ZodUnknown2.init(inst, def); ZodType4.init(inst, def); }); function unknown2() { return _unknown2(ZodUnknown4); } var ZodNever4 = /* @__PURE__ */ $constructor2("ZodNever", (inst, def) => { $ZodNever2.init(inst, def); ZodType4.init(inst, def); }); function never2(params) { return _never2(ZodNever4, params); } var ZodVoid4 = /* @__PURE__ */ $constructor2("ZodVoid", (inst, def) => { $ZodVoid2.init(inst, def); ZodType4.init(inst, def); }); function _void4(params) { return _void3(ZodVoid4, params); } var ZodDate4 = /* @__PURE__ */ $constructor2("ZodDate", (inst, def) => { $ZodDate2.init(inst, def); ZodType4.init(inst, def); inst.min = (value, params) => inst.check(_gte2(value, params)); inst.max = (value, params) => inst.check(_lte2(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 date7(params) { return _date2(ZodDate4, params); } var ZodArray4 = /* @__PURE__ */ $constructor2("ZodArray", (inst, def) => { $ZodArray2.init(inst, def); ZodType4.init(inst, def); inst.element = def.element; inst.min = (minLength, params) => inst.check(_minLength2(minLength, params)); inst.nonempty = (params) => inst.check(_minLength2(1, params)); inst.max = (maxLength, params) => inst.check(_maxLength2(maxLength, params)); inst.length = (len, params) => inst.check(_length2(len, params)); inst.unwrap = () => inst.element; }); function array2(element, params) { return _array2(ZodArray4, element, params); } function keyof2(schema) { const shape = schema._zod.def.shape; return literal2(Object.keys(shape)); } var ZodObject4 = /* @__PURE__ */ $constructor2("ZodObject", (inst, def) => { $ZodObject2.init(inst, def); ZodType4.init(inst, def); util_exports2.defineLazy(inst, "shape", () => def.shape); inst.keyof = () => _enum4(Object.keys(inst._zod.def.shape)); inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never2() }); inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); inst.extend = (incoming) => { return util_exports2.extend(inst, incoming); }; inst.merge = (other) => util_exports2.merge(inst, other); inst.pick = (mask) => util_exports2.pick(inst, mask); inst.omit = (mask) => util_exports2.omit(inst, mask); inst.partial = (...args) => util_exports2.partial(ZodOptional4, inst, args[0]); inst.required = (...args) => util_exports2.required(ZodNonOptional2, inst, args[0]); }); function object4(shape, params) { const def = { type: "object", get shape() { util_exports2.assignProp(this, "shape", { ...shape }); return this.shape; }, ...util_exports2.normalizeParams(params) }; return new ZodObject4(def); } function strictObject2(shape, params) { return new ZodObject4({ type: "object", get shape() { util_exports2.assignProp(this, "shape", { ...shape }); return this.shape; }, catchall: never2(), ...util_exports2.normalizeParams(params) }); } function looseObject2(shape, params) { return new ZodObject4({ type: "object", get shape() { util_exports2.assignProp(this, "shape", { ...shape }); return this.shape; }, catchall: unknown2(), ...util_exports2.normalizeParams(params) }); } var ZodUnion4 = /* @__PURE__ */ $constructor2("ZodUnion", (inst, def) => { $ZodUnion2.init(inst, def); ZodType4.init(inst, def); inst.options = def.options; }); function union2(options, params) { return new ZodUnion4({ type: "union", options, ...util_exports2.normalizeParams(params) }); } var ZodDiscriminatedUnion4 = /* @__PURE__ */ $constructor2("ZodDiscriminatedUnion", (inst, def) => { ZodUnion4.init(inst, def); $ZodDiscriminatedUnion2.init(inst, def); }); function discriminatedUnion2(discriminator, options, params) { return new ZodDiscriminatedUnion4({ type: "union", options, discriminator, ...util_exports2.normalizeParams(params) }); } var ZodIntersection4 = /* @__PURE__ */ $constructor2("ZodIntersection", (inst, def) => { $ZodIntersection2.init(inst, def); ZodType4.init(inst, def); }); function intersection2(left, right) { return new ZodIntersection4({ type: "intersection", left, right }); } var ZodTuple4 = /* @__PURE__ */ $constructor2("ZodTuple", (inst, def) => { $ZodTuple2.init(inst, def); ZodType4.init(inst, def); inst.rest = (rest) => inst.clone({ ...inst._zod.def, rest }); }); function tuple2(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType2; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new ZodTuple4({ type: "tuple", items, rest, ...util_exports2.normalizeParams(params) }); } var ZodRecord4 = /* @__PURE__ */ $constructor2("ZodRecord", (inst, def) => { $ZodRecord2.init(inst, def); ZodType4.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function record2(keyType, valueType, params) { return new ZodRecord4({ type: "record", keyType, valueType, ...util_exports2.normalizeParams(params) }); } function partialRecord2(keyType, valueType, params) { return new ZodRecord4({ type: "record", keyType: union2([keyType, never2()]), valueType, ...util_exports2.normalizeParams(params) }); } var ZodMap4 = /* @__PURE__ */ $constructor2("ZodMap", (inst, def) => { $ZodMap2.init(inst, def); ZodType4.init(inst, def); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function map2(keyType, valueType, params) { return new ZodMap4({ type: "map", keyType, valueType, ...util_exports2.normalizeParams(params) }); } var ZodSet4 = /* @__PURE__ */ $constructor2("ZodSet", (inst, def) => { $ZodSet2.init(inst, def); ZodType4.init(inst, def); inst.min = (...args) => inst.check(_minSize2(...args)); inst.nonempty = (params) => inst.check(_minSize2(1, params)); inst.max = (...args) => inst.check(_maxSize2(...args)); inst.size = (...args) => inst.check(_size2(...args)); }); function set2(valueType, params) { return new ZodSet4({ type: "set", valueType, ...util_exports2.normalizeParams(params) }); } var ZodEnum4 = /* @__PURE__ */ $constructor2("ZodEnum", (inst, def) => { $ZodEnum2.init(inst, def); ZodType4.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 ZodEnum4({ ...def, checks: [], ...util_exports2.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 ZodEnum4({ ...def, checks: [], ...util_exports2.normalizeParams(params), entries: newEntries }); }; }); function _enum4(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new ZodEnum4({ type: "enum", entries, ...util_exports2.normalizeParams(params) }); } function nativeEnum2(entries, params) { return new ZodEnum4({ type: "enum", entries, ...util_exports2.normalizeParams(params) }); } var ZodLiteral4 = /* @__PURE__ */ $constructor2("ZodLiteral", (inst, def) => { $ZodLiteral2.init(inst, def); ZodType4.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 literal2(value, params) { return new ZodLiteral4({ type: "literal", values: Array.isArray(value) ? value : [value], ...util_exports2.normalizeParams(params) }); } var ZodFile2 = /* @__PURE__ */ $constructor2("ZodFile", (inst, def) => { $ZodFile2.init(inst, def); ZodType4.init(inst, def); inst.min = (size, params) => inst.check(_minSize2(size, params)); inst.max = (size, params) => inst.check(_maxSize2(size, params)); inst.mime = (types, params) => inst.check(_mime2(Array.isArray(types) ? types : [types], params)); }); function file2(params) { return _file2(ZodFile2, params); } var ZodTransform2 = /* @__PURE__ */ $constructor2("ZodTransform", (inst, def) => { $ZodTransform2.init(inst, def); ZodType4.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.addIssue = (issue3) => { if (typeof issue3 === "string") { payload.issues.push(util_exports2.issue(issue3, payload.value, def)); } else { const _issue = issue3; 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_exports2.issue(_issue)); } }; const output = def.transform(payload.value, payload); if (output instanceof Promise) { return output.then((output2) => { payload.value = output2; return payload; }); } payload.value = output; return payload; }; }); function transform2(fn) { return new ZodTransform2({ type: "transform", transform: fn }); } var ZodOptional4 = /* @__PURE__ */ $constructor2("ZodOptional", (inst, def) => { $ZodOptional2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function optional2(innerType) { return new ZodOptional4({ type: "optional", innerType }); } var ZodNullable4 = /* @__PURE__ */ $constructor2("ZodNullable", (inst, def) => { $ZodNullable2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nullable2(innerType) { return new ZodNullable4({ type: "nullable", innerType }); } function nullish4(innerType) { return optional2(nullable2(innerType)); } var ZodDefault4 = /* @__PURE__ */ $constructor2("ZodDefault", (inst, def) => { $ZodDefault2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); function _default4(innerType, defaultValue) { return new ZodDefault4({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; } }); } var ZodPrefault2 = /* @__PURE__ */ $constructor2("ZodPrefault", (inst, def) => { $ZodPrefault2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function prefault2(innerType, defaultValue) { return new ZodPrefault2({ type: "prefault", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : defaultValue; } }); } var ZodNonOptional2 = /* @__PURE__ */ $constructor2("ZodNonOptional", (inst, def) => { $ZodNonOptional2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional2(innerType, params) { return new ZodNonOptional2({ type: "nonoptional", innerType, ...util_exports2.normalizeParams(params) }); } var ZodSuccess2 = /* @__PURE__ */ $constructor2("ZodSuccess", (inst, def) => { $ZodSuccess2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function success2(innerType) { return new ZodSuccess2({ type: "success", innerType }); } var ZodCatch4 = /* @__PURE__ */ $constructor2("ZodCatch", (inst, def) => { $ZodCatch2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); function _catch4(innerType, catchValue) { return new ZodCatch4({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } var ZodNaN4 = /* @__PURE__ */ $constructor2("ZodNaN", (inst, def) => { $ZodNaN2.init(inst, def); ZodType4.init(inst, def); }); function nan2(params) { return _nan2(ZodNaN4, params); } var ZodPipe2 = /* @__PURE__ */ $constructor2("ZodPipe", (inst, def) => { $ZodPipe2.init(inst, def); ZodType4.init(inst, def); inst.in = def.in; inst.out = def.out; }); function pipe2(in_, out) { return new ZodPipe2({ type: "pipe", in: in_, out // ...util.normalizeParams(params), }); } var ZodReadonly4 = /* @__PURE__ */ $constructor2("ZodReadonly", (inst, def) => { $ZodReadonly2.init(inst, def); ZodType4.init(inst, def); }); function readonly2(innerType) { return new ZodReadonly4({ type: "readonly", innerType }); } var ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("ZodTemplateLiteral", (inst, def) => { $ZodTemplateLiteral2.init(inst, def); ZodType4.init(inst, def); }); function templateLiteral2(parts, params) { return new ZodTemplateLiteral2({ type: "template_literal", parts, ...util_exports2.normalizeParams(params) }); } var ZodLazy4 = /* @__PURE__ */ $constructor2("ZodLazy", (inst, def) => { $ZodLazy2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.getter(); }); function lazy2(getter) { return new ZodLazy4({ type: "lazy", getter }); } var ZodPromise4 = /* @__PURE__ */ $constructor2("ZodPromise", (inst, def) => { $ZodPromise2.init(inst, def); ZodType4.init(inst, def); inst.unwrap = () => inst._zod.def.innerType; }); function promise2(innerType) { return new ZodPromise4({ type: "promise", innerType }); } var ZodCustom2 = /* @__PURE__ */ $constructor2("ZodCustom", (inst, def) => { $ZodCustom2.init(inst, def); ZodType4.init(inst, def); }); function check2(fn) { const ch = new $ZodCheck2({ check: "custom" // ...util.normalizeParams(params), }); ch._zod.check = fn; return ch; } function custom3(fn, _params) { return _custom2(ZodCustom2, fn ?? (() => true), _params); } function refine2(fn, _params = {}) { return _refine2(ZodCustom2, fn, _params); } function superRefine2(fn) { const ch = check2((payload) => { payload.addIssue = (issue3) => { if (typeof issue3 === "string") { payload.issues.push(util_exports2.issue(issue3, payload.value, ch._zod.def)); } else { const _issue = issue3; 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_exports2.issue(_issue)); } }; return fn(payload.value, payload); }); return ch; } function _instanceof2(cls, params = { error: `Input not instance of ${cls.name}` }) { const inst = new ZodCustom2({ type: "custom", check: "custom", fn: (data) => data instanceof cls, abort: true, ...util_exports2.normalizeParams(params) }); inst._zod.bag.Class = cls; return inst; } var stringbool2 = (...args) => _stringbool2({ Pipe: ZodPipe2, Boolean: ZodBoolean4, String: ZodString4, Transform: ZodTransform2 }, ...args); function json2(params) { const jsonSchema42 = lazy2(() => { return union2([string5(params), number5(), boolean5(), _null6(), array2(jsonSchema42), record2(string5(), jsonSchema42)]); }); return jsonSchema42; } function preprocess2(fn, schema) { return pipe2(transform2(fn), schema); } var ZodIssueCode4 = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" }; function setErrorMap3(map3) { config2({ customError: map3 }); } function getErrorMap4() { return config2().customError; } var coerce_exports2 = {}; __export(coerce_exports2, { bigint: () => bigint6, boolean: () => boolean6, date: () => date8, number: () => number6, string: () => string6 }); function string6(params) { return _coercedString2(ZodString4, params); } function number6(params) { return _coercedNumber2(ZodNumber4, params); } function boolean6(params) { return _coercedBoolean2(ZodBoolean4, params); } function bigint6(params) { return _coercedBigint2(ZodBigInt4, params); } function date8(params) { return _coercedDate2(ZodDate4, params); } config2(en_default4()); var marker19 = "vercel.ai.error"; var symbol21 = Symbol.for(marker19); var _a21; var _b17; var AISDKError3 = class _AISDKError4 extends (_b17 = Error, _a21 = symbol21, _b17) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name1422, message, cause }) { super(message); this[_a21] = true; this.name = name1422; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error90) { return _AISDKError4.hasMarker(error90, marker19); } static hasMarker(error90, marker1522) { const markerSymbol = Symbol.for(marker1522); return error90 != null && typeof error90 === "object" && markerSymbol in error90 && typeof error90[markerSymbol] === "boolean" && error90[markerSymbol] === true; } }; var name19 = "AI_APICallError"; var marker25 = `vercel.ai.error.${name19}`; var symbol25 = Symbol.for(marker25); var _a25; var _b23; var APICallError3 = class extends (_b23 = AISDKError3, _a25 = symbol25, _b23) { constructor({ message, url: url3, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name: name19, message, cause }); this[_a25] = true; this.url = url3; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker25); } }; var name25 = "AI_EmptyResponseBodyError"; var marker35 = `vercel.ai.error.${name25}`; var symbol35 = Symbol.for(marker35); var _a35; var _b33; var EmptyResponseBodyError2 = class extends (_b33 = AISDKError3, _a35 = symbol35, _b33) { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name25, message }); this[_a35] = true; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker35); } }; function getErrorMessage4(error90) { if (error90 == null) { return "unknown error"; } if (typeof error90 === "string") { return error90; } if (error90 instanceof Error) { return error90.message; } return JSON.stringify(error90); } var name35 = "AI_InvalidArgumentError"; var marker45 = `vercel.ai.error.${name35}`; var symbol45 = Symbol.for(marker45); var _a45; var _b43; var InvalidArgumentError4 = class extends (_b43 = AISDKError3, _a45 = symbol45, _b43) { constructor({ message, cause, argument }) { super({ name: name35, message, cause }); this[_a45] = true; this.argument = argument; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker45); } }; var name65 = "AI_JSONParseError"; var marker75 = `vercel.ai.error.${name65}`; var symbol75 = Symbol.for(marker75); var _a75; var _b73; var JSONParseError3 = class extends (_b73 = AISDKError3, _a75 = symbol75, _b73) { constructor({ text: text42, cause }) { super({ name: name65, message: `JSON parsing failed: Text: ${text42}. Error message: ${getErrorMessage4(cause)}`, cause }); this[_a75] = true; this.text = text42; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker75); } }; var name125 = "AI_TypeValidationError"; var marker135 = `vercel.ai.error.${name125}`; var symbol135 = Symbol.for(marker135); var _a135; var _b132; var TypeValidationError3 = class _TypeValidationError4 extends (_b132 = AISDKError3, _a135 = symbol135, _b132) { constructor({ value, cause, context: context2 }) { let contextPrefix = "Type validation failed"; if (context2 == null ? void 0 : context2.field) { contextPrefix += ` for ${context2.field}`; } if ((context2 == null ? void 0 : context2.entityName) || (context2 == null ? void 0 : context2.entityId)) { contextPrefix += " ("; const parts = []; if (context2.entityName) { parts.push(context2.entityName); } if (context2.entityId) { parts.push(`id: "${context2.entityId}"`); } contextPrefix += parts.join(", "); contextPrefix += ")"; } super({ name: name125, message: `${contextPrefix}: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage4(cause)}`, cause }); this[_a135] = true; this.value = value; this.context = context2; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker135); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value and context, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @param {TypeValidationContext} params.context - Optional context about what is being validated. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause, context: context2 }) { var _a1522, _b1522, _c; if (_TypeValidationError4.isInstance(cause) && cause.value === value && ((_a1522 = cause.context) == null ? void 0 : _a1522.field) === (context2 == null ? void 0 : context2.field) && ((_b1522 = cause.context) == null ? void 0 : _b1522.entityName) === (context2 == null ? void 0 : context2.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context2 == null ? void 0 : context2.entityId)) { return cause; } return new _TypeValidationError4({ value, cause, context: context2 }); } }; var ParseError2 = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; var LF2 = 10; var CR2 = 13; var SPACE2 = 32; function noop2(_arg) { } function createParser2(callbacks) { if (typeof callbacks == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks, pendingFragments = []; let isFirstChunk = true, id, data = "", dataLines = 0, eventType; function feed(chunk) { if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) { const trailing2 = processLines(chunk); trailing2 !== "" && pendingFragments.push(trailing2); return; } if (chunk.indexOf(` `) === -1 && chunk.indexOf("\r") === -1) { pendingFragments.push(chunk); return; } pendingFragments.push(chunk); const input = pendingFragments.join(""); pendingFragments.length = 0; const trailing = processLines(input); trailing !== "" && pendingFragments.push(trailing); } function processLines(chunk) { let searchIndex = 0; if (chunk.indexOf("\r") === -1) { let lfIndex = chunk.indexOf(` `, searchIndex); for (; lfIndex !== -1; ) { if (searchIndex === lfIndex) { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); continue; } const firstCharCode = chunk.charCodeAt(searchIndex); if (isDataPrefix2(chunk, searchIndex, firstCharCode)) { const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE2 ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex); if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF2) { onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(` `, searchIndex); continue; } data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; } else isEventPrefix2(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice( chunk.charCodeAt(searchIndex + 6) === SPACE2 ? searchIndex + 7 : searchIndex + 6, lfIndex ) || void 0 : parseLine(chunk, searchIndex, lfIndex); searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); } return chunk.slice(searchIndex); } for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break; parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR2 && chunk.charCodeAt(searchIndex) === LF2 && searchIndex++; } return chunk.slice(searchIndex); } function parseLine(chunk, start, end) { if (start === end) { dispatchEvent(); return; } const firstCharCode = chunk.charCodeAt(start); if (isDataPrefix2(chunk, start, firstCharCode)) { const valueStart = chunk.charCodeAt(start + 5) === SPACE2 ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end); data = dataLines === 0 ? value2 : `${data} ${value2}`, dataLines++; return; } if (isEventPrefix2(chunk, start, firstCharCode)) { eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE2 ? start + 7 : start + 6, end) || void 0; return; } if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) { const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE2 ? start + 4 : start + 3, end); id = value2.includes("\0") ? void 0 : value2; return; } if (firstCharCode === 58) { if (onComment) { const line2 = chunk.slice(start, end); onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE2 ? 2 : 1)); } return; } const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":"); if (fieldSeparatorIndex === -1) { processField(line, "", line); return; } const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE2 ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); processField(field, value, line); } function processField(field, value, line) { switch (field) { case "event": eventType = value || void 0; break; case "data": data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError2(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError2( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line } ) ); break; } } function dispatchEvent() { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0; } function reset(options = {}) { if (options.consume && pendingFragments.length > 0) { const incompleteLine = pendingFragments.join(""); parseLine(incompleteLine, 0, incompleteLine.length); } isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0; } return { feed, reset }; } function isDataPrefix2(chunk, i, firstCharCode) { return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58; } function isEventPrefix2(chunk, i, firstCharCode) { return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58; } var EventSourceParserStream2 = class extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser2({ onEvent: (event) => { controller.enqueue(event); }, onError(error90) { onError === "terminate" ? controller.error(error90) : typeof onError == "function" && onError(error90); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; function combineHeaders2(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {} ); } async function delay3(delayInMs, options) { if (delayInMs == null) { return Promise.resolve(); } const signal = options == null ? void 0 : options.abortSignal; return new Promise((resolve22, reject) => { if (signal == null ? void 0 : signal.aborted) { reject(createAbortError2()); return; } const timeoutId = setTimeout(() => { cleanup(); resolve22(); }, delayInMs); const cleanup = () => { clearTimeout(timeoutId); signal == null ? void 0 : signal.removeEventListener("abort", onAbort); }; const onAbort = () => { cleanup(); reject(createAbortError2()); }; signal == null ? void 0 : signal.addEventListener("abort", onAbort); }); } function createAbortError2() { return new DOMException("Delay was aborted", "AbortError"); } function extractResponseHeaders2(response) { return Object.fromEntries([...response.headers]); } var { btoa: btoa4 } = globalThis; function convertUint8ArrayToBase643(array4) { let latin1string = ""; for (let i = 0; i < array4.length; i++) { latin1string += String.fromCodePoint(array4[i]); } return btoa4(latin1string); } var createIdGenerator3 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i = 0; i < size; i++) { chars[i] = alphabet[Math.random() * alphabetLength | 0]; } return chars.join(""); }; if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError4({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return () => `${prefix}${separator}${generator()}`; }; createIdGenerator3(); function getErrorMessage23(error90) { if (error90 == null) { return "unknown error"; } if (typeof error90 === "string") { return error90; } if (error90 instanceof Error) { return error90.message; } return JSON.stringify(error90); } function isAbortError3(error90) { return (error90 instanceof Error || error90 instanceof DOMException) && (error90.name === "AbortError" || error90.name === "ResponseAborted" || // Next.js error90.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES2 = ["fetch failed", "failed to fetch"]; var BUN_ERROR_CODES = [ "ConnectionRefused", "ConnectionClosed", "FailedToOpenSocket", "ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE" ]; function isBunNetworkError(error90) { if (!(error90 instanceof Error)) { return false; } const code = error90.code; if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) { return true; } return false; } function handleFetchError2({ error: error90, url: url3, requestBodyValues }) { if (isAbortError3(error90)) { return error90; } if (error90 instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES2.includes(error90.message.toLowerCase())) { const cause = error90.cause; if (cause != null) { return new APICallError3({ message: `Cannot connect to API: ${cause.message}`, cause, url: url3, requestBodyValues, isRetryable: true // retry when network error }); } } if (isBunNetworkError(error90)) { return new APICallError3({ message: `Cannot connect to API: ${error90.message}`, cause: error90, url: url3, requestBodyValues, isRetryable: true }); } return error90; } function getRuntimeEnvironmentUserAgent2(globalThisAny = globalThis) { var _a224, _b2222, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a224 = globalThisAny.navigator) == null ? void 0 : _a224.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b2222 = globalThisAny.process) == null ? void 0 : _b2222.versions) == null ? void 0 : _c.node) { return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; } if (globalThisAny.EdgeRuntime) { return `runtime/vercel-edge`; } return "runtime/unknown"; } function normalizeHeaders2(headers) { if (headers == null) { return {}; } const normalized = {}; if (headers instanceof Headers) { headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); } else { if (!Array.isArray(headers)) { headers = Object.entries(headers); } for (const [key, value] of headers) { if (value != null) { normalized[key.toLowerCase()] = value; } } } return normalized; } function withUserAgentSuffix2(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders2(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION4 = "4.0.27"; var getOriginalFetch3 = () => globalThis.fetch; var getFromApi2 = async ({ url: url3, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch3() }) => { try { const response = await fetch2(url3, { method: "GET", headers: withUserAgentSuffix2( headers, `ai-sdk/provider-utils/${VERSION4}`, getRuntimeEnvironmentUserAgent2() ), signal: abortSignal }); const responseHeaders = extractResponseHeaders2(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url: url3, requestBodyValues: {} }); } catch (error90) { if (isAbortError3(error90) || APICallError3.isInstance(error90)) { throw error90; } throw new APICallError3({ message: "Failed to process error response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: {} }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url3, requestBodyValues: {} }); } catch (error90) { if (error90 instanceof Error) { if (isAbortError3(error90) || APICallError3.isInstance(error90)) { throw error90; } } throw new APICallError3({ message: "Failed to process successful response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: {} }); } } catch (error90) { throw handleFetchError2({ error: error90, url: url3, requestBodyValues: {} }); } }; function loadOptionalSetting2({ settingValue, environmentVariableName }) { if (typeof settingValue === "string") { return settingValue; } if (settingValue != null || typeof process === "undefined") { return void 0; } settingValue = process.env[environmentVariableName]; if (settingValue == null || typeof settingValue !== "string") { return void 0; } return settingValue; } var suspectProtoRx2 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx2 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse4(text42) { const obj = JSON.parse(text42); if (obj === null || typeof obj !== "object") { return obj; } if (suspectProtoRx2.test(text42) === false && suspectConstructorRx2.test(text42) === false) { return obj; } return filter2(obj); } function filter2(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) { throw new SyntaxError("Object contains forbidden prototype property"); } if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { throw new SyntaxError("Object contains forbidden prototype property"); } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function secureJsonParse2(text42) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e2) { return _parse4(text42); } try { return _parse4(text42); } finally { Error.stackTraceLimit = stackTraceLimit; } } function addAdditionalPropertiesToJsonSchema2(jsonSchema22) { if (jsonSchema22.type === "object" || Array.isArray(jsonSchema22.type) && jsonSchema22.type.includes("object")) { jsonSchema22.additionalProperties = false; const { properties } = jsonSchema22; if (properties != null) { for (const key of Object.keys(properties)) { properties[key] = visit(properties[key]); } } } if (jsonSchema22.items != null) { jsonSchema22.items = Array.isArray(jsonSchema22.items) ? jsonSchema22.items.map(visit) : visit(jsonSchema22.items); } if (jsonSchema22.anyOf != null) { jsonSchema22.anyOf = jsonSchema22.anyOf.map(visit); } if (jsonSchema22.allOf != null) { jsonSchema22.allOf = jsonSchema22.allOf.map(visit); } if (jsonSchema22.oneOf != null) { jsonSchema22.oneOf = jsonSchema22.oneOf.map(visit); } const { definitions } = jsonSchema22; if (definitions != null) { for (const key of Object.keys(definitions)) { definitions[key] = visit(definitions[key]); } } return jsonSchema22; } function visit(def) { if (typeof def === "boolean") return def; return addAdditionalPropertiesToJsonSchema2(def); } var ignoreOverride3 = /* @__PURE__ */ Symbol( "Let zodToJsonSchema decide on which parser to use" ); var defaultOptions3 = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions3 = (options) => typeof options === "string" ? { ...defaultOptions3, name: options } : { ...defaultOptions3, ...options }; function parseAnyDef3() { return {}; } function parseArrayDef3(def, refs) { var _a224, _b2222, _c; const res = { type: "array" }; if (((_a224 = def.type) == null ? void 0 : _a224._def) && ((_c = (_b2222 = def.type) == null ? void 0 : _b2222._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef3(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { res.minItems = def.minLength.value; } if (def.maxLength) { res.maxItems = def.maxLength.value; } if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef3(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "min": if (check3.inclusive) { res.minimum = check3.value; } else { res.exclusiveMinimum = check3.value; } break; case "max": if (check3.inclusive) { res.maximum = check3.value; } else { res.exclusiveMaximum = check3.value; } break; case "multipleOf": res.multipleOf = check3.value; break; } } return res; } function parseBooleanDef3() { return { type: "boolean" }; } function parseBrandedDef3(_def, refs) { return parseDef3(_def.type._def, refs); } var parseCatchDef3 = (def, refs) => { return parseDef3(def.innerType._def, refs); }; function parseDateDef3(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef3(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 integerDateParser3(def); } } var integerDateParser3 = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check3 of def.checks) { switch (check3.kind) { case "min": res.minimum = check3.value; break; case "max": res.maximum = check3.value; break; } } return res; }; function parseDefaultDef3(_def, refs) { return { ...parseDef3(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef3(_def, refs) { return refs.effectStrategy === "input" ? parseDef3(_def.schema._def, refs) : parseAnyDef3(); } function parseEnumDef3(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType3 = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef3(def, refs) { const allOf = [ parseDef3(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef3(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType3(schema)) { mergedAllOf.push(...schema.allOf); } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef3(def) { const parsedType5 = typeof def.value; if (parsedType5 !== "bigint" && parsedType5 !== "number" && parsedType5 !== "boolean" && parsedType5 !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } return { type: parsedType5 === "bigint" ? "integer" : parsedType5, const: def.value }; } var emojiRegex5 = void 0; var zodPatterns3 = { /** * `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 (emojiRegex5 === void 0) { emojiRegex5 = RegExp( "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u" ); } return emojiRegex5; }, /** * 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 parseStringDef3(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check3 of def.checks) { switch (check3.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat3(res, "email", check3.message, refs); break; case "format:idn-email": addFormat3(res, "idn-email", check3.message, refs); break; case "pattern:zod": addPattern3(res, zodPatterns3.email, check3.message, refs); break; } break; case "url": addFormat3(res, "uri", check3.message, refs); break; case "uuid": addFormat3(res, "uuid", check3.message, refs); break; case "regex": addPattern3(res, check3.regex, check3.message, refs); break; case "cuid": addPattern3(res, zodPatterns3.cuid, check3.message, refs); break; case "cuid2": addPattern3(res, zodPatterns3.cuid2, check3.message, refs); break; case "startsWith": addPattern3( res, RegExp(`^${escapeLiteralCheckValue3(check3.value, refs)}`), check3.message, refs ); break; case "endsWith": addPattern3( res, RegExp(`${escapeLiteralCheckValue3(check3.value, refs)}$`), check3.message, refs ); break; case "datetime": addFormat3(res, "date-time", check3.message, refs); break; case "date": addFormat3(res, "date", check3.message, refs); break; case "time": addFormat3(res, "time", check3.message, refs); break; case "duration": addFormat3(res, "duration", check3.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value; break; case "includes": { addPattern3( res, RegExp(escapeLiteralCheckValue3(check3.value, refs)), check3.message, refs ); break; } case "ip": { if (check3.version !== "v6") { addFormat3(res, "ipv4", check3.message, refs); } if (check3.version !== "v4") { addFormat3(res, "ipv6", check3.message, refs); } break; } case "base64url": addPattern3(res, zodPatterns3.base64url, check3.message, refs); break; case "jwt": addPattern3(res, zodPatterns3.jwt, check3.message, refs); break; case "cidr": { if (check3.version !== "v6") { addPattern3(res, zodPatterns3.ipv4Cidr, check3.message, refs); } if (check3.version !== "v4") { addPattern3(res, zodPatterns3.ipv6Cidr, check3.message, refs); } break; } case "emoji": addPattern3(res, zodPatterns3.emoji(), check3.message, refs); break; case "ulid": { addPattern3(res, zodPatterns3.ulid, check3.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat3(res, "binary", check3.message, refs); break; } case "contentEncoding:base64": { res.contentEncoding = "base64"; break; } case "pattern:zod": { addPattern3(res, zodPatterns3.base64, check3.message, refs); break; } } break; } case "nanoid": { addPattern3(res, zodPatterns3.nanoid, check3.message, refs); } } } } return res; } function escapeLiteralCheckValue3(literal3, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric3(literal3) : literal3; } var ALPHA_NUMERIC3 = new Set( "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789" ); function escapeNonAlphaNumeric3(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC3.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat3(schema, value, message, refs) { var _a224; if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x) => x.format))) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format }); delete schema.format; } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { schema.format = value; } } function addPattern3(schema, regex, message, refs) { var _a224; if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x) => x.pattern))) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern }); delete schema.pattern; } schema.allOf.push({ pattern: stringifyRegExpWithFlags3(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { schema.pattern = stringifyRegExpWithFlags3(regex, refs); } } function stringifyRegExpWithFlags3(regex, refs) { var _a224; if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s") // `.` matches newlines }; 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] === "-" && ((_a224 = source[i + 2]) == null ? void 0 : _a224.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 ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } return pattern; } function parseRecordDef3(def, refs) { var _a224, _b2222, _c, _d, _e, _f; const schema = { type: "object", additionalProperties: (_a224 = parseDef3(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] })) != null ? _a224 : refs.allowedAdditionalProperties }; if (((_b2222 = def.keyType) == null ? void 0 : _b2222._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) { const { type, ...keyType } = parseStringDef3(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) { const { type, ...keyType } = parseBrandedDef3( def.keyType._def, refs ); return { ...schema, propertyNames: keyType }; } return schema; } function parseMapDef3(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef3(def, refs); } const keys = parseDef3(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || parseAnyDef3(); const values = parseDef3(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || parseAnyDef3(); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } function parseNativeEnumDef3(def) { const object62 = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object62[object62[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object62[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 }; } function parseNeverDef3() { return { not: parseAnyDef3() }; } function parseNullDef3() { return { type: "null" }; } var primitiveMappings3 = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef3(def, refs) { const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every( (x) => x._def.typeName in primitiveMappings3 && (!x._def.checks || !x._def.checks.length) )) { const types = options.reduce((types2, x) => { const type = primitiveMappings3[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { 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) { 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((x2) => !acc.includes(x2)) ], [] ) }; } return asAnyOf3(def, refs); } var asAnyOf3 = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map( (x, i) => parseDef3(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 } : void 0; }; function parseNullableDef3(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes( def.innerType._def.typeName ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { return { type: [ primitiveMappings3[def.innerType._def.typeName], "null" ] }; } const base = parseDef3(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } function parseNumberDef3(def) { const res = { type: "number" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "int": res.type = "integer"; break; case "min": if (check3.inclusive) { res.minimum = check3.value; } else { res.exclusiveMinimum = check3.value; } break; case "max": if (check3.inclusive) { res.maximum = check3.value; } else { res.exclusiveMaximum = check3.value; } break; case "multipleOf": res.multipleOf = check3.value; break; } } return res; } function parseObjectDef3(def, refs) { const result = { type: "object", properties: {} }; const required3 = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } const propOptional = safeIsOptional3(propDef); const parsedDef = parseDef3(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required3.push(propName); } } if (required3.length) { result.required = required3; } const additionalProperties = decideAdditionalProperties3(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties3(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef3(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 safeIsOptional3(schema) { try { return schema.isOptional(); } catch (e2) { return true; } } var parseOptionalDef3 = (def, refs) => { var _a224; if (refs.currentPath.toString() === ((_a224 = refs.propertyPath) == null ? void 0 : _a224.toString())) { return parseDef3(def.innerType._def, refs); } const innerSchema = parseDef3(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [{ not: parseAnyDef3() }, innerSchema] } : parseAnyDef3(); }; var parsePipelineDef3 = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef3(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef3(def.out._def, refs); } const a = parseDef3(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef3(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== void 0) }; }; function parsePromiseDef3(def, refs) { return parseDef3(def.type._def, refs); } function parseSetDef3(def, refs) { const items = parseDef3(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { schema.minItems = def.minSize.value; } if (def.maxSize) { schema.maxItems = def.maxSize.value; } return schema; } function parseTupleDef3(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map( (x, i) => parseDef3(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ), additionalItems: parseDef3(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) => parseDef3(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ) }; } } function parseUndefinedDef3() { return { not: parseAnyDef3() }; } function parseUnknownDef3() { return parseAnyDef3(); } var parseReadonlyDef3 = (def, refs) => { return parseDef3(def.innerType._def, refs); }; var selectParser3 = (def, typeName, refs) => { switch (typeName) { case ZodFirstPartyTypeKind.ZodString: return parseStringDef3(def, refs); case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef3(def); case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef3(def, refs); case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef3(def); case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef3(); case ZodFirstPartyTypeKind.ZodDate: return parseDateDef3(def, refs); case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef3(); case ZodFirstPartyTypeKind.ZodNull: return parseNullDef3(); case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef3(def, refs); case ZodFirstPartyTypeKind.ZodUnion: case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef3(def, refs); case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef3(def, refs); case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef3(def, refs); case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef3(def, refs); case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef3(def); case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef3(def); case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef3(def); case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef3(def, refs); case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef3(def, refs); case ZodFirstPartyTypeKind.ZodMap: return parseMapDef3(def, refs); case ZodFirstPartyTypeKind.ZodSet: return parseSetDef3(def, refs); case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef3(def, refs); case ZodFirstPartyTypeKind.ZodNaN: case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef3(); case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef3(def, refs); case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef3(); case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef3(); case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef3(def, refs); case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef3(def, refs); case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef3(def, refs); case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef3(def, refs); case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef3(def, refs); case ZodFirstPartyTypeKind.ZodFunction: case ZodFirstPartyTypeKind.ZodVoid: case ZodFirstPartyTypeKind.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_) => void 0)(); } }; var getRelativePath3 = (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("/"); }; function parseDef3(def, refs, forceResolution = false) { var _a224; const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = (_a224 = refs.override) == null ? void 0 : _a224.call( refs, def, refs, seenItem, forceResolution ); if (overrideResult !== ignoreOverride3) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref3(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser3(def, def.typeName, refs); const jsonSchema22 = typeof jsonSchemaOrGetter === "function" ? parseDef3(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema22) { addMeta3(def, refs, jsonSchema22); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema22, def, refs); newItem.jsonSchema = jsonSchema22; return postProcessResult; } newItem.jsonSchema = jsonSchema22; return jsonSchema22; } var get$ref3 = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath3(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 parseAnyDef3(); } return refs.$refStrategy === "seen" ? parseAnyDef3() : void 0; } } }; var addMeta3 = (def, refs, jsonSchema22) => { if (def.description) { jsonSchema22.description = def.description; } return jsonSchema22; }; var getRefs3 = (options) => { const _options = getDefaultOptions3(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: void 0, seen: new Map( Object.entries(_options.definitions).map(([name224, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name224], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ]) ) }; }; var zod3ToJsonSchema = (schema, options) => { var _a224; const refs = getRefs3(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce( (acc, [name324, schema2]) => { var _a324; return { ...acc, [name324]: (_a324 = parseDef3( schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name324] }, true )) != null ? _a324 : parseAnyDef3() }; }, {} ) : void 0; const name224 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name; const main = (_a224 = parseDef3( schema._def, name224 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name224] }, false )) != null ? _a224 : parseAnyDef3(); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main.title = title; } const combined = name224 === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name224 ].join("/"), [refs.definitionPath]: { ...definitions, [name224]: main } }; combined.$schema = "http://json-schema.org/draft-07/schema#"; return combined; }; var schemaSymbol3 = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema2(createSchema) { let schema; return () => { if (schema == null) { schema = createSchema(); } return schema; }; } function jsonSchema3(jsonSchema22, { validate } = {}) { return { [schemaSymbol3]: true, _type: void 0, // should never be used directly get jsonSchema() { if (typeof jsonSchema22 === "function") { jsonSchema22 = jsonSchema22(); } return jsonSchema22; }, validate }; } function isSchema3(value) { return typeof value === "object" && value !== null && schemaSymbol3 in value && value[schemaSymbol3] === true && "jsonSchema" in value && "validate" in value; } function asSchema3(schema) { return schema == null ? jsonSchema3({ properties: {}, additionalProperties: false }) : isSchema3(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema3(schema) : standardSchema(schema) : schema(); } function standardSchema(standardSchema2) { return jsonSchema3( () => addAdditionalPropertiesToJsonSchema2( standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }) ), { validate: async (value) => { const result = await standardSchema2["~standard"].validate(value); return "value" in result ? { success: true, value: result.value } : { success: false, error: new TypeValidationError3({ value, cause: result.issues }) }; } } ); } function zod3Schema2(zodSchema22, options) { var _a224; const useReferences = (_a224 = void 0) != null ? _a224 : false; return jsonSchema3( // defer json schema creation to avoid unnecessary computation when only validation is needed () => zod3ToJsonSchema(zodSchema22, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => { const result = await zodSchema22.safeParseAsync(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function zod4Schema2(zodSchema22, options) { var _a224; const useReferences = (_a224 = void 0) != null ? _a224 : false; return jsonSchema3( // defer json schema creation to avoid unnecessary computation when only validation is needed () => addAdditionalPropertiesToJsonSchema2( toJSONSchema2(zodSchema22, { target: "draft-7", io: "input", reused: useReferences ? "ref" : "inline" }) ), { validate: async (value) => { const result = await safeParseAsync4(zodSchema22, value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function isZod4Schema2(zodSchema22) { return "_zod" in zodSchema22; } function zodSchema3(zodSchema22, options) { if (isZod4Schema2(zodSchema22)) { return zod4Schema2(zodSchema22); } else { return zod3Schema2(zodSchema22); } } async function validateTypes2({ value, schema, context: context2 }) { const result = await safeValidateTypes3({ value, schema, context: context2 }); if (!result.success) { throw TypeValidationError3.wrap({ value, cause: result.error, context: context2 }); } return result.value; } async function safeValidateTypes3({ value, schema, context: context2 }) { const actualSchema = asSchema3(schema); try { if (actualSchema.validate == null) { return { success: true, value, rawValue: value }; } const result = await actualSchema.validate(value); if (result.success) { return { success: true, value: result.value, rawValue: value }; } return { success: false, error: TypeValidationError3.wrap({ value, cause: result.error, context: context2 }), rawValue: value }; } catch (error90) { return { success: false, error: TypeValidationError3.wrap({ value, cause: error90, context: context2 }), rawValue: value }; } } async function parseJSON2({ text: text42, schema }) { try { const value = secureJsonParse2(text42); if (schema == null) { return value; } return validateTypes2({ value, schema }); } catch (error90) { if (JSONParseError3.isInstance(error90) || TypeValidationError3.isInstance(error90)) { throw error90; } throw new JSONParseError3({ text: text42, cause: error90 }); } } async function safeParseJSON3({ text: text42, schema }) { try { const value = secureJsonParse2(text42); if (schema == null) { return { success: true, value, rawValue: value }; } return await safeValidateTypes3({ value, schema }); } catch (error90) { return { success: false, error: JSONParseError3.isInstance(error90) ? error90 : new JSONParseError3({ text: text42, cause: error90 }), rawValue: void 0 }; } } function parseJsonEventStream2({ stream, schema }) { return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream2()).pipeThrough( new TransformStream({ async transform({ data }, controller) { if (data === "[DONE]") { return; } controller.enqueue(await safeParseJSON3({ text: data, schema })); } }) ); } var getOriginalFetch22 = () => globalThis.fetch; var postJsonToApi2 = async ({ url: url3, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi2({ url: url3, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postToApi2 = async ({ url: url3, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch22() }) => { try { const response = await fetch2(url3, { method: "POST", headers: withUserAgentSuffix2( headers, `ai-sdk/provider-utils/${VERSION4}`, getRuntimeEnvironmentUserAgent2() ), body: body.content, signal: abortSignal }); const responseHeaders = extractResponseHeaders2(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url: url3, requestBodyValues: body.values }); } catch (error90) { if (isAbortError3(error90) || APICallError3.isInstance(error90)) { throw error90; } throw new APICallError3({ message: "Failed to process error response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: body.values }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url3, requestBodyValues: body.values }); } catch (error90) { if (error90 instanceof Error) { if (isAbortError3(error90) || APICallError3.isInstance(error90)) { throw error90; } } throw new APICallError3({ message: "Failed to process successful response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: body.values }); } } catch (error90) { throw handleFetchError2({ error: error90, url: url3, requestBodyValues: body.values }); } }; function tool2(tool22) { return tool22; } function createProviderToolFactoryWithOutputSchema({ id, inputSchema, outputSchema: outputSchema32, supportsDeferredResults }) { return ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool2({ type: "provider", id, args, inputSchema, outputSchema: outputSchema32, execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, supportsDeferredResults }); } async function resolve2(value) { if (typeof value === "function") { value = value(); } return Promise.resolve(value); } var createJsonErrorResponseHandler2 = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url: url3, requestBodyValues }) => { const responseBody = await response.text(); const responseHeaders = extractResponseHeaders2(response); if (responseBody.trim() === "") { return { responseHeaders, value: new APICallError3({ message: response.statusText, url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } try { const parsedError = await parseJSON2({ text: responseBody, schema: errorSchema }); return { responseHeaders, value: new APICallError3({ message: errorToMessage(parsedError), url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, data: parsedError, isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) }) }; } catch (parseError) { return { responseHeaders, value: new APICallError3({ message: response.statusText, url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } }; var createEventSourceResponseHandler2 = (chunkSchema) => async ({ response }) => { const responseHeaders = extractResponseHeaders2(response); if (response.body == null) { throw new EmptyResponseBodyError2({}); } return { responseHeaders, value: parseJsonEventStream2({ stream: response.body, schema: chunkSchema }) }; }; var createJsonResponseHandler2 = (responseSchema) => async ({ response, url: url3, requestBodyValues }) => { const responseBody = await response.text(); const parsedResult = await safeParseJSON3({ text: responseBody, schema: responseSchema }); const responseHeaders = extractResponseHeaders2(response); if (!parsedResult.success) { throw new APICallError3({ message: "Invalid JSON response", cause: parsedResult.error, statusCode: response.status, responseHeaders, responseBody, url: url3, requestBodyValues }); } return { responseHeaders, value: parsedResult.value, rawValue: parsedResult.rawValue }; }; function withoutTrailingSlash2(url3) { return url3 == null ? void 0 : url3.replace(/\/$/, ""); } function getContext2() { return { headers: {} }; } async function getVercelOidcToken2() { if (process.env.VERCEL_OIDC_TOKEN) { return process.env.VERCEL_OIDC_TOKEN ?? ""; } throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead."); } var marker20 = "vercel.ai.gateway.error"; var symbol26 = Symbol.for(marker20); var _a26; var _b18; var GatewayError2 = class _GatewayError2 extends (_b18 = Error, _a26 = symbol26, _b18) { constructor({ message, statusCode = 500, cause, generationId }) { super(generationId ? `${message} [${generationId}]` : message); this[_a26] = true; this.statusCode = statusCode; this.cause = cause; this.generationId = generationId; } /** * Checks if the given error is a Gateway Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is a Gateway Error, false otherwise. */ static isInstance(error90) { return _GatewayError2.hasMarker(error90); } static hasMarker(error90) { return typeof error90 === "object" && error90 !== null && symbol26 in error90 && error90[symbol26] === true; } }; var name20 = "GatewayAuthenticationError"; var marker26 = `vercel.ai.gateway.error.${name20}`; var symbol27 = Symbol.for(marker26); var _a27; var _b24; var GatewayAuthenticationError2 = class _GatewayAuthenticationError2 extends (_b24 = GatewayError2, _a27 = symbol27, _b24) { constructor({ message = "Authentication failed", statusCode = 401, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a27] = true; this.name = name20; this.type = "authentication_error"; } static isInstance(error90) { return GatewayError2.hasMarker(error90) && symbol27 in error90; } /** * Creates a contextual error message when authentication fails */ static createContextualError({ apiKeyProvided, oidcTokenProvided, message = "Authentication failed", statusCode = 401, cause, generationId }) { let contextualMessage; if (apiKeyProvided) { contextualMessage = `AI Gateway authentication failed: Invalid API key. Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`; } else if (oidcTokenProvided) { contextualMessage = `AI Gateway authentication failed: Invalid OIDC token. Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token. Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`; } else { contextualMessage = `AI Gateway authentication failed: No authentication provided. Option 1 - API key: Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable. Option 2 - OIDC token: Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`; } return new _GatewayAuthenticationError2({ message: contextualMessage, statusCode, cause, generationId }); } }; var name26 = "GatewayInvalidRequestError"; var marker36 = `vercel.ai.gateway.error.${name26}`; var symbol36 = Symbol.for(marker36); var _a36; var _b34; var GatewayInvalidRequestError2 = class extends (_b34 = GatewayError2, _a36 = symbol36, _b34) { constructor({ message = "Invalid request", statusCode = 400, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a36] = true; this.name = name26; this.type = "invalid_request_error"; } static isInstance(error90) { return GatewayError2.hasMarker(error90) && symbol36 in error90; } }; var name36 = "GatewayRateLimitError"; var marker46 = `vercel.ai.gateway.error.${name36}`; var symbol46 = Symbol.for(marker46); var _a46; var _b44; var GatewayRateLimitError2 = class extends (_b44 = GatewayError2, _a46 = symbol46, _b44) { constructor({ message = "Rate limit exceeded", statusCode = 429, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a46] = true; this.name = name36; this.type = "rate_limit_exceeded"; } static isInstance(error90) { return GatewayError2.hasMarker(error90) && symbol46 in error90; } }; var name46 = "GatewayModelNotFoundError"; var marker56 = `vercel.ai.gateway.error.${name46}`; var symbol56 = Symbol.for(marker56); var modelNotFoundParamSchema2 = lazySchema2( () => zodSchema3( external_exports3.object({ modelId: external_exports3.string() }) ) ); var _a56; var _b54; var GatewayModelNotFoundError2 = class extends (_b54 = GatewayError2, _a56 = symbol56, _b54) { constructor({ message = "Model not found", statusCode = 404, modelId, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a56] = true; this.name = name46; this.type = "model_not_found"; this.modelId = modelId; } static isInstance(error90) { return GatewayError2.hasMarker(error90) && symbol56 in error90; } }; var name56 = "GatewayInternalServerError"; var marker66 = `vercel.ai.gateway.error.${name56}`; var symbol66 = Symbol.for(marker66); var _a66; var _b64; var GatewayInternalServerError2 = class extends (_b64 = GatewayError2, _a66 = symbol66, _b64) { constructor({ message = "Internal server error", statusCode = 500, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a66] = true; this.name = name56; this.type = "internal_server_error"; } static isInstance(error90) { return GatewayError2.hasMarker(error90) && symbol66 in error90; } }; var name66 = "GatewayResponseError"; var marker76 = `vercel.ai.gateway.error.${name66}`; var symbol76 = Symbol.for(marker76); var _a76; var _b74; var GatewayResponseError2 = class extends (_b74 = GatewayError2, _a76 = symbol76, _b74) { constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a76] = true; this.name = name66; this.type = "response_error"; this.response = response; this.validationError = validationError; } static isInstance(error90) { return GatewayError2.hasMarker(error90) && symbol76 in error90; } }; async function createGatewayErrorFromResponse2({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) { var _a932; const parseResult = await safeValidateTypes3({ value: response, schema: gatewayErrorResponseSchema2 }); if (!parseResult.success) { const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : void 0; return new GatewayResponseError2({ message: `Invalid error response format: ${defaultMessage}`, statusCode, response, validationError: parseResult.error, cause, generationId: rawGenerationId }); } const validatedResponse = parseResult.value; const errorType = validatedResponse.error.type; const message = validatedResponse.error.message; const generationId = (_a932 = validatedResponse.generationId) != null ? _a932 : void 0; switch (errorType) { case "authentication_error": return GatewayAuthenticationError2.createContextualError({ apiKeyProvided: authMethod === "api-key", oidcTokenProvided: authMethod === "oidc", statusCode, cause, generationId }); case "invalid_request_error": return new GatewayInvalidRequestError2({ message, statusCode, cause, generationId }); case "rate_limit_exceeded": return new GatewayRateLimitError2({ message, statusCode, cause, generationId }); case "model_not_found": { const modelResult = await safeValidateTypes3({ value: validatedResponse.error.param, schema: modelNotFoundParamSchema2 }); return new GatewayModelNotFoundError2({ message, statusCode, modelId: modelResult.success ? modelResult.value.modelId : void 0, cause, generationId }); } case "internal_server_error": return new GatewayInternalServerError2({ message, statusCode, cause, generationId }); default: return new GatewayInternalServerError2({ message, statusCode, cause, generationId }); } } var gatewayErrorResponseSchema2 = lazySchema2( () => zodSchema3( external_exports3.object({ error: external_exports3.object({ message: external_exports3.string(), type: external_exports3.string().nullish(), param: external_exports3.unknown().nullish(), code: external_exports3.union([external_exports3.string(), external_exports3.number()]).nullish() }), generationId: external_exports3.string().nullish() }) ) ); function extractApiCallResponse2(error90) { if (error90.data !== void 0) { return error90.data; } if (error90.responseBody != null) { try { return JSON.parse(error90.responseBody); } catch (e2) { return error90.responseBody; } } return {}; } var name76 = "GatewayTimeoutError"; var marker86 = `vercel.ai.gateway.error.${name76}`; var symbol86 = Symbol.for(marker86); var _a86; var _b84; var GatewayTimeoutError2 = class _GatewayTimeoutError2 extends (_b84 = GatewayError2, _a86 = symbol86, _b84) { constructor({ message = "Request timed out", statusCode = 408, cause, generationId } = {}) { super({ message, statusCode, cause, generationId }); this[_a86] = true; this.name = name76; this.type = "timeout_error"; } static isInstance(error90) { return GatewayError2.hasMarker(error90) && symbol86 in error90; } /** * Creates a helpful timeout error message with troubleshooting guidance */ static createTimeoutError({ originalMessage, statusCode = 408, cause, generationId }) { const message = `Gateway request timed out: ${originalMessage} This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`; return new _GatewayTimeoutError2({ message, statusCode, cause, generationId }); } }; function isTimeoutError2(error90) { if (!(error90 instanceof Error)) { return false; } const errorCode = error90.code; if (typeof errorCode === "string") { const undiciTimeoutCodes = [ "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT" ]; return undiciTimeoutCodes.includes(errorCode); } return false; } async function asGatewayError2(error90, authMethod) { var _a932; if (GatewayError2.isInstance(error90)) { return error90; } if (isTimeoutError2(error90)) { return GatewayTimeoutError2.createTimeoutError({ originalMessage: error90 instanceof Error ? error90.message : "Unknown error", cause: error90 }); } if (APICallError3.isInstance(error90)) { if (error90.cause && isTimeoutError2(error90.cause)) { return GatewayTimeoutError2.createTimeoutError({ originalMessage: error90.message, cause: error90 }); } return await createGatewayErrorFromResponse2({ response: extractApiCallResponse2(error90), statusCode: (_a932 = error90.statusCode) != null ? _a932 : 500, defaultMessage: "Gateway request failed", cause: error90, authMethod }); } return await createGatewayErrorFromResponse2({ response: {}, statusCode: 500, defaultMessage: error90 instanceof Error ? `Gateway request failed: ${error90.message}` : "Unknown Gateway error", cause: error90, authMethod }); } var GATEWAY_AUTH_METHOD_HEADER2 = "ai-gateway-auth-method"; async function parseAuthMethod2(headers) { const result = await safeValidateTypes3({ value: headers[GATEWAY_AUTH_METHOD_HEADER2], schema: gatewayAuthMethodSchema2 }); return result.success ? result.value : void 0; } var gatewayAuthMethodSchema2 = lazySchema2( () => zodSchema3(external_exports3.union([external_exports3.literal("api-key"), external_exports3.literal("oidc")])) ); var KNOWN_MODEL_TYPES2 = [ "embedding", "image", "language", "reranking", "video" ]; var GatewayFetchMetadata2 = class { constructor(config3) { this.config = config3; } async getAvailableModels() { try { const { value } = await getFromApi2({ url: `${this.config.baseURL}/config`, headers: await resolve2(this.config.headers()), successfulResponseHandler: createJsonResponseHandler2( gatewayAvailableModelsResponseSchema2 ), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError2(error90); } } async getCredits() { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi2({ url: `${baseUrl.origin}/v1/credits`, headers: await resolve2(this.config.headers()), successfulResponseHandler: createJsonResponseHandler2( gatewayCreditsResponseSchema2 ), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError2(error90); } } }; var gatewayAvailableModelsResponseSchema2 = lazySchema2( () => zodSchema3( external_exports3.object({ models: external_exports3.array( external_exports3.object({ id: external_exports3.string(), name: external_exports3.string(), description: external_exports3.string().nullish(), pricing: external_exports3.object({ input: external_exports3.string(), output: external_exports3.string(), input_cache_read: external_exports3.string().nullish(), input_cache_write: external_exports3.string().nullish() }).transform( ({ input, output, input_cache_read, input_cache_write }) => ({ input, output, ...input_cache_read ? { cachedInputTokens: input_cache_read } : {}, ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {} }) ).nullish(), specification: external_exports3.object({ specificationVersion: external_exports3.literal("v3"), provider: external_exports3.string(), modelId: external_exports3.string() }), modelType: external_exports3.string().nullish() }) ).transform( (models) => models.filter( (m) => m.modelType == null || KNOWN_MODEL_TYPES2.includes(m.modelType) ) ) }) ) ); var gatewayCreditsResponseSchema2 = lazySchema2( () => zodSchema3( external_exports3.object({ balance: external_exports3.string(), total_used: external_exports3.string() }).transform(({ balance, total_used }) => ({ balance, totalUsed: total_used })) ) ); var GatewaySpendReport2 = class { constructor(config3) { this.config = config3; } async getSpendReport(params) { try { const baseUrl = new URL(this.config.baseURL); const searchParams = new URLSearchParams(); searchParams.set("start_date", params.startDate); searchParams.set("end_date", params.endDate); if (params.groupBy) { searchParams.set("group_by", params.groupBy); } if (params.datePart) { searchParams.set("date_part", params.datePart); } if (params.userId) { searchParams.set("user_id", params.userId); } if (params.model) { searchParams.set("model", params.model); } if (params.provider) { searchParams.set("provider", params.provider); } if (params.credentialType) { searchParams.set("credential_type", params.credentialType); } if (params.tags && params.tags.length > 0) { searchParams.set("tags", params.tags.join(",")); } const { value } = await getFromApi2({ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`, headers: await resolve2(this.config.headers()), successfulResponseHandler: createJsonResponseHandler2( gatewaySpendReportResponseSchema2 ), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError2(error90); } } }; var gatewaySpendReportResponseSchema2 = lazySchema2( () => zodSchema3( external_exports3.object({ results: external_exports3.array( external_exports3.object({ day: external_exports3.string().optional(), hour: external_exports3.string().optional(), user: external_exports3.string().optional(), model: external_exports3.string().optional(), tag: external_exports3.string().optional(), provider: external_exports3.string().optional(), credential_type: external_exports3.enum(["byok", "system"]).optional(), total_cost: external_exports3.number(), market_cost: external_exports3.number().optional(), input_tokens: external_exports3.number().optional(), output_tokens: external_exports3.number().optional(), cached_input_tokens: external_exports3.number().optional(), cache_creation_input_tokens: external_exports3.number().optional(), reasoning_tokens: external_exports3.number().optional(), request_count: external_exports3.number().optional() }).transform( ({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({ ...rest, ...credential_type !== void 0 ? { credentialType: credential_type } : {}, totalCost: total_cost, ...market_cost !== void 0 ? { marketCost: market_cost } : {}, ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {}, ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {}, ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {}, ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {}, ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {}, ...request_count !== void 0 ? { requestCount: request_count } : {} }) ) ) }) ) ); var GatewayGenerationInfoFetcher2 = class { constructor(config3) { this.config = config3; } async getGenerationInfo(params) { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi2({ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`, headers: await resolve2(this.config.headers()), successfulResponseHandler: createJsonResponseHandler2( gatewayGenerationInfoResponseSchema2 ), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError2(error90); } } }; var gatewayGenerationInfoResponseSchema2 = lazySchema2( () => zodSchema3( external_exports3.object({ data: external_exports3.object({ id: external_exports3.string(), total_cost: external_exports3.number(), upstream_inference_cost: external_exports3.number(), usage: external_exports3.number(), created_at: external_exports3.string(), model: external_exports3.string(), is_byok: external_exports3.boolean(), provider_name: external_exports3.string(), streamed: external_exports3.boolean(), finish_reason: external_exports3.string(), latency: external_exports3.number(), generation_time: external_exports3.number(), native_tokens_prompt: external_exports3.number(), native_tokens_completion: external_exports3.number(), native_tokens_reasoning: external_exports3.number(), native_tokens_cached: external_exports3.number(), native_tokens_cache_creation: external_exports3.number(), billable_web_search_calls: external_exports3.number() }).transform( ({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({ ...rest, totalCost: total_cost, upstreamInferenceCost: upstream_inference_cost, createdAt: created_at, isByok: is_byok, providerName: provider_name, finishReason: finish_reason, generationTime: generation_time, promptTokens: native_tokens_prompt, completionTokens: native_tokens_completion, reasoningTokens: native_tokens_reasoning, cachedTokens: native_tokens_cached, cacheCreationTokens: native_tokens_cache_creation, billableWebSearchCalls: billable_web_search_calls }) ) }).transform(({ data }) => data) ) ); var GatewayLanguageModel2 = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v3"; this.supportedUrls = { "*/*": [/.*/] }; } get provider() { return this.config.provider; } async getArgs(options) { const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options; return { args: this.maybeEncodeFileParts(optionsWithoutSignal), warnings: [] }; } async doGenerate(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = await resolve2(this.config.headers()); try { const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi2({ url: this.getUrl(), headers: combineHeaders2( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve2(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createJsonResponseHandler2(external_exports3.any()), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { ...responseBody, request: { body: args }, response: { headers: responseHeaders, body: rawResponse }, warnings }; } catch (error90) { throw await asGatewayError2(error90, await parseAuthMethod2(resolvedHeaders)); } } async doStream(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = await resolve2(this.config.headers()); try { const { value: response, responseHeaders } = await postJsonToApi2({ url: this.getUrl(), headers: combineHeaders2( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve2(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createEventSourceResponseHandler2(external_exports3.any()), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { stream: response.pipeThrough( new TransformStream({ start(controller) { if (warnings.length > 0) { controller.enqueue({ type: "stream-start", warnings }); } }, transform(chunk, controller) { if (chunk.success) { const streamPart = chunk.value; if (streamPart.type === "raw" && !options.includeRawChunks) { return; } if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") { streamPart.timestamp = new Date(streamPart.timestamp); } controller.enqueue(streamPart); } else { controller.error( chunk.error ); } } }) ), request: { body: args }, response: { headers: responseHeaders } }; } catch (error90) { throw await asGatewayError2(error90, await parseAuthMethod2(resolvedHeaders)); } } isFilePart(part) { return part && typeof part === "object" && "type" in part && part.type === "file"; } /** * Encodes file parts in the prompt to base64. Mutates the passed options * instance directly to avoid copying the file data. * @param options - The options to encode. * @returns The options with the file parts encoded. */ maybeEncodeFileParts(options) { for (const message of options.prompt) { for (const part of message.content) { if (this.isFilePart(part)) { const filePart = part; if (filePart.data instanceof Uint8Array) { const buffer = Uint8Array.from(filePart.data); const base64Data = Buffer.from(buffer).toString("base64"); filePart.data = new URL( `data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}` ); } } } } return options; } getUrl() { return `${this.config.baseURL}/language-model`; } getModelConfigHeaders(modelId, streaming) { return { "ai-language-model-specification-version": "3", "ai-language-model-id": modelId, "ai-language-model-streaming": String(streaming) }; } }; var GatewayEmbeddingModel2 = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v3"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a932; const resolvedHeaders = await resolve2(this.config.headers()); try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi2({ url: this.getUrl(), headers: combineHeaders2( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve2(this.config.o11yHeaders) ), body: { values, ...providerOptions ? { providerOptions } : {} }, successfulResponseHandler: createJsonResponseHandler2( gatewayEmbeddingResponseSchema2 ), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { embeddings: responseBody.embeddings, usage: (_a932 = responseBody.usage) != null ? _a932 : void 0, providerMetadata: responseBody.providerMetadata, response: { headers: responseHeaders, body: rawValue }, warnings: [] }; } catch (error90) { throw await asGatewayError2(error90, await parseAuthMethod2(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/embedding-model`; } getModelConfigHeaders() { return { "ai-embedding-model-specification-version": "3", "ai-model-id": this.modelId }; } }; var gatewayEmbeddingResponseSchema2 = lazySchema2( () => zodSchema3( external_exports3.object({ embeddings: external_exports3.array(external_exports3.array(external_exports3.number())), usage: external_exports3.object({ tokens: external_exports3.number() }).nullish(), providerMetadata: external_exports3.record(external_exports3.string(), external_exports3.record(external_exports3.string(), external_exports3.unknown())).optional() }) ) ); var GatewayImageModel2 = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v3"; this.maxImagesPerCall = Number.MAX_SAFE_INTEGER; } get provider() { return this.config.provider; } async doGenerate({ prompt, n, size, aspectRatio, seed, files, mask, providerOptions, headers, abortSignal }) { var _a932, _b93, _c, _d; const resolvedHeaders = await resolve2(this.config.headers()); try { const { responseHeaders, value: responseBody } = await postJsonToApi2({ url: this.getUrl(), headers: combineHeaders2( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve2(this.config.o11yHeaders) ), body: { prompt, n, ...size && { size }, ...aspectRatio && { aspectRatio }, ...seed && { seed }, ...providerOptions && { providerOptions }, ...files && { files: files.map((file3) => maybeEncodeImageFile(file3)) }, ...mask && { mask: maybeEncodeImageFile(mask) } }, successfulResponseHandler: createJsonResponseHandler2( gatewayImageResponseSchema2 ), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { images: responseBody.images, // Always base64 strings from server warnings: (_a932 = responseBody.warnings) != null ? _a932 : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders }, ...responseBody.usage != null && { usage: { inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0, outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0, totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0 } } }; } catch (error90) { throw await asGatewayError2(error90, await parseAuthMethod2(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/image-model`; } getModelConfigHeaders() { return { "ai-image-model-specification-version": "3", "ai-model-id": this.modelId }; } }; function maybeEncodeImageFile(file3) { if (file3.type === "file" && file3.data instanceof Uint8Array) { return { ...file3, data: convertUint8ArrayToBase643(file3.data) }; } return file3; } var providerMetadataEntrySchema2 = external_exports3.object({ images: external_exports3.array(external_exports3.unknown()).optional() }).catchall(external_exports3.unknown()); var gatewayImageWarningSchema = external_exports3.discriminatedUnion("type", [ external_exports3.object({ type: external_exports3.literal("unsupported"), feature: external_exports3.string(), details: external_exports3.string().optional() }), external_exports3.object({ type: external_exports3.literal("compatibility"), feature: external_exports3.string(), details: external_exports3.string().optional() }), external_exports3.object({ type: external_exports3.literal("other"), message: external_exports3.string() }) ]); var gatewayImageUsageSchema2 = external_exports3.object({ inputTokens: external_exports3.number().nullish(), outputTokens: external_exports3.number().nullish(), totalTokens: external_exports3.number().nullish() }); var gatewayImageResponseSchema2 = external_exports3.object({ images: external_exports3.array(external_exports3.string()), // Always base64 strings over the wire warnings: external_exports3.array(gatewayImageWarningSchema).optional(), providerMetadata: external_exports3.record(external_exports3.string(), providerMetadataEntrySchema2).optional(), usage: gatewayImageUsageSchema2.optional() }); var GatewayVideoModel = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v3"; this.maxVideosPerCall = Number.MAX_SAFE_INTEGER; } get provider() { return this.config.provider; } async doGenerate({ prompt, n, aspectRatio, resolution, duration: duration5, fps, seed, image, providerOptions, headers, abortSignal }) { var _a932; const resolvedHeaders = await resolve2(this.config.headers()); try { const { responseHeaders, value: responseBody } = await postJsonToApi2({ url: this.getUrl(), headers: combineHeaders2( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve2(this.config.o11yHeaders), { accept: "text/event-stream" } ), body: { prompt, n, ...aspectRatio && { aspectRatio }, ...resolution && { resolution }, ...duration5 && { duration: duration5 }, ...fps && { fps }, ...seed && { seed }, ...providerOptions && { providerOptions }, ...image && { image: maybeEncodeVideoFile(image) } }, successfulResponseHandler: async ({ response, url: url3, requestBodyValues }) => { if (response.body == null) { throw new APICallError3({ message: "SSE response body is empty", url: url3, requestBodyValues, statusCode: response.status }); } const eventStream = parseJsonEventStream2({ stream: response.body, schema: gatewayVideoEventSchema }); const reader = eventStream.getReader(); const { done, value: parseResult } = await reader.read(); reader.releaseLock(); if (done || !parseResult) { throw new APICallError3({ message: "SSE stream ended without a data event", url: url3, requestBodyValues, statusCode: response.status }); } if (!parseResult.success) { throw new APICallError3({ message: "Failed to parse video SSE event", cause: parseResult.error, url: url3, requestBodyValues, statusCode: response.status }); } const event = parseResult.value; if (event.type === "error") { throw new APICallError3({ message: event.message, statusCode: event.statusCode, url: url3, requestBodyValues, responseHeaders: Object.fromEntries([...response.headers]), responseBody: JSON.stringify(event), data: { error: { message: event.message, type: event.errorType, param: event.param } } }); } return { value: { videos: event.videos, warnings: event.warnings, providerMetadata: event.providerMetadata }, responseHeaders: Object.fromEntries([...response.headers]) }; }, failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { videos: responseBody.videos, warnings: (_a932 = responseBody.warnings) != null ? _a932 : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders } }; } catch (error90) { throw await asGatewayError2(error90, await parseAuthMethod2(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/video-model`; } getModelConfigHeaders() { return { "ai-video-model-specification-version": "3", "ai-model-id": this.modelId }; } }; function maybeEncodeVideoFile(file3) { if (file3.type === "file" && file3.data instanceof Uint8Array) { return { ...file3, data: convertUint8ArrayToBase643(file3.data) }; } return file3; } var providerMetadataEntrySchema22 = external_exports3.object({ videos: external_exports3.array(external_exports3.unknown()).optional() }).catchall(external_exports3.unknown()); var gatewayVideoDataSchema = external_exports3.union([ external_exports3.object({ type: external_exports3.literal("url"), url: external_exports3.string(), mediaType: external_exports3.string() }), external_exports3.object({ type: external_exports3.literal("base64"), data: external_exports3.string(), mediaType: external_exports3.string() }) ]); var gatewayVideoWarningSchema = external_exports3.discriminatedUnion("type", [ external_exports3.object({ type: external_exports3.literal("unsupported"), feature: external_exports3.string(), details: external_exports3.string().optional() }), external_exports3.object({ type: external_exports3.literal("compatibility"), feature: external_exports3.string(), details: external_exports3.string().optional() }), external_exports3.object({ type: external_exports3.literal("other"), message: external_exports3.string() }) ]); var gatewayVideoEventSchema = external_exports3.discriminatedUnion("type", [ external_exports3.object({ type: external_exports3.literal("result"), videos: external_exports3.array(gatewayVideoDataSchema), warnings: external_exports3.array(gatewayVideoWarningSchema).optional(), providerMetadata: external_exports3.record(external_exports3.string(), providerMetadataEntrySchema22).optional() }), external_exports3.object({ type: external_exports3.literal("error"), message: external_exports3.string(), errorType: external_exports3.string(), statusCode: external_exports3.number(), param: external_exports3.unknown().nullable() }) ]); var GatewayRerankingModel = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v3"; } get provider() { return this.config.provider; } async doRerank({ documents, query, topN, headers, abortSignal, providerOptions }) { const resolvedHeaders = await resolve2(this.config.headers()); try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi2({ url: this.getUrl(), headers: combineHeaders2( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve2(this.config.o11yHeaders) ), body: { documents, query, ...topN != null ? { topN } : {}, ...providerOptions ? { providerOptions } : {} }, successfulResponseHandler: createJsonResponseHandler2( gatewayRerankingResponseSchema ), failedResponseHandler: createJsonErrorResponseHandler2({ errorSchema: external_exports3.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { ranking: responseBody.ranking, providerMetadata: responseBody.providerMetadata, response: { headers: responseHeaders, body: rawValue }, warnings: [] }; } catch (error90) { throw await asGatewayError2(error90, await parseAuthMethod2(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/reranking-model`; } getModelConfigHeaders() { return { "ai-reranking-model-specification-version": "3", "ai-model-id": this.modelId }; } }; var gatewayRerankingResponseSchema = lazySchema2( () => zodSchema3( external_exports3.object({ ranking: external_exports3.array( external_exports3.object({ index: external_exports3.number(), relevanceScore: external_exports3.number() }) ), providerMetadata: external_exports3.record(external_exports3.string(), external_exports3.record(external_exports3.string(), external_exports3.unknown())).optional() }) ) ); var parallelSearchInputSchema2 = lazySchema2( () => zodSchema3( external_exports.object({ objective: external_exports.string().describe( "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters." ), search_queries: external_exports.array(external_exports.string()).optional().describe( "Optional search queries to supplement the objective. Maximum 200 characters per query." ), mode: external_exports.enum(["one-shot", "agentic"]).optional().describe( 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.' ), max_results: external_exports.number().optional().describe( "Maximum number of results to return (1-20). Defaults to 10 if not specified." ), source_policy: external_exports.object({ include_domains: external_exports.array(external_exports.string()).optional().describe("List of domains to include in search results."), exclude_domains: external_exports.array(external_exports.string()).optional().describe("List of domains to exclude from search results."), after_date: external_exports.string().optional().describe( "Only include results published after this date (ISO 8601 format)." ) }).optional().describe( "Source policy for controlling which domains to include/exclude and freshness." ), excerpts: external_exports.object({ max_chars_per_result: external_exports.number().optional().describe("Maximum characters per result."), max_chars_total: external_exports.number().optional().describe("Maximum total characters across all results.") }).optional().describe("Excerpt configuration for controlling result length."), fetch_policy: external_exports.object({ max_age_seconds: external_exports.number().optional().describe( "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content." ) }).optional().describe("Fetch policy for controlling content freshness.") }) ) ); var parallelSearchOutputSchema2 = lazySchema2( () => zodSchema3( external_exports.union([ // Success response external_exports.object({ searchId: external_exports.string(), results: external_exports.array( external_exports.object({ url: external_exports.string(), title: external_exports.string(), excerpt: external_exports.string(), publishDate: external_exports.string().nullable().optional(), relevanceScore: external_exports.number().optional() }) ) }), // Error response external_exports.object({ error: external_exports.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "configuration_error", "unknown" ]), statusCode: external_exports.number().optional(), message: external_exports.string() }) ]) ) ); var parallelSearchToolFactory2 = createProviderToolFactoryWithOutputSchema({ id: "gateway.parallel_search", inputSchema: parallelSearchInputSchema2, outputSchema: parallelSearchOutputSchema2 }); var parallelSearch2 = (config3 = {}) => parallelSearchToolFactory2(config3); var perplexitySearchInputSchema2 = lazySchema2( () => zodSchema3( external_exports.object({ query: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).describe( "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries." ), max_results: external_exports.number().optional().describe( "Maximum number of search results to return (1-20, default: 10)" ), max_tokens_per_page: external_exports.number().optional().describe( "Maximum number of tokens to extract per search result page (256-2048, default: 2048)" ), max_tokens: external_exports.number().optional().describe( "Maximum total tokens across all search results (default: 25000, max: 1000000)" ), country: external_exports.string().optional().describe( "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')" ), search_domain_filter: external_exports.array(external_exports.string()).optional().describe( "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']" ), search_language_filter: external_exports.array(external_exports.string()).optional().describe( "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']" ), search_after_date: external_exports.string().optional().describe( "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter." ), search_before_date: external_exports.string().optional().describe( "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter." ), last_updated_after_filter: external_exports.string().optional().describe( "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter." ), last_updated_before_filter: external_exports.string().optional().describe( "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter." ), search_recency_filter: external_exports.enum(["day", "week", "month", "year"]).optional().describe( "Filter results by relative time period. Cannot be used with search_after_date or search_before_date." ) }) ) ); var perplexitySearchOutputSchema2 = lazySchema2( () => zodSchema3( external_exports.union([ // Success response external_exports.object({ results: external_exports.array( external_exports.object({ title: external_exports.string(), url: external_exports.string(), snippet: external_exports.string(), date: external_exports.string().optional(), lastUpdated: external_exports.string().optional() }) ), id: external_exports.string() }), // Error response external_exports.object({ error: external_exports.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "unknown" ]), statusCode: external_exports.number().optional(), message: external_exports.string() }) ]) ) ); var perplexitySearchToolFactory2 = createProviderToolFactoryWithOutputSchema({ id: "gateway.perplexity_search", inputSchema: perplexitySearchInputSchema2, outputSchema: perplexitySearchOutputSchema2 }); var perplexitySearch2 = (config3 = {}) => perplexitySearchToolFactory2(config3); var gatewayTools2 = { /** * Search the web using Parallel AI's Search API for LLM-optimized excerpts. * * Takes a natural language objective and returns relevant excerpts, * replacing multiple keyword searches with a single call for broad * or complex queries. Supports different search types for depth vs * breadth tradeoffs. */ parallelSearch: parallelSearch2, /** * Search the web using Perplexity's Search API for real-time information, * news, research papers, and articles. * * Provides ranked search results with advanced filtering options including * domain, language, date range, and recency filters. */ perplexitySearch: perplexitySearch2 }; async function getVercelRequestId2() { var _a932; return (_a932 = getContext2().headers) == null ? void 0 : _a932["x-vercel-id"]; } var VERSION5 = "3.0.112"; var AI_GATEWAY_PROTOCOL_VERSION2 = "0.0.1"; function createGatewayProvider2(options = {}) { var _a932, _b93; let pendingMetadata = null; let metadataCache = null; const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5; let lastFetchTime = 0; const baseURL = (_b93 = withoutTrailingSlash2(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v3/ai"; const getHeaders = async () => { try { const auth = await getGatewayAuthToken2(options); return withUserAgentSuffix2( { Authorization: `Bearer ${auth.token}`, "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION2, [GATEWAY_AUTH_METHOD_HEADER2]: auth.authMethod, ...options.headers }, `ai-sdk/gateway/${VERSION5}` ); } catch (error90) { throw GatewayAuthenticationError2.createContextualError({ apiKeyProvided: false, oidcTokenProvided: false, statusCode: 401, cause: error90 }); } }; const createO11yHeaders = () => { const deploymentId = loadOptionalSetting2({ settingValue: void 0, environmentVariableName: "VERCEL_DEPLOYMENT_ID" }); const environment = loadOptionalSetting2({ settingValue: void 0, environmentVariableName: "VERCEL_ENV" }); const region = loadOptionalSetting2({ settingValue: void 0, environmentVariableName: "VERCEL_REGION" }); const projectId = loadOptionalSetting2({ settingValue: void 0, environmentVariableName: "VERCEL_PROJECT_ID" }); return async () => { const requestId = await getVercelRequestId2(); return { ...deploymentId && { "ai-o11y-deployment-id": deploymentId }, ...environment && { "ai-o11y-environment": environment }, ...region && { "ai-o11y-region": region }, ...requestId && { "ai-o11y-request-id": requestId }, ...projectId && { "ai-o11y-project-id": projectId } }; }; }; const createLanguageModel = (modelId) => { return new GatewayLanguageModel2(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; const getAvailableModels = async () => { var _a1022, _b103, _c; const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now(); if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) { lastFetchTime = now2; pendingMetadata = new GatewayFetchMetadata2({ baseURL, headers: getHeaders, fetch: options.fetch }).getAvailableModels().then((metadata) => { metadataCache = metadata; return metadata; }).catch(async (error90) => { throw await asGatewayError2( error90, await parseAuthMethod2(await getHeaders()) ); }); } return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata; }; const getCredits = async () => { return new GatewayFetchMetadata2({ baseURL, headers: getHeaders, fetch: options.fetch }).getCredits().catch(async (error90) => { throw await asGatewayError2( error90, await parseAuthMethod2(await getHeaders()) ); }); }; const getSpendReport = async (params) => { return new GatewaySpendReport2({ baseURL, headers: getHeaders, fetch: options.fetch }).getSpendReport(params).catch(async (error90) => { throw await asGatewayError2( error90, await parseAuthMethod2(await getHeaders()) ); }); }; const getGenerationInfo = async (params) => { return new GatewayGenerationInfoFetcher2({ baseURL, headers: getHeaders, fetch: options.fetch }).getGenerationInfo(params).catch(async (error90) => { throw await asGatewayError2( error90, await parseAuthMethod2(await getHeaders()) ); }); }; const provider = function(modelId) { if (new.target) { throw new Error( "The Gateway Provider model function cannot be called with the new keyword." ); } return createLanguageModel(modelId); }; provider.specificationVersion = "v3"; provider.getAvailableModels = getAvailableModels; provider.getCredits = getCredits; provider.getSpendReport = getSpendReport; provider.getGenerationInfo = getGenerationInfo; provider.imageModel = (modelId) => { return new GatewayImageModel2(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.languageModel = createLanguageModel; const createEmbeddingModel = (modelId) => { return new GatewayEmbeddingModel2(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.embeddingModel = createEmbeddingModel; provider.textEmbeddingModel = createEmbeddingModel; provider.videoModel = (modelId) => { return new GatewayVideoModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; const createRerankingModel = (modelId) => { return new GatewayRerankingModel(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.rerankingModel = createRerankingModel; provider.reranking = createRerankingModel; provider.chat = provider.languageModel; provider.embedding = provider.embeddingModel; provider.image = provider.imageModel; provider.video = provider.videoModel; provider.tools = gatewayTools2; return provider; } var gateway2 = createGatewayProvider2(); async function getGatewayAuthToken2(options) { const apiKey = loadOptionalSetting2({ settingValue: options.apiKey, environmentVariableName: "AI_GATEWAY_API_KEY" }); if (apiKey) { return { token: apiKey, authMethod: "api-key" }; } const oidcToken = await getVercelOidcToken2(); return { token: oidcToken, authMethod: "oidc" }; } var _globalThis3 = typeof globalThis === "object" ? globalThis : global; var VERSION23 = "1.9.0"; var re3 = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; function _makeCompatibilityCheck3(ownVersion) { var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); var rejectedVersions = /* @__PURE__ */ new Set(); var myVersionMatch = ownVersion.match(re3); if (!myVersionMatch) { return function() { return false; }; } var ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], prerelease: myVersionMatch[4] }; if (ownVersionParsed.prerelease != null) { return function isExactmatch(globalVersion) { return globalVersion === ownVersion; }; } function _reject(v) { rejectedVersions.add(v); return false; } function _accept(v) { acceptedVersions.add(v); return true; } return function isCompatible22(globalVersion) { if (acceptedVersions.has(globalVersion)) { return true; } if (rejectedVersions.has(globalVersion)) { return false; } var globalVersionMatch = globalVersion.match(re3); if (!globalVersionMatch) { return _reject(globalVersion); } var globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], prerelease: globalVersionMatch[4] }; if (globalVersionParsed.prerelease != null) { return _reject(globalVersion); } if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); } if (ownVersionParsed.major === 0) { if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { return _accept(globalVersion); } return _reject(globalVersion); } if (ownVersionParsed.minor <= globalVersionParsed.minor) { return _accept(globalVersion); } return _reject(globalVersion); }; } var isCompatible3 = _makeCompatibilityCheck3(VERSION23); var major3 = VERSION23.split(".")[0]; var GLOBAL_OPENTELEMETRY_API_KEY3 = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major3); var _global3 = _globalThis3; function registerGlobal3(type, instance, diag, allowOverride) { var _a212; if (allowOverride === void 0) { allowOverride = false; } var api = _global3[GLOBAL_OPENTELEMETRY_API_KEY3] = (_a212 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) !== null && _a212 !== void 0 ? _a212 : { version: VERSION23 }; if (!allowOverride && api[type]) { var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); diag.error(err.stack || err.message); return false; } if (api.version !== VERSION23) { var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION23); diag.error(err.stack || err.message); return false; } api[type] = instance; diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION23 + "."); return true; } function getGlobal3(type) { var _a212, _b93; var globalVersion = (_a212 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _a212 === void 0 ? void 0 : _a212.version; if (!globalVersion || !isCompatible3(globalVersion)) { return; } return (_b93 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _b93 === void 0 ? void 0 : _b93[type]; } function unregisterGlobal3(type, diag) { diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION23 + "."); var api = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]; if (api) { delete api[type]; } } var __read6 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray6 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var DiagComponentLogger3 = ( /** @class */ (function() { function DiagComponentLogger22(props) { this._namespace = props.namespace || "DiagComponentLogger"; } DiagComponentLogger22.prototype.debug = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy3("debug", this._namespace, args); }; DiagComponentLogger22.prototype.error = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy3("error", this._namespace, args); }; DiagComponentLogger22.prototype.info = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy3("info", this._namespace, args); }; DiagComponentLogger22.prototype.warn = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy3("warn", this._namespace, args); }; DiagComponentLogger22.prototype.verbose = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy3("verbose", this._namespace, args); }; return DiagComponentLogger22; })() ); function logProxy3(funcName, namespace, args) { var logger = getGlobal3("diag"); if (!logger) { return; } args.unshift(namespace); return logger[funcName].apply(logger, __spreadArray6([], __read6(args), false)); } var DiagLogLevel3; (function(DiagLogLevel22) { DiagLogLevel22[DiagLogLevel22["NONE"] = 0] = "NONE"; DiagLogLevel22[DiagLogLevel22["ERROR"] = 30] = "ERROR"; DiagLogLevel22[DiagLogLevel22["WARN"] = 50] = "WARN"; DiagLogLevel22[DiagLogLevel22["INFO"] = 60] = "INFO"; DiagLogLevel22[DiagLogLevel22["DEBUG"] = 70] = "DEBUG"; DiagLogLevel22[DiagLogLevel22["VERBOSE"] = 80] = "VERBOSE"; DiagLogLevel22[DiagLogLevel22["ALL"] = 9999] = "ALL"; })(DiagLogLevel3 || (DiagLogLevel3 = {})); function createLogLevelDiagLogger3(maxLevel, logger) { if (maxLevel < DiagLogLevel3.NONE) { maxLevel = DiagLogLevel3.NONE; } else if (maxLevel > DiagLogLevel3.ALL) { maxLevel = DiagLogLevel3.ALL; } logger = logger || {}; function _filterFunc(funcName, theLevel) { var theFunc = logger[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { return theFunc.bind(logger); } return function() { }; } return { error: _filterFunc("error", DiagLogLevel3.ERROR), warn: _filterFunc("warn", DiagLogLevel3.WARN), info: _filterFunc("info", DiagLogLevel3.INFO), debug: _filterFunc("debug", DiagLogLevel3.DEBUG), verbose: _filterFunc("verbose", DiagLogLevel3.VERBOSE) }; } var __read23 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray23 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME5 = "diag"; var DiagAPI3 = ( /** @class */ (function() { function DiagAPI22() { function _logProxy(funcName) { return function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var logger = getGlobal3("diag"); if (!logger) return; return logger[funcName].apply(logger, __spreadArray23([], __read23(args), false)); }; } var self = this; var setLogger = function(logger, optionsOrLogLevel) { var _a212, _b93, _c; if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel3.INFO }; } if (logger === self) { var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self.error((_a212 = err.stack) !== null && _a212 !== void 0 ? _a212 : err.message); return false; } if (typeof optionsOrLogLevel === "number") { optionsOrLogLevel = { logLevel: optionsOrLogLevel }; } var oldLogger = getGlobal3("diag"); var newLogger = createLogLevelDiagLogger3((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel3.INFO, logger); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn("Current logger will be overwritten from " + stack); newLogger.warn("Current logger will overwrite one already registered from " + stack); } return registerGlobal3("diag", newLogger, self, true); }; self.setLogger = setLogger; self.disable = function() { unregisterGlobal3(API_NAME5, self); }; self.createComponentLogger = function(options) { return new DiagComponentLogger3(options); }; self.verbose = _logProxy("verbose"); self.debug = _logProxy("debug"); self.info = _logProxy("info"); self.warn = _logProxy("warn"); self.error = _logProxy("error"); } DiagAPI22.instance = function() { if (!this._instance) { this._instance = new DiagAPI22(); } return this._instance; }; return DiagAPI22; })() ); function createContextKey3(description) { return Symbol.for(description); } var BaseContext3 = ( /** @class */ /* @__PURE__ */ (function() { function BaseContext22(parentContext) { var self = this; self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); self.getValue = function(key) { return self._currentContext.get(key); }; self.setValue = function(key, value) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.set(key, value); return context2; }; self.deleteValue = function(key) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.delete(key); return context2; }; } return BaseContext22; })() ); var ROOT_CONTEXT3 = new BaseContext3(); var __read33 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray33 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var NoopContextManager3 = ( /** @class */ (function() { function NoopContextManager22() { } NoopContextManager22.prototype.active = function() { return ROOT_CONTEXT3; }; NoopContextManager22.prototype.with = function(_context, fn, thisArg) { var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return fn.call.apply(fn, __spreadArray33([thisArg], __read33(args), false)); }; NoopContextManager22.prototype.bind = function(_context, target) { return target; }; NoopContextManager22.prototype.enable = function() { return this; }; NoopContextManager22.prototype.disable = function() { return this; }; return NoopContextManager22; })() ); var __read43 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray43 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME23 = "context"; var NOOP_CONTEXT_MANAGER3 = new NoopContextManager3(); var ContextAPI3 = ( /** @class */ (function() { function ContextAPI22() { } ContextAPI22.getInstance = function() { if (!this._instance) { this._instance = new ContextAPI22(); } return this._instance; }; ContextAPI22.prototype.setGlobalContextManager = function(contextManager) { return registerGlobal3(API_NAME23, contextManager, DiagAPI3.instance()); }; ContextAPI22.prototype.active = function() { return this._getContextManager().active(); }; ContextAPI22.prototype.with = function(context2, fn, thisArg) { var _a212; var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return (_a212 = this._getContextManager()).with.apply(_a212, __spreadArray43([context2, fn, thisArg], __read43(args), false)); }; ContextAPI22.prototype.bind = function(context2, target) { return this._getContextManager().bind(context2, target); }; ContextAPI22.prototype._getContextManager = function() { return getGlobal3(API_NAME23) || NOOP_CONTEXT_MANAGER3; }; ContextAPI22.prototype.disable = function() { this._getContextManager().disable(); unregisterGlobal3(API_NAME23, DiagAPI3.instance()); }; return ContextAPI22; })() ); var TraceFlags3; (function(TraceFlags22) { TraceFlags22[TraceFlags22["NONE"] = 0] = "NONE"; TraceFlags22[TraceFlags22["SAMPLED"] = 1] = "SAMPLED"; })(TraceFlags3 || (TraceFlags3 = {})); var INVALID_SPANID3 = "0000000000000000"; var INVALID_TRACEID3 = "00000000000000000000000000000000"; var INVALID_SPAN_CONTEXT3 = { traceId: INVALID_TRACEID3, spanId: INVALID_SPANID3, traceFlags: TraceFlags3.NONE }; var NonRecordingSpan3 = ( /** @class */ (function() { function NonRecordingSpan22(_spanContext) { if (_spanContext === void 0) { _spanContext = INVALID_SPAN_CONTEXT3; } this._spanContext = _spanContext; } NonRecordingSpan22.prototype.spanContext = function() { return this._spanContext; }; NonRecordingSpan22.prototype.setAttribute = function(_key, _value) { return this; }; NonRecordingSpan22.prototype.setAttributes = function(_attributes) { return this; }; NonRecordingSpan22.prototype.addEvent = function(_name, _attributes) { return this; }; NonRecordingSpan22.prototype.addLink = function(_link) { return this; }; NonRecordingSpan22.prototype.addLinks = function(_links) { return this; }; NonRecordingSpan22.prototype.setStatus = function(_status) { return this; }; NonRecordingSpan22.prototype.updateName = function(_name) { return this; }; NonRecordingSpan22.prototype.end = function(_endTime) { }; NonRecordingSpan22.prototype.isRecording = function() { return false; }; NonRecordingSpan22.prototype.recordException = function(_exception, _time) { }; return NonRecordingSpan22; })() ); var SPAN_KEY3 = createContextKey3("OpenTelemetry Context Key SPAN"); function getSpan3(context2) { return context2.getValue(SPAN_KEY3) || void 0; } function getActiveSpan3() { return getSpan3(ContextAPI3.getInstance().active()); } function setSpan3(context2, span) { return context2.setValue(SPAN_KEY3, span); } function deleteSpan3(context2) { return context2.deleteValue(SPAN_KEY3); } function setSpanContext3(context2, spanContext) { return setSpan3(context2, new NonRecordingSpan3(spanContext)); } function getSpanContext3(context2) { var _a212; return (_a212 = getSpan3(context2)) === null || _a212 === void 0 ? void 0 : _a212.spanContext(); } var VALID_TRACEID_REGEX3 = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX3 = /^[0-9a-f]{16}$/i; function isValidTraceId3(traceId) { return VALID_TRACEID_REGEX3.test(traceId) && traceId !== INVALID_TRACEID3; } function isValidSpanId3(spanId) { return VALID_SPANID_REGEX3.test(spanId) && spanId !== INVALID_SPANID3; } function isSpanContextValid3(spanContext) { return isValidTraceId3(spanContext.traceId) && isValidSpanId3(spanContext.spanId); } function wrapSpanContext3(spanContext) { return new NonRecordingSpan3(spanContext); } var contextApi3 = ContextAPI3.getInstance(); var NoopTracer3 = ( /** @class */ (function() { function NoopTracer22() { } NoopTracer22.prototype.startSpan = function(name21, options, context2) { if (context2 === void 0) { context2 = contextApi3.active(); } var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan3(); } var parentFromContext = context2 && getSpanContext3(context2); if (isSpanContext3(parentFromContext) && isSpanContextValid3(parentFromContext)) { return new NonRecordingSpan3(parentFromContext); } else { return new NonRecordingSpan3(); } }; NoopTracer22.prototype.startActiveSpan = function(name21, arg2, arg3, arg4) { var opts; var ctx; var fn; if (arguments.length < 2) { return; } else if (arguments.length === 2) { fn = arg2; } else if (arguments.length === 3) { opts = arg2; fn = arg3; } else { opts = arg2; ctx = arg3; fn = arg4; } var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi3.active(); var span = this.startSpan(name21, opts, parentContext); var contextWithSpanSet = setSpan3(parentContext, span); return contextApi3.with(contextWithSpanSet, fn, void 0, span); }; return NoopTracer22; })() ); function isSpanContext3(spanContext) { return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; } var NOOP_TRACER3 = new NoopTracer3(); var ProxyTracer3 = ( /** @class */ (function() { function ProxyTracer22(_provider, name21, version3, options) { this._provider = _provider; this.name = name21; this.version = version3; this.options = options; } ProxyTracer22.prototype.startSpan = function(name21, options, context2) { return this._getTracer().startSpan(name21, options, context2); }; ProxyTracer22.prototype.startActiveSpan = function(_name, _options, _context, _fn) { var tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); }; ProxyTracer22.prototype._getTracer = function() { if (this._delegate) { return this._delegate; } var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER3; } this._delegate = tracer; return this._delegate; }; return ProxyTracer22; })() ); var NoopTracerProvider3 = ( /** @class */ (function() { function NoopTracerProvider22() { } NoopTracerProvider22.prototype.getTracer = function(_name, _version, _options) { return new NoopTracer3(); }; return NoopTracerProvider22; })() ); var NOOP_TRACER_PROVIDER3 = new NoopTracerProvider3(); var ProxyTracerProvider3 = ( /** @class */ (function() { function ProxyTracerProvider22() { } ProxyTracerProvider22.prototype.getTracer = function(name21, version3, options) { var _a212; return (_a212 = this.getDelegateTracer(name21, version3, options)) !== null && _a212 !== void 0 ? _a212 : new ProxyTracer3(this, name21, version3, options); }; ProxyTracerProvider22.prototype.getDelegate = function() { var _a212; return (_a212 = this._delegate) !== null && _a212 !== void 0 ? _a212 : NOOP_TRACER_PROVIDER3; }; ProxyTracerProvider22.prototype.setDelegate = function(delegate) { this._delegate = delegate; }; ProxyTracerProvider22.prototype.getDelegateTracer = function(name21, version3, options) { var _a212; return (_a212 = this._delegate) === null || _a212 === void 0 ? void 0 : _a212.getTracer(name21, version3, options); }; return ProxyTracerProvider22; })() ); var SpanStatusCode3; (function(SpanStatusCode22) { SpanStatusCode22[SpanStatusCode22["UNSET"] = 0] = "UNSET"; SpanStatusCode22[SpanStatusCode22["OK"] = 1] = "OK"; SpanStatusCode22[SpanStatusCode22["ERROR"] = 2] = "ERROR"; })(SpanStatusCode3 || (SpanStatusCode3 = {})); var context = ContextAPI3.getInstance(); var API_NAME33 = "trace"; var TraceAPI3 = ( /** @class */ (function() { function TraceAPI22() { this._proxyTracerProvider = new ProxyTracerProvider3(); this.wrapSpanContext = wrapSpanContext3; this.isSpanContextValid = isSpanContextValid3; this.deleteSpan = deleteSpan3; this.getSpan = getSpan3; this.getActiveSpan = getActiveSpan3; this.getSpanContext = getSpanContext3; this.setSpan = setSpan3; this.setSpanContext = setSpanContext3; } TraceAPI22.getInstance = function() { if (!this._instance) { this._instance = new TraceAPI22(); } return this._instance; }; TraceAPI22.prototype.setGlobalTracerProvider = function(provider) { var success3 = registerGlobal3(API_NAME33, this._proxyTracerProvider, DiagAPI3.instance()); if (success3) { this._proxyTracerProvider.setDelegate(provider); } return success3; }; TraceAPI22.prototype.getTracerProvider = function() { return getGlobal3(API_NAME33) || this._proxyTracerProvider; }; TraceAPI22.prototype.getTracer = function(name21, version3) { return this.getTracerProvider().getTracer(name21, version3); }; TraceAPI22.prototype.disable = function() { unregisterGlobal3(API_NAME33, DiagAPI3.instance()); this._proxyTracerProvider = new ProxyTracerProvider3(); }; return TraceAPI22; })() ); var trace3 = TraceAPI3.getInstance(); var __defProp4 = Object.defineProperty; var __export4 = (target, all) => { for (var name21 in all) __defProp4(target, name21, { get: all[name21], enumerable: true }); }; var name86 = "AI_InvalidArgumentError"; var marker96 = `vercel.ai.error.${name86}`; var symbol96 = Symbol.for(marker96); var _a96; var InvalidArgumentError23 = class extends AISDKError3 { constructor({ parameter, value, message }) { super({ name: name86, message: `Invalid argument for parameter ${parameter}: ${message}` }); this[_a96] = true; this.parameter = parameter; this.value = value; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker96); } }; _a96 = symbol96; var name823 = "AI_NoObjectGeneratedError"; var marker823 = `vercel.ai.error.${name823}`; var symbol823 = Symbol.for(marker823); var _a823; var NoObjectGeneratedError3 = class extends AISDKError3 { constructor({ message = "No object generated.", cause, text: text22, response, usage, finishReason }) { super({ name: name823, message, cause }); this[_a823] = true; this.text = text22; this.response = response; this.usage = usage; this.finishReason = finishReason; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker823); } }; _a823 = symbol823; var UnsupportedModelVersionError3 = class extends AISDKError3 { constructor(options) { super({ name: "AI_UnsupportedModelVersionError", message: `Unsupported model version ${options.version} for provider "${options.provider}" and model "${options.modelId}". AI SDK 5 only supports models that implement specification version "v2".` }); this.version = options.version; this.provider = options.provider; this.modelId = options.modelId; } }; var name192 = "AI_RetryError"; var marker192 = `vercel.ai.error.${name192}`; var symbol192 = Symbol.for(marker192); var _a192; var RetryError3 = class extends AISDKError3 { constructor({ message, reason, errors }) { super({ name: name192, message }); this[_a192] = true; this.reason = reason; this.errors = errors; this.lastError = errors[errors.length - 1]; } static isInstance(error90) { return AISDKError3.hasMarker(error90, marker192); } }; _a192 = symbol192; function formatWarning({ warning, provider, model }) { const prefix = `AI SDK Warning (${provider} / ${model}):`; switch (warning.type) { case "unsupported": { let message = `${prefix} The feature "${warning.feature}" is not supported.`; if (warning.details) { message += ` ${warning.details}`; } return message; } case "compatibility": { let message = `${prefix} The feature "${warning.feature}" is used in a compatibility mode.`; if (warning.details) { message += ` ${warning.details}`; } return message; } case "other": { return `${prefix} ${warning.message}`; } default: { return `${prefix} ${JSON.stringify(warning, null, 2)}`; } } } var FIRST_WARNING_INFO_MESSAGE = "AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false."; var hasLoggedBefore = false; var logWarnings = (options) => { if (options.warnings.length === 0) { return; } const logger = globalThis.AI_SDK_LOG_WARNINGS; if (logger === false) { return; } if (typeof logger === "function") { logger(options); return; } if (!hasLoggedBefore) { hasLoggedBefore = true; console.info(FIRST_WARNING_INFO_MESSAGE); } for (const warning of options.warnings) { console.warn( formatWarning({ warning, provider: options.provider, model: options.model }) ); } }; function logV2CompatibilityWarning({ provider, modelId }) { logWarnings({ warnings: [ { type: "compatibility", feature: "specificationVersion", details: `Using v2 specification compatibility mode. Some features may not be available.` } ], provider, model: modelId }); } function asEmbeddingModelV3(model) { if (model.specificationVersion === "v3") { return model; } logV2CompatibilityWarning({ provider: model.provider, modelId: model.modelId }); return new Proxy(model, { get(target, prop) { if (prop === "specificationVersion") return "v3"; return target[prop]; } }); } function resolveEmbeddingModel2(model) { if (typeof model !== "string") { if (model.specificationVersion !== "v3" && model.specificationVersion !== "v2") { const unsupportedModel = model; throw new UnsupportedModelVersionError3({ version: unsupportedModel.specificationVersion, provider: unsupportedModel.provider, modelId: unsupportedModel.modelId }); } return asEmbeddingModelV3(model); } return getGlobalProvider2().embeddingModel(model); } function getGlobalProvider2() { var _a212; return (_a212 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a212 : gateway2; } function getTotalTimeoutMs(timeout) { if (timeout == null) { return void 0; } if (typeof timeout === "number") { return timeout; } return timeout.totalMs; } var VERSION33 = "6.0.177"; var dataContentSchema3 = external_exports3.union([ external_exports3.string(), external_exports3.instanceof(Uint8Array), external_exports3.instanceof(ArrayBuffer), external_exports3.custom( // Buffer might not be available in some environments such as CloudFlare: (value) => { var _a212, _b93; return (_b93 = (_a212 = globalThis.Buffer) == null ? void 0 : _a212.isBuffer(value)) != null ? _b93 : false; }, { message: "Must be a Buffer" } ) ]); var jsonValueSchema3 = external_exports3.lazy( () => external_exports3.union([ external_exports3.null(), external_exports3.string(), external_exports3.number(), external_exports3.boolean(), external_exports3.record(external_exports3.string(), jsonValueSchema3.optional()), external_exports3.array(jsonValueSchema3) ]) ); var providerMetadataSchema3 = external_exports3.record( external_exports3.string(), external_exports3.record(external_exports3.string(), jsonValueSchema3.optional()) ); var textPartSchema3 = external_exports3.object({ type: external_exports3.literal("text"), text: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }); var imagePartSchema3 = external_exports3.object({ type: external_exports3.literal("image"), image: external_exports3.union([dataContentSchema3, external_exports3.instanceof(URL)]), mediaType: external_exports3.string().optional(), providerOptions: providerMetadataSchema3.optional() }); var filePartSchema3 = external_exports3.object({ type: external_exports3.literal("file"), data: external_exports3.union([dataContentSchema3, external_exports3.instanceof(URL)]), filename: external_exports3.string().optional(), mediaType: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }); var reasoningPartSchema3 = external_exports3.object({ type: external_exports3.literal("reasoning"), text: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }); var toolCallPartSchema3 = external_exports3.object({ type: external_exports3.literal("tool-call"), toolCallId: external_exports3.string(), toolName: external_exports3.string(), input: external_exports3.unknown(), providerOptions: providerMetadataSchema3.optional(), providerExecuted: external_exports3.boolean().optional() }); var outputSchema2 = external_exports3.discriminatedUnion( "type", [ external_exports3.object({ type: external_exports3.literal("text"), value: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("json"), value: jsonValueSchema3, providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("execution-denied"), reason: external_exports3.string().optional(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("error-text"), value: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("error-json"), value: jsonValueSchema3, providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("content"), value: external_exports3.array( external_exports3.union([ external_exports3.object({ type: external_exports3.literal("text"), text: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("media"), data: external_exports3.string(), mediaType: external_exports3.string() }), external_exports3.object({ type: external_exports3.literal("file-data"), data: external_exports3.string(), mediaType: external_exports3.string(), filename: external_exports3.string().optional(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("file-url"), url: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("file-id"), fileId: external_exports3.union([external_exports3.string(), external_exports3.record(external_exports3.string(), external_exports3.string())]), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("image-data"), data: external_exports3.string(), mediaType: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("image-url"), url: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("image-file-id"), fileId: external_exports3.union([external_exports3.string(), external_exports3.record(external_exports3.string(), external_exports3.string())]), providerOptions: providerMetadataSchema3.optional() }), external_exports3.object({ type: external_exports3.literal("custom"), providerOptions: providerMetadataSchema3.optional() }) ]) ) }) ] ); var toolResultPartSchema3 = external_exports3.object({ type: external_exports3.literal("tool-result"), toolCallId: external_exports3.string(), toolName: external_exports3.string(), output: outputSchema2, providerOptions: providerMetadataSchema3.optional() }); var toolApprovalRequestSchema = external_exports3.object({ type: external_exports3.literal("tool-approval-request"), approvalId: external_exports3.string(), toolCallId: external_exports3.string() }); var toolApprovalResponseSchema = external_exports3.object({ type: external_exports3.literal("tool-approval-response"), approvalId: external_exports3.string(), approved: external_exports3.boolean(), reason: external_exports3.string().optional() }); var systemModelMessageSchema2 = external_exports3.object( { role: external_exports3.literal("system"), content: external_exports3.string(), providerOptions: providerMetadataSchema3.optional() } ); var userModelMessageSchema2 = external_exports3.object({ role: external_exports3.literal("user"), content: external_exports3.union([ external_exports3.string(), external_exports3.array(external_exports3.union([textPartSchema3, imagePartSchema3, filePartSchema3])) ]), providerOptions: providerMetadataSchema3.optional() }); var assistantModelMessageSchema2 = external_exports3.object({ role: external_exports3.literal("assistant"), content: external_exports3.union([ external_exports3.string(), external_exports3.array( external_exports3.union([ textPartSchema3, filePartSchema3, reasoningPartSchema3, toolCallPartSchema3, toolResultPartSchema3, toolApprovalRequestSchema ]) ) ]), providerOptions: providerMetadataSchema3.optional() }); var toolModelMessageSchema2 = external_exports3.object({ role: external_exports3.literal("tool"), content: external_exports3.array(external_exports3.union([toolResultPartSchema3, toolApprovalResponseSchema])), providerOptions: providerMetadataSchema3.optional() }); external_exports3.union([ systemModelMessageSchema2, userModelMessageSchema2, assistantModelMessageSchema2, toolModelMessageSchema2 ]); function assembleOperationName3({ operationId, telemetry }) { return { // standardized operation and resource name: "operation.name": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`, "resource.name": telemetry == null ? void 0 : telemetry.functionId, // detailed, AI SDK specific data: "ai.operationId": operationId, "ai.telemetry.functionId": telemetry == null ? void 0 : telemetry.functionId }; } function getBaseTelemetryAttributes3({ model, settings, telemetry, headers }) { var _a212; return { "ai.model.provider": model.provider, "ai.model.id": model.modelId, // settings: ...Object.entries(settings).reduce((attributes, [key, value]) => { if (key === "timeout") { const totalTimeoutMs = getTotalTimeoutMs( value ); if (totalTimeoutMs != null) { attributes[`ai.settings.${key}`] = totalTimeoutMs; } } else { attributes[`ai.settings.${key}`] = value; } return attributes; }, {}), // add metadata as attributes: ...Object.entries((_a212 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a212 : {}).reduce( (attributes, [key, value]) => { attributes[`ai.telemetry.metadata.${key}`] = value; return attributes; }, {} ), // request headers ...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => { if (value !== void 0) { attributes[`ai.request.headers.${key}`] = value; } return attributes; }, {}) }; } var noopTracer3 = { startSpan() { return noopSpan3; }, startActiveSpan(name21, arg1, arg2, arg3) { if (typeof arg1 === "function") { return arg1(noopSpan3); } if (typeof arg2 === "function") { return arg2(noopSpan3); } if (typeof arg3 === "function") { return arg3(noopSpan3); } } }; var noopSpan3 = { spanContext() { return noopSpanContext3; }, setAttribute() { return this; }, setAttributes() { return this; }, addEvent() { return this; }, addLink() { return this; }, addLinks() { return this; }, setStatus() { return this; }, updateName() { return this; }, end() { return this; }, isRecording() { return false; }, recordException() { return this; } }; var noopSpanContext3 = { traceId: "", spanId: "", traceFlags: 0 }; function getTracer3({ isEnabled = false, tracer } = {}) { if (!isEnabled) { return noopTracer3; } if (tracer) { return tracer; } return trace3.getTracer("ai"); } async function recordSpan3({ name: name21, tracer, attributes, fn, endWhenDone = true }) { return tracer.startActiveSpan( name21, { attributes: await attributes }, async (span) => { const ctx = context.active(); try { const result = await context.with(ctx, () => fn(span)); if (endWhenDone) { span.end(); } return result; } catch (error90) { try { recordErrorOnSpan3(span, error90); } finally { span.end(); } throw error90; } } ); } function recordErrorOnSpan3(span, error90) { if (error90 instanceof Error) { span.recordException({ name: error90.name, message: error90.message, stack: error90.stack }); span.setStatus({ code: SpanStatusCode3.ERROR, message: error90.message }); } else { span.setStatus({ code: SpanStatusCode3.ERROR }); } } async function selectTelemetryAttributes3({ telemetry, attributes }) { if ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) { return {}; } const resultAttributes = {}; for (const [key, value] of Object.entries(attributes)) { if (value == null) { continue; } if (typeof value === "object" && "input" in value && typeof value.input === "function") { if ((telemetry == null ? void 0 : telemetry.recordInputs) === false) { continue; } const result = await value.input(); if (result != null) { resultAttributes[key] = result; } continue; } if (typeof value === "object" && "output" in value && typeof value.output === "function") { if ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) { continue; } const result = await value.output(); if (result != null) { resultAttributes[key] = result; } continue; } resultAttributes[key] = value; } return resultAttributes; } function getRetryDelayInMs2({ error: error90, exponentialBackoffDelay }) { const headers = error90.responseHeaders; if (!headers) return exponentialBackoffDelay; let ms; const retryAfterMs = headers["retry-after-ms"]; if (retryAfterMs) { const timeoutMs = parseFloat(retryAfterMs); if (!Number.isNaN(timeoutMs)) { ms = timeoutMs; } } const retryAfter = headers["retry-after"]; if (retryAfter && ms === void 0) { const timeoutSeconds = parseFloat(retryAfter); if (!Number.isNaN(timeoutSeconds)) { ms = timeoutSeconds * 1e3; } else { ms = Date.parse(retryAfter) - Date.now(); } } if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) { return ms; } return exponentialBackoffDelay; } var retryWithExponentialBackoffRespectingRetryHeaders2 = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal } = {}) => async (f) => _retryWithExponentialBackoff3(f, { maxRetries, delayInMs: initialDelayInMs, backoffFactor, abortSignal }); async function _retryWithExponentialBackoff3(f, { maxRetries, delayInMs, backoffFactor, abortSignal }, errors = []) { try { return await f(); } catch (error90) { if (isAbortError3(error90)) { throw error90; } if (maxRetries === 0) { throw error90; } const errorMessage = getErrorMessage23(error90); const newErrors = [...errors, error90]; const tryNumber = newErrors.length; if (tryNumber > maxRetries) { throw new RetryError3({ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`, reason: "maxRetriesExceeded", errors: newErrors }); } if (error90 instanceof Error && APICallError3.isInstance(error90) && error90.isRetryable === true && tryNumber <= maxRetries) { await delay3( getRetryDelayInMs2({ error: error90, exponentialBackoffDelay: delayInMs }), { abortSignal } ); return _retryWithExponentialBackoff3( f, { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor, abortSignal }, newErrors ); } if (tryNumber === 1) { throw error90; } throw new RetryError3({ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`, reason: "errorNotRetryable", errors: newErrors }); } } function prepareRetries3({ maxRetries, abortSignal }) { if (maxRetries != null) { if (!Number.isInteger(maxRetries)) { throw new InvalidArgumentError23({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be an integer" }); } if (maxRetries < 0) { throw new InvalidArgumentError23({ parameter: "maxRetries", value: maxRetries, message: "maxRetries must be >= 0" }); } } const maxRetriesResult = maxRetries != null ? maxRetries : 2; return { maxRetries: maxRetriesResult, retry: retryWithExponentialBackoffRespectingRetryHeaders2({ maxRetries: maxRetriesResult, abortSignal }) }; } var output_exports3 = {}; __export4(output_exports3, { array: () => array3, choice: () => choice, json: () => json3, object: () => object5, text: () => text3 }); function fixJson3(input) { const stack = ["ROOT"]; let lastValidIndex = -1; let literalStart = null; function processValueStart(char, i, swapState) { { switch (char) { case '"': { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_STRING"); break; } case "f": case "t": case "n": { lastValidIndex = i; literalStart = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_LITERAL"); break; } case "-": { stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "{": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_OBJECT_START"); break; } case "[": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_ARRAY_START"); break; } } } } function processAfterObjectValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_COMMA"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } } function processAfterArrayValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } } } for (let i = 0; i < input.length; i++) { const char = input[i]; const currentState = stack[stack.length - 1]; switch (currentState) { case "ROOT": processValueStart(char, i, "FINISH"); break; case "INSIDE_OBJECT_START": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } break; } case "INSIDE_OBJECT_AFTER_COMMA": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } } break; } case "INSIDE_OBJECT_KEY": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_KEY"); break; } } break; } case "INSIDE_OBJECT_AFTER_KEY": { switch (char) { case ":": { stack.pop(); stack.push("INSIDE_OBJECT_BEFORE_VALUE"); break; } } break; } case "INSIDE_OBJECT_BEFORE_VALUE": { processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE"); break; } case "INSIDE_OBJECT_AFTER_VALUE": { processAfterObjectValue(char, i); break; } case "INSIDE_STRING": { switch (char) { case '"': { stack.pop(); lastValidIndex = i; break; } case "\\": { stack.push("INSIDE_STRING_ESCAPE"); break; } default: { lastValidIndex = i; } } break; } case "INSIDE_ARRAY_START": { switch (char) { case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } } break; } case "INSIDE_ARRAY_AFTER_VALUE": { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; break; } } break; } case "INSIDE_ARRAY_AFTER_COMMA": { processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } case "INSIDE_STRING_ESCAPE": { stack.pop(); lastValidIndex = i; break; } case "INSIDE_NUMBER": { switch (char) { case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; break; } case "e": case "E": case "-": case ".": { break; } case ",": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "}": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "]": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } break; } default: { stack.pop(); break; } } break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, i + 1); if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } } else { lastValidIndex = i; } break; } } } let result = input.slice(0, lastValidIndex + 1); for (let i = stack.length - 1; i >= 0; i--) { const state = stack[i]; switch (state) { case "INSIDE_STRING": { result += '"'; break; } case "INSIDE_OBJECT_KEY": case "INSIDE_OBJECT_AFTER_KEY": case "INSIDE_OBJECT_AFTER_COMMA": case "INSIDE_OBJECT_START": case "INSIDE_OBJECT_BEFORE_VALUE": case "INSIDE_OBJECT_AFTER_VALUE": { result += "}"; break; } case "INSIDE_ARRAY_START": case "INSIDE_ARRAY_AFTER_COMMA": case "INSIDE_ARRAY_AFTER_VALUE": { result += "]"; break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, input.length); if ("true".startsWith(partialLiteral)) { result += "true".slice(partialLiteral.length); } else if ("false".startsWith(partialLiteral)) { result += "false".slice(partialLiteral.length); } else if ("null".startsWith(partialLiteral)) { result += "null".slice(partialLiteral.length); } } } } return result; } async function parsePartialJson3(jsonText) { if (jsonText === void 0) { return { value: void 0, state: "undefined-input" }; } let result = await safeParseJSON3({ text: jsonText }); if (result.success) { return { value: result.value, state: "successful-parse" }; } result = await safeParseJSON3({ text: fixJson3(jsonText) }); if (result.success) { return { value: result.value, state: "repaired-parse" }; } return { value: void 0, state: "failed-parse" }; } var text3 = () => ({ name: "text", responseFormat: Promise.resolve({ type: "text" }), async parseCompleteOutput({ text: text22 }) { return text22; }, async parsePartialOutput({ text: text22 }) { return { partial: text22 }; }, createElementStreamTransform() { return void 0; } }); var object5 = ({ schema: inputSchema, name: name21, description }) => { const schema = asSchema3(inputSchema); return { name: "object", responseFormat: resolve2(schema.jsonSchema).then((jsonSchema22) => ({ type: "json", schema: jsonSchema22, ...name21 != null && { name: name21 }, ...description != null && { description } })), async parseCompleteOutput({ text: text22 }, context2) { const parseResult = await safeParseJSON3({ text: text22 }); if (!parseResult.success) { throw new NoObjectGeneratedError3({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } const validationResult = await safeValidateTypes3({ value: parseResult.value, schema }); if (!validationResult.success) { throw new NoObjectGeneratedError3({ message: "No object generated: response did not match schema.", cause: validationResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } return validationResult.value; }, async parsePartialOutput({ text: text22 }) { const result = await parsePartialJson3(text22); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { return { // Note: currently no validation of partial results: partial: result.value }; } } }, createElementStreamTransform() { return void 0; } }; }; var array3 = ({ element: inputElementSchema, name: name21, description }) => { const elementSchema = asSchema3(inputElementSchema); return { name: "array", // JSON schema that describes an array of elements: responseFormat: resolve2(elementSchema.jsonSchema).then((jsonSchema22) => { const { $schema, ...itemSchema } = jsonSchema22; return { type: "json", schema: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { elements: { type: "array", items: itemSchema } }, required: ["elements"], additionalProperties: false }, ...name21 != null && { name: name21 }, ...description != null && { description } }; }), async parseCompleteOutput({ text: text22 }, context2) { const parseResult = await safeParseJSON3({ text: text22 }); if (!parseResult.success) { throw new NoObjectGeneratedError3({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } const outerValue = parseResult.value; if (outerValue == null || typeof outerValue !== "object" || !("elements" in outerValue) || !Array.isArray(outerValue.elements)) { throw new NoObjectGeneratedError3({ message: "No object generated: response did not match schema.", cause: new TypeValidationError3({ value: outerValue, cause: "response must be an object with an elements array" }), text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } for (const element of outerValue.elements) { const validationResult = await safeValidateTypes3({ value: element, schema: elementSchema }); if (!validationResult.success) { throw new NoObjectGeneratedError3({ message: "No object generated: response did not match schema.", cause: validationResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } } return outerValue.elements; }, async parsePartialOutput({ text: text22 }) { const result = await parsePartialJson3(text22); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { const outerValue = result.value; if (outerValue == null || typeof outerValue !== "object" || !("elements" in outerValue) || !Array.isArray(outerValue.elements)) { return void 0; } const rawElements = result.state === "repaired-parse" && outerValue.elements.length > 0 ? outerValue.elements.slice(0, -1) : outerValue.elements; const parsedElements = []; for (const rawElement of rawElements) { const validationResult = await safeValidateTypes3({ value: rawElement, schema: elementSchema }); if (validationResult.success) { parsedElements.push(validationResult.value); } } return { partial: parsedElements }; } } }, createElementStreamTransform() { let publishedElements = 0; return new TransformStream({ transform({ partialOutput }, controller) { if (partialOutput != null) { for (; publishedElements < partialOutput.length; publishedElements++) { controller.enqueue(partialOutput[publishedElements]); } } } }); } }; }; var choice = ({ options: choiceOptions, name: name21, description }) => { return { name: "choice", // JSON schema that describes an enumeration: responseFormat: Promise.resolve({ type: "json", schema: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { result: { type: "string", enum: choiceOptions } }, required: ["result"], additionalProperties: false }, ...name21 != null && { name: name21 }, ...description != null && { description } }), async parseCompleteOutput({ text: text22 }, context2) { const parseResult = await safeParseJSON3({ text: text22 }); if (!parseResult.success) { throw new NoObjectGeneratedError3({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } const outerValue = parseResult.value; if (outerValue == null || typeof outerValue !== "object" || !("result" in outerValue) || typeof outerValue.result !== "string" || !choiceOptions.includes(outerValue.result)) { throw new NoObjectGeneratedError3({ message: "No object generated: response did not match schema.", cause: new TypeValidationError3({ value: outerValue, cause: "response must be an object that contains a choice value." }), text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } return outerValue.result; }, async parsePartialOutput({ text: text22 }) { const result = await parsePartialJson3(text22); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { const outerValue = result.value; if (outerValue == null || typeof outerValue !== "object" || !("result" in outerValue) || typeof outerValue.result !== "string") { return void 0; } const potentialMatches = choiceOptions.filter( (choiceOption) => choiceOption.startsWith(outerValue.result) ); if (result.state === "successful-parse") { return potentialMatches.includes(outerValue.result) ? { partial: outerValue.result } : void 0; } else { return potentialMatches.length === 1 ? { partial: potentialMatches[0] } : void 0; } } } }, createElementStreamTransform() { return void 0; } }; }; var json3 = ({ name: name21, description } = {}) => { return { name: "json", responseFormat: Promise.resolve({ type: "json", ...name21 != null && { name: name21 }, ...description != null && { description } }), async parseCompleteOutput({ text: text22 }, context2) { const parseResult = await safeParseJSON3({ text: text22 }); if (!parseResult.success) { throw new NoObjectGeneratedError3({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } return parseResult.value; }, async parsePartialOutput({ text: text22 }) { const result = await parsePartialJson3(text22); switch (result.state) { case "failed-parse": case "undefined-input": { return void 0; } case "repaired-parse": case "successful-parse": { return result.value === void 0 ? void 0 : { partial: result.value }; } } }, createElementStreamTransform() { return void 0; } }; }; createIdGenerator3({ prefix: "aitxt", size: 24 }); external_exports3.record( external_exports3.string(), jsonValueSchema3.optional() ); createIdGenerator3({ prefix: "aitxt", size: 24 }); external_exports3.record( external_exports3.string(), jsonValueSchema3.optional() ); function splitArray3(array22, chunkSize) { if (chunkSize <= 0) { throw new Error("chunkSize must be greater than 0"); } const result = []; for (let i = 0; i < array22.length; i += chunkSize) { result.push(array22.slice(i, i + chunkSize)); } return result; } async function embedMany3({ model: modelArg, values, maxParallelCalls = Infinity, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry }) { const model = resolveEmbeddingModel2(modelArg); const { maxRetries, retry } = prepareRetries3({ maxRetries: maxRetriesArg, abortSignal }); const headersWithUserAgent = withUserAgentSuffix2( headers != null ? headers : {}, `ai/${VERSION33}` ); const baseTelemetryAttributes = getBaseTelemetryAttributes3({ model, telemetry, headers: headersWithUserAgent, settings: { maxRetries } }); const tracer = getTracer3(telemetry); return recordSpan3({ name: "ai.embedMany", attributes: selectTelemetryAttributes3({ telemetry, attributes: { ...assembleOperationName3({ operationId: "ai.embedMany", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => values.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (span) => { var _a212; const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([ model.maxEmbeddingsPerCall, model.supportsParallelCalls ]); if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) { const { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(() => { return recordSpan3({ name: "ai.embedMany.doEmbed", attributes: selectTelemetryAttributes3({ telemetry, attributes: { ...assembleOperationName3({ operationId: "ai.embedMany.doEmbed", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => values.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (doEmbedSpan) => { var _a2222; const modelResponse = await model.doEmbed({ values, abortSignal, headers: headersWithUserAgent, providerOptions }); const embeddings3 = modelResponse.embeddings; const usage2 = (_a2222 = modelResponse.usage) != null ? _a2222 : { tokens: NaN }; doEmbedSpan.setAttributes( await selectTelemetryAttributes3({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings3.map( (embedding) => JSON.stringify(embedding) ) }, "ai.usage.tokens": usage2.tokens } }) ); return { embeddings: embeddings3, usage: usage2, warnings: modelResponse.warnings, providerMetadata: modelResponse.providerMetadata, response: modelResponse.response }; } }); }); span.setAttributes( await selectTelemetryAttributes3({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": usage.tokens } }) ); logWarnings({ warnings: warnings2, provider: model.provider, model: model.modelId }); return new DefaultEmbedManyResult3({ values, embeddings: embeddings2, usage, warnings: warnings2, providerMetadata: providerMetadata2, responses: [response] }); } const valueChunks = splitArray3(values, maxEmbeddingsPerCall); const embeddings = []; const warnings = []; const responses = []; let tokens = 0; let providerMetadata; const parallelChunks = splitArray3( valueChunks, supportsParallelCalls ? maxParallelCalls : 1 ); for (const parallelChunk of parallelChunks) { const results = await Promise.all( parallelChunk.map((chunk) => { return retry(() => { return recordSpan3({ name: "ai.embedMany.doEmbed", attributes: selectTelemetryAttributes3({ telemetry, attributes: { ...assembleOperationName3({ operationId: "ai.embedMany.doEmbed", telemetry }), ...baseTelemetryAttributes, // specific settings that only make sense on the outer level: "ai.values": { input: () => chunk.map((value) => JSON.stringify(value)) } } }), tracer, fn: async (doEmbedSpan) => { var _a2222; const modelResponse = await model.doEmbed({ values: chunk, abortSignal, headers: headersWithUserAgent, providerOptions }); const embeddings2 = modelResponse.embeddings; const usage = (_a2222 = modelResponse.usage) != null ? _a2222 : { tokens: NaN }; doEmbedSpan.setAttributes( await selectTelemetryAttributes3({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings2.map( (embedding) => JSON.stringify(embedding) ) }, "ai.usage.tokens": usage.tokens } }) ); return { embeddings: embeddings2, usage, warnings: modelResponse.warnings, providerMetadata: modelResponse.providerMetadata, response: modelResponse.response }; } }); }); }) ); for (const result of results) { embeddings.push(...result.embeddings); warnings.push(...result.warnings); responses.push(result.response); tokens += result.usage.tokens; if (result.providerMetadata) { if (!providerMetadata) { providerMetadata = { ...result.providerMetadata }; } else { for (const [providerName, metadata] of Object.entries( result.providerMetadata )) { providerMetadata[providerName] = { ...(_a212 = providerMetadata[providerName]) != null ? _a212 : {}, ...metadata }; } } } } } span.setAttributes( await selectTelemetryAttributes3({ telemetry, attributes: { "ai.embeddings": { output: () => embeddings.map((embedding) => JSON.stringify(embedding)) }, "ai.usage.tokens": tokens } }) ); logWarnings({ warnings, provider: model.provider, model: model.modelId }); return new DefaultEmbedManyResult3({ values, embeddings, usage: { tokens }, warnings, providerMetadata, responses }); } }); } var DefaultEmbedManyResult3 = class { constructor(options) { this.values = options.values; this.embeddings = options.embeddings; this.usage = options.usage; this.warnings = options.warnings; this.providerMetadata = options.providerMetadata; this.responses = options.responses; } }; createIdGenerator3({ prefix: "aiobj", size: 24 }); createIdGenerator3({ prefix: "aiobj", size: 24 }); function getMessageParts(msg) { if (typeof msg.content === "string") return []; if (Array.isArray(msg.content)) return msg.content; const parts = msg.content?.parts; return Array.isArray(parts) ? parts : []; } function hasVisibleParts(msg) { if (typeof msg.content === "string") return msg.content.length > 0; const parts = getMessageParts(msg); if (parts.length === 0) return Boolean(msg.content?.content); return parts.some((p) => !p.type?.startsWith("data-")); } function parseRangeFormat(cursor) { if (cursor.includes(",")) { const parts = cursor.split(",").map((p) => p.trim()).filter(Boolean); if (parts.length >= 1) { const first = parts[0]; const last = parts[parts.length - 1]; const firstColon = first.indexOf(":"); const lastColon = last.indexOf(":"); return { startId: firstColon > 0 ? first.slice(0, firstColon) : first, endId: lastColon > 0 ? last.slice(lastColon + 1) : last }; } } const colonIndex = cursor.indexOf(":"); if (colonIndex > 0 && colonIndex < cursor.length - 1) { return { startId: cursor.slice(0, colonIndex), endId: cursor.slice(colonIndex + 1) }; } return null; } async function resolveCursorMessage(memory, cursor, access) { const normalized = cursor.trim(); if (!normalized) { throw new Error("Cursor is required"); } const rangeIds = parseRangeFormat(normalized); if (rangeIds) { return { hint: `The cursor "${cursor}" looks like a range. Use one of the individual message IDs as the cursor instead: start="${rangeIds.startId}" or end="${rangeIds.endId}".`, ...rangeIds }; } const memoryStore = await memory.getMemoryStore(); const result = await memoryStore.listMessagesById({ messageIds: [normalized] }); let message = result.messages.find((message2) => message2.id === normalized) ?? null; if (!message) { message = await resolveCursorMessageByRecall(memory, normalized, access); } if (!message) { throw new Error(`Could not resolve cursor message: ${cursor}`); } if (access?.resourceId && message.resourceId !== access.resourceId) { throw new Error(`Could not resolve cursor message: ${cursor}`); } if (access?.enforceThreadScope && access.threadScope && message.threadId !== access.threadScope) { throw new Error(`Could not resolve cursor message: ${cursor}`); } return message; } async function resolveCursorMessageByRecall(memory, cursor, access) { if (access?.enforceThreadScope && access.threadScope) { const result = await memory.recall({ threadId: access.threadScope, resourceId: access.resourceId, page: 0, perPage: false }); return result.messages.find((message) => message.id === cursor) ?? null; } if (!access?.resourceId) { return null; } const threads = await memory.listThreads({ page: 0, perPage: 100, orderBy: { field: "updatedAt", direction: "DESC" }, filter: { resourceId: access.resourceId } }); for (const thread of threads.threads) { const result = await memory.recall({ threadId: thread.id, resourceId: access.resourceId, page: 0, perPage: false }); const message = result.messages.find((message2) => message2.id === cursor); if (message) { return message; } } return null; } async function listThreadsForResource({ memory, resourceId, currentThreadId, page = 0, limit = 20, before, after }) { if (!resourceId) { throw new Error("Resource ID is required to list threads"); } const MAX_LIMIT = 50; const normalizedLimit = Math.min(Math.max(limit, 1), MAX_LIMIT); const hasDateFilter = !!(before || after); const beforeDate = before ? new Date(before) : null; const afterDate = after ? new Date(after) : null; const result = await memory.listThreads({ filter: { resourceId }, page: hasDateFilter ? 0 : page, perPage: hasDateFilter ? false : normalizedLimit, orderBy: { field: "updatedAt", direction: "DESC" } }); let threads = result.threads; if (beforeDate) { threads = threads.filter((t) => t.createdAt < beforeDate); } if (afterDate) { threads = threads.filter((t) => t.createdAt > afterDate); } let hasMore; if (hasDateFilter) { const offset = page * normalizedLimit; hasMore = offset + normalizedLimit < threads.length; threads = threads.slice(offset, offset + normalizedLimit); } else { hasMore = result.hasMore; } if (threads.length === 0) { return { threads: "No threads found matching the criteria.", count: 0, page, hasMore: false }; } const lines = []; for (const thread of threads) { const isCurrent = thread.id === currentThreadId; const title = thread.title || "(untitled)"; const updated = formatTimestamp(thread.updatedAt); const created = formatTimestamp(thread.createdAt); const marker21 = isCurrent ? " \u2190 current" : ""; lines.push(`- **${title}**${marker21}`); lines.push(` id: ${thread.id}`); lines.push(` updated: ${updated} | created: ${created}`); } return { threads: lines.join("\n"), count: threads.length, page, hasMore }; } async function searchMessagesForResource({ memory, resourceId, currentThreadId, query, topK = 10, maxTokens = DEFAULT_MAX_RESULT_TOKENS, before, after, threadScope }) { if (!memory.searchMessages) { return { results: "Search is not configured. Enable it with `retrieval: { vector: true }` and configure a vector store and embedder on your Memory instance.", count: 0 }; } const MAX_TOPK = 20; const clampedTopK = Math.min(Math.max(topK, 1), MAX_TOPK); const effectiveTopK = threadScope || before || after ? Math.max(clampedTopK * 3, clampedTopK + 10) : clampedTopK; const searchTopK = Math.min(MAX_TOPK, effectiveTopK); const beforeDate = before ? new Date(before) : void 0; const afterDate = after ? new Date(after) : void 0; const { results } = await memory.searchMessages({ query, resourceId, topK: searchTopK, filter: { ...threadScope ? { threadId: threadScope } : {}, ...afterDate ? { observedAfter: afterDate } : {}, ...beforeDate ? { observedBefore: beforeDate } : {} } }); if (results.length === 0) { return { results: "No matching messages found.", count: 0 }; } const threadIds = [...new Set(results.map((r) => r.threadId))]; const threadMap = /* @__PURE__ */ new Map(); if (memory.getThreadById) { await Promise.all( threadIds.map(async (id) => { const thread = await memory.getThreadById({ threadId: id }); if (thread) threadMap.set(id, thread); }) ); } const filteredMatches = results.filter((match) => { if (threadScope && match.threadId !== threadScope) return false; if (beforeDate && match.observedAt && match.observedAt >= beforeDate) return false; if (afterDate && match.observedAt && match.observedAt <= afterDate) return false; return true; }); if (filteredMatches.length === 0) { return { results: "No matching messages found.", count: 0 }; } const limitedMatches = filteredMatches.slice(0, clampedTopK); const sections = limitedMatches.map((match) => { const thread = threadMap.get(match.threadId); const title = thread?.title || "(untitled)"; const isCurrentThread = match.threadId === currentThreadId; const generationLabel = isCurrentThread ? "Current thread memory" : "Older memory from another thread"; const generationDetail = isCurrentThread ? "This result came from the current thread." : "This result came from an older memory generation in another thread."; const threadLine = `- thread: ${match.threadId}${thread ? ` (${title})` : ""}`; const sourceLine = match.range ? `- source: raw messages from ID ${match.range.split(":")[0] ?? "(unknown)"} through ID ${match.range.split(":")[1] ?? "(unknown)"}` : "- source: raw message range unavailable"; const updatedLine = thread ? `- thread updated: ${formatTimestamp(thread.updatedAt)}` : void 0; const groupLine = match.groupId ? `- observation group: ${match.groupId}` : void 0; const scoreLine = `- score: ${match.score.toFixed(2)}`; const body = (match.text || "").trim() || "_Observation text unavailable._"; return [ `### ${generationLabel}`, "", generationDetail, threadLine, sourceLine, updatedLine, groupLine, scoreLine, "", "```text", body, "```" ].filter(Boolean).join("\n"); }); const assembled = sections.join("\n\n"); const { text: limited } = truncateByTokens(assembled, maxTokens); return { results: limited, count: limitedMatches.length }; } var LOW_DETAIL_PART_TOKENS = 30; var AUTO_EXPAND_TEXT_TOKENS = 100; var AUTO_EXPAND_TOOL_TOKENS = 20; var HIGH_DETAIL_TOOL_RESULT_TOKENS = 4e3; var DEFAULT_MAX_RESULT_TOKENS = 2e3; function formatTimestamp(date9) { return date9.toISOString().replace("T", " ").replace(/\.\d{3}Z$/, "Z"); } function truncateByTokens(text42, maxTokens, hint) { if (chunk3ZV6GYQI_cjs.estimateTokenCount(text42) <= maxTokens) return { text: text42, wasTruncated: false }; const truncated = chunk3ZV6GYQI_cjs.truncateStringByTokens(text42, maxTokens); const suffix = hint ? ` [${hint} for more]` : ""; return { text: truncated + suffix, wasTruncated: true }; } function lowDetailPartLimit(type) { if (type === "text") return AUTO_EXPAND_TEXT_TOKENS; if (type === "tool-result" || type === "tool-call") return AUTO_EXPAND_TOOL_TOKENS; return LOW_DETAIL_PART_TOKENS; } function makePart(msg, partIndex, type, fullText, detail, toolName) { if (detail === "high") { return { messageId: msg.id, partIndex, role: msg.role, type, text: fullText, fullText, toolName }; } const hint = `recall cursor="${msg.id}" partIndex=${partIndex} detail="high"`; const { text: text42 } = truncateByTokens(fullText, lowDetailPartLimit(type), hint); return { messageId: msg.id, partIndex, role: msg.role, type, text: text42, fullText, toolName }; } function formatMessageParts(msg, detail) { const parts = []; if (typeof msg.content === "string") { parts.push(makePart(msg, 0, "text", msg.content, detail)); return parts; } const messageParts = getMessageParts(msg); if (messageParts.length > 0) { for (let i = 0; i < messageParts.length; i++) { const part = messageParts[i]; const partType = part.type; if (partType === "text") { const text42 = part.text; if (text42) { parts.push(makePart(msg, i, "text", text42, detail)); } } else if (partType === "tool-invocation") { const inv = part.toolInvocation; if (inv?.toolName) { const hasArgs = inv.args != null; if (inv.state !== "partial-call" && hasArgs) { const argsStr = detail === "low" ? "" : ` ${JSON.stringify(inv.args, null, 2)}`; const fullText = `[Tool Call: ${inv.toolName}]${argsStr}`; parts.push({ messageId: msg.id, partIndex: i, role: msg.role, type: "tool-call", text: fullText, fullText, toolName: inv.toolName }); } if (inv.state === "result") { const { value: resultValue } = chunk3ZV6GYQI_cjs.resolveToolResultValue( part, inv.result ); const resultStr = chunk3ZV6GYQI_cjs.formatToolResultForObserver(resultValue, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS }); const fullText = `[Tool Result: ${inv.toolName}] ${resultStr}`; parts.push(makePart(msg, i, "tool-result", fullText, detail, inv.toolName)); } } } else if (partType === "tool-call") { const toolName = part.toolName; if (toolName) { const rawArgs = part.input ?? part.args; const argsStr = detail === "low" || rawArgs == null ? "" : ` ${typeof rawArgs === "string" ? rawArgs : JSON.stringify(rawArgs, null, 2)}`; const fullText = `[Tool Call: ${toolName}]${argsStr}`; parts.push({ messageId: msg.id, partIndex: i, role: msg.role, type: "tool-call", text: fullText, fullText, toolName }); } } else if (partType === "tool-result") { const toolName = part.toolName; if (toolName) { const rawResult = part.output ?? part.result; const resultStr = chunk3ZV6GYQI_cjs.formatToolResultForObserver(rawResult, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS }); const fullText = `[Tool Result: ${toolName}] ${resultStr}`; parts.push(makePart(msg, i, "tool-result", fullText, detail, toolName)); } } else if (partType === "reasoning") { const reasoning = part.reasoning ?? part.text; if (reasoning) { parts.push(makePart(msg, i, "reasoning", reasoning, detail)); } } else if (partType === "image" || partType === "file") { const filename = part.filename; const label = filename ? `: ${filename}` : ""; const fullText = `[${partType === "image" ? "Image" : "File"}${label}]`; parts.push({ messageId: msg.id, partIndex: i, role: msg.role, type: partType, text: fullText, fullText }); } else if (partType?.startsWith("data-")) ; else if (partType) { const fullText = `[${partType}]`; parts.push({ messageId: msg.id, partIndex: i, role: msg.role, type: partType, text: fullText, fullText }); } } } else if (msg.content?.content) { parts.push(makePart(msg, 0, "text", msg.content.content, detail)); } return parts; } function buildRenderedText(parts, timestamps) { let currentMessageId = ""; const lines = []; for (const part of parts) { if (part.messageId !== currentMessageId) { currentMessageId = part.messageId; const ts = timestamps.get(part.messageId); const tsStr = ts ? ` (${formatTimestamp(ts)})` : ""; if (lines.length > 0) lines.push(""); lines.push(`**${part.role}${tsStr}** [${part.messageId}]:`); } const indexLabel = `[p${part.partIndex}]`; lines.push(` ${indexLabel} ${part.text}`); } return lines.join("\n"); } async function getNextVisibleMessage({ memory, threadId, resourceId, after }) { const result = await memory.recall({ threadId, resourceId, page: 0, perPage: 50, orderBy: { field: "createdAt", direction: "ASC" }, filter: { dateRange: { start: after, startExclusive: true } } }); return result.messages.find(hasVisibleParts) ?? null; } var MAX_EXPAND_USER_TEXT_TOKENS = 200; var MAX_EXPAND_OTHER_TOKENS = 50; function expandLimit(part) { if (part.role === "user" && part.type === "text") return MAX_EXPAND_USER_TEXT_TOKENS; return MAX_EXPAND_OTHER_TOKENS; } function expandPriority(part) { if (part.role === "user" && part.type === "text") return 0; if (part.type === "text" || part.type === "reasoning") return 1; if (part.type === "tool-result") return 2; if (part.type === "tool-call") return 3; return 4; } function renderFormattedParts(parts, timestamps, options) { const text42 = buildRenderedText(parts, timestamps); let totalTokens = chunk3ZV6GYQI_cjs.estimateTokenCount(text42); if (totalTokens > options.maxTokens) { const truncated = chunk3ZV6GYQI_cjs.truncateStringByTokens(text42, options.maxTokens); return { text: truncated, truncated: true, tokenOffset: totalTokens - options.maxTokens }; } const truncatedIndices = parts.map((p, i) => ({ part: p, index: i })).filter(({ part }) => part.text !== part.fullText).sort((a, b) => expandPriority(a.part) - expandPriority(b.part)); if (truncatedIndices.length === 0) { return { text: text42, truncated: false, tokenOffset: 0 }; } let remaining = options.maxTokens - totalTokens; for (const { part, index } of truncatedIndices) { if (remaining <= 0) break; const maxTokens = expandLimit(part); const fullTokens = chunk3ZV6GYQI_cjs.estimateTokenCount(part.fullText); const currentTokens = chunk3ZV6GYQI_cjs.estimateTokenCount(part.text); const targetTokens = Math.min(fullTokens, maxTokens); const delta = targetTokens - currentTokens; if (delta <= 0) continue; if (delta <= remaining && targetTokens >= fullTokens) { parts[index] = { ...part, text: part.fullText }; remaining -= delta; } else { const expandedLimit = Math.min(currentTokens + remaining, maxTokens); const hint = `recall cursor="${part.messageId}" partIndex=${part.partIndex} detail="high"`; const { text: expanded2 } = truncateByTokens(part.fullText, expandedLimit, hint); const expandedDelta = chunk3ZV6GYQI_cjs.estimateTokenCount(expanded2) - currentTokens; parts[index] = { ...part, text: expanded2 }; remaining -= expandedDelta; } } const expanded = buildRenderedText(parts, timestamps); const expandedTokens = chunk3ZV6GYQI_cjs.estimateTokenCount(expanded); if (expandedTokens <= options.maxTokens) { return { text: expanded, truncated: false, tokenOffset: 0 }; } const hardTruncated = chunk3ZV6GYQI_cjs.truncateStringByTokens(expanded, options.maxTokens); return { text: hardTruncated, truncated: true, tokenOffset: expandedTokens - options.maxTokens }; } async function recallPart({ memory, threadId, resourceId, cursor, partIndex, threadScope, maxTokens = DEFAULT_MAX_RESULT_TOKENS }) { if (!memory || typeof memory.getMemoryStore !== "function") { throw new Error("Memory instance is required for recall"); } if (!threadId) { throw new Error("Thread ID is required for recall"); } const resolved = await resolveCursorMessage(memory, cursor, { resourceId, threadScope, enforceThreadScope: false }); if ("hint" in resolved) { throw new Error(resolved.hint); } const allParts = formatMessageParts(resolved, "high"); if (allParts.length === 0) { throw new Error( `Message ${cursor} has no visible content (it may be an internal system message). Try a neighboring message ID instead.` ); } const target = [...allParts].reverse().find((p) => p.partIndex === partIndex); if (!target) { const availableIndices = allParts.map((p) => p.partIndex).join(", "); const highestVisiblePartIndex = Math.max(...allParts.map((p) => p.partIndex)); if (partIndex > highestVisiblePartIndex) { const nextMessage = await getNextVisibleMessage({ memory, threadId, resourceId, after: resolved.createdAt }); if (nextMessage) { const nextParts = formatMessageParts(nextMessage, "high"); const firstNextPart = nextParts[0]; if (firstNextPart) { const fallbackNote = `Part index ${partIndex} not found in message ${cursor}; showing partIndex ${firstNextPart.partIndex} from next message ${firstNextPart.messageId}. `; const fallbackText = `${fallbackNote}${firstNextPart.text}`; const truncatedText2 = chunk3ZV6GYQI_cjs.truncateStringByTokens(fallbackText, maxTokens); const wasTruncated2 = truncatedText2 !== fallbackText; return { text: truncatedText2, messageId: firstNextPart.messageId, partIndex: firstNextPart.partIndex, role: firstNextPart.role, type: firstNextPart.type, truncated: wasTruncated2 }; } } } throw new Error(`Part index ${partIndex} not found in message ${cursor}. Available indices: ${availableIndices}`); } const truncatedText = chunk3ZV6GYQI_cjs.truncateStringByTokens(target.text, maxTokens); const wasTruncated = truncatedText !== target.text; return { text: truncatedText, messageId: target.messageId, partIndex: target.partIndex, role: target.role, type: target.type, truncated: wasTruncated }; } async function recallMessages({ memory, threadId, resourceId, cursor, page = 1, limit = 20, detail = "low", partType, toolName, threadScope, maxTokens = DEFAULT_MAX_RESULT_TOKENS }) { if (!memory) { throw new Error("Memory instance is required for recall"); } if (!threadId) { throw new Error("Thread ID is required for recall"); } if (typeof memory.getMemoryStore !== "function") { throw new Error("recall requires a Memory instance with storage access"); } const MAX_PAGE = 50; const MAX_LIMIT = 20; const rawPage = page === 0 ? 1 : page; const normalizedPage = Math.max(Math.min(rawPage, MAX_PAGE), -MAX_PAGE); const normalizedLimit = Math.min(limit, MAX_LIMIT); const resolved = await resolveCursorMessage(memory, cursor, { resourceId, threadScope, enforceThreadScope: false }); if ("hint" in resolved) { return { messages: resolved.hint, count: 0, cursor, page: normalizedPage, limit: normalizedLimit, detail, hasNextPage: false, hasPrevPage: false, truncated: false, tokenOffset: 0 }; } const anchor = resolved; const crossThreadId = anchor.threadId && anchor.threadId !== threadId ? anchor.threadId : void 0; if (crossThreadId && threadScope) { return { messages: `Cursor does not belong to the active thread. Expected thread "${threadId}" but cursor "${cursor}" belongs to "${anchor.threadId}". Pass threadId="${anchor.threadId}" to browse that thread, or omit threadId and use this cursor directly in resource scope.`, count: 0, cursor, page: normalizedPage, limit: normalizedLimit, detail, hasNextPage: false, hasPrevPage: false, truncated: false, tokenOffset: 0 }; } const resolvedThreadId = crossThreadId ?? threadId; if (!resolvedThreadId) { throw new Error("Thread ID is required for recall"); } const isForward = normalizedPage > 0; const pageIndex = Math.max(Math.abs(normalizedPage), 1) - 1; const skip = pageIndex * normalizedLimit; const fetchCount = skip + normalizedLimit + 1; const result = await memory.recall({ threadId: resolvedThreadId, resourceId, page: 0, perPage: fetchCount, orderBy: { field: "createdAt", direction: isForward ? "ASC" : "DESC" }, filter: { dateRange: isForward ? { start: anchor.createdAt, startExclusive: true } : { end: anchor.createdAt, endExclusive: true } } }); const visibleMessages = result.messages.filter(hasVisibleParts); const total = visibleMessages.length; const hasMore = total > skip + normalizedLimit; let messages; if (isForward) { messages = visibleMessages.slice(skip, skip + normalizedLimit); } else { const endIdx = Math.max(total - skip, 0); const startIdx = Math.max(endIdx - normalizedLimit, 0); messages = visibleMessages.slice(startIdx, endIdx); } const hasNextPage = isForward ? hasMore : pageIndex > 0; const hasPrevPage = isForward ? pageIndex > 0 : hasMore; let allParts = []; const timestamps = /* @__PURE__ */ new Map(); for (const msg of messages) { timestamps.set(msg.id, msg.createdAt); allParts.push(...formatMessageParts(msg, detail)); } if (toolName) { allParts = allParts.filter((p) => (p.type === "tool-call" || p.type === "tool-result") && p.toolName === toolName); } if (partType) { allParts = allParts.filter((p) => p.type === partType); } if (detail === "high" && allParts.length > 0) { const firstPart = allParts[0]; const sameMsgParts = allParts.filter((p) => p.messageId === firstPart.messageId); const otherMsgParts = allParts.filter((p) => p.messageId !== firstPart.messageId); const rendered2 = renderFormattedParts([firstPart], timestamps, { maxTokens }); let text42 = rendered2.text; const hints = []; if (sameMsgParts.length > 1) { const nextPart = sameMsgParts[1]; hints.push(`next part: partIndex=${nextPart.partIndex} on cursor="${firstPart.messageId}"`); } if (otherMsgParts.length > 0) { const next = otherMsgParts[0]; hints.push(`next message: partIndex=${next.partIndex} on cursor="${next.messageId}"`); } else if (hasNextPage) { hints.push(`more messages available on page ${normalizedPage + 1}`); } if (hints.length > 0) { text42 += ` High detail returns 1 part at a time. To continue: ${hints.join(", or ")}.`; } return { messages: text42, count: 1, cursor, page: normalizedPage, limit: normalizedLimit, detail, hasNextPage: otherMsgParts.length > 0 || hasNextPage, hasPrevPage, truncated: rendered2.truncated, tokenOffset: rendered2.tokenOffset }; } const rendered = renderFormattedParts(allParts, timestamps, { maxTokens }); const emptyMessage = allParts.length === 0 ? partType || toolName ? "(no message parts matched the current filters)" : "(no visible message parts found for this page)" : "(no messages found)"; return { messages: rendered.text || emptyMessage, count: messages.length, cursor, page: normalizedPage, limit: normalizedLimit, detail, hasNextPage, hasPrevPage, truncated: rendered.truncated, tokenOffset: rendered.tokenOffset }; } async function recallThreadFromStart({ memory, threadId, resourceId, page = 1, limit = 20, detail = "low", partType, toolName, anchor = "start", maxTokens = DEFAULT_MAX_RESULT_TOKENS }) { if (!memory) { throw new Error("Memory instance is required for recall"); } if (!threadId) { throw new Error("Thread ID is required for recall"); } if (resourceId && memory.getThreadById) { const thread = await memory.getThreadById({ threadId }); if (!thread || thread.resourceId !== resourceId) { throw new Error("Thread not found"); } } const MAX_PAGE = 50; const MAX_LIMIT = 20; const normalizedPage = Math.max(Math.min(page, MAX_PAGE), 1); const normalizedLimit = Math.min(Math.max(limit, 1), MAX_LIMIT); const pageIndex = normalizedPage - 1; const fetchCount = pageIndex * normalizedLimit + normalizedLimit + 1; const result = await memory.recall({ threadId, resourceId, page: 0, perPage: fetchCount, orderBy: { field: "createdAt", direction: anchor === "end" ? "DESC" : "ASC" } }); const visibleMessages = anchor === "end" ? result.messages.slice(0, fetchCount).filter(hasVisibleParts).reverse() : result.messages.slice(0, fetchCount).filter(hasVisibleParts); const skip = pageIndex * normalizedLimit; const messages = visibleMessages.slice(skip, skip + normalizedLimit); const hasExtraMessage = visibleMessages.length > skip + messages.length; const hasNextPage = messages.length > 0 ? anchor === "end" ? pageIndex > 0 : hasExtraMessage : false; const hasPrevPage = messages.length > 0 ? anchor === "end" ? hasExtraMessage : pageIndex > 0 : pageIndex > 0; let allParts = []; const timestamps = /* @__PURE__ */ new Map(); for (const msg of messages) { timestamps.set(msg.id, msg.createdAt); allParts.push(...formatMessageParts(msg, detail)); } if (toolName) { allParts = allParts.filter((p) => (p.type === "tool-call" || p.type === "tool-result") && p.toolName === toolName); } if (partType) { allParts = allParts.filter((p) => p.type === partType); } const rendered = renderFormattedParts(allParts, timestamps, { maxTokens }); const emptyMessage = messages.length === 0 ? pageIndex > 0 ? `(no messages found on page ${normalizedPage} for this thread)` : "(no messages in this thread)" : partType || toolName ? "(no message parts matched the current filters)" : "(no messages found)"; return { messages: rendered.text || emptyMessage, count: messages.length, cursor: messages[0]?.id || "", page: normalizedPage, limit: normalizedLimit, detail, hasNextPage, hasPrevPage, truncated: rendered.truncated, tokenOffset: rendered.tokenOffset }; } var recallTool = (_memoryConfig, options) => { const retrievalScope = options?.retrievalScope ?? "thread"; const isResourceScope = retrievalScope === "resource"; const description = isResourceScope ? 'Browse conversation history. Use mode="threads" to list all threads for the current user. Use mode="messages" (default) to browse messages in the current thread or pass threadId to browse another thread in the active resource. When mode="messages" has no cursor or threadId, it defaults to the current thread and says so at the top of the result. If you pass only a cursor, it must belong to the current thread. Use mode="search" to find messages by content across all threads.' : `Browse conversation history in the current thread. Use mode="messages" (default) to page through messages near a cursor. Use mode="search" to find messages by content in this thread. Use mode="threads" to get the current thread's ID and title.`; return tools.createTool({ id: "recall", description, inputSchema: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { ...isResourceScope ? { mode: { type: "string", enum: ["messages", "threads", "search"], description: 'What to retrieve. "messages" (default) pages through message history. "threads" lists all threads for the current user. "search" finds messages by semantic similarity across all threads.' }, threadId: { type: "string", minLength: 1, description: 'Browse a different thread, or "current" for the active thread. Use mode="threads" first to discover thread IDs.' }, before: { type: "string", description: 'For mode="threads": only show threads created before this date. ISO 8601 or natural date string (e.g. "2026-03-15", "2026-03-10T00:00:00Z").' }, after: { type: "string", description: 'For mode="threads": only show threads created after this date. ISO 8601 or natural date string (e.g. "2026-03-01", "2026-03-10T00:00:00Z").' } } : { mode: { type: "string", enum: ["messages", "threads", "search"], description: 'What to retrieve. "messages" (default) pages through message history. "threads" returns info about the current thread. "search" finds messages by semantic similarity in this thread.' } }, query: { type: "string", minLength: 1, description: 'Search query for mode="search". Finds messages semantically similar to this text.' }, cursor: { type: "string", minLength: 1, description: 'A message ID to use as the pagination cursor. For mode="messages", omit both cursor and threadId to browse the current thread. If only cursor is provided, it must belong to the current thread. Extract it from the start or end of an observation group range.' }, anchor: { type: "string", enum: ["start", "end"], description: 'For mode="messages" without a cursor, page from the start (oldest-first) or end (newest-first) of the thread. Defaults to "start".' }, page: { type: "integer", minimum: -50, maximum: 50, description: "Pagination offset. For messages: positive pages move forward from cursor, negative move backward. For threads: page number (0-indexed). 0 is treated as 1 for messages." }, limit: { type: "integer", minimum: 1, maximum: 20, description: "Maximum number of items to return per page. Defaults to 20." }, detail: { type: "string", enum: ["low", "high"], description: 'Detail level for messages. "low" (default) returns truncated text and tool names. "high" returns full content with tool args/results.' }, partType: { type: "string", enum: ["text", "tool-call", "tool-result", "reasoning", "image", "file"], description: 'Filter results to only include parts of this type. Only applies to mode="messages".' }, toolName: { type: "string", minLength: 1, description: 'Filter results to only include tool-call and tool-result parts matching this tool name. Only applies to mode="messages".' }, partIndex: { type: "integer", minimum: 0, description: "Fetch a single part from the cursor message by its positional index. When provided, returns only that part at high detail. Indices are shown as [p0], [p1], etc. in recall results." } } }, execute: async (inputData, context2) => { const { mode, query, cursor, threadId: explicitThreadId, anchor, page, limit, detail, partType, toolName, partIndex, before, after } = inputData; const memory = context2?.memory; const currentThreadId = context2?.agent?.threadId; const resourceId = context2?.agent?.resourceId; const resolvedExplicitThreadId = explicitThreadId === "current" ? currentThreadId : explicitThreadId; if (!memory) { throw new Error("Memory instance is required for recall"); } if (explicitThreadId === "current" && !currentThreadId) { throw new Error("Could not resolve current thread."); } if (mode === "search") { if (!query) { throw new Error('query is required for mode="search"'); } if (!resourceId) { throw new Error("Resource ID is required for recall"); } return searchMessagesForResource({ memory, resourceId, currentThreadId: currentThreadId || void 0, query, topK: limit ?? 10, before, after, threadScope: !isResourceScope ? currentThreadId || void 0 : resolvedExplicitThreadId || void 0 }); } if (mode === "threads") { const requestedCurrentThread = explicitThreadId === "current"; if (!isResourceScope || requestedCurrentThread) { if (!currentThreadId || !memory.getThreadById) { return { error: "Could not resolve current thread." }; } const thread = await memory.getThreadById({ threadId: currentThreadId }); if (!thread) { return { error: "Could not resolve current thread." }; } if (isResourceScope && resourceId && thread.resourceId !== resourceId) { throw new Error("Thread does not belong to the active resource"); } return { threads: `- **${thread.title || "(untitled)"}** \u2190 current id: ${thread.id} updated: ${formatTimestamp(thread.updatedAt)} | created: ${formatTimestamp(thread.createdAt)}`, count: 1, page: 0, hasMore: false }; } if (!resourceId) { throw new Error("Resource ID is required for recall"); } return listThreadsForResource({ memory, resourceId, currentThreadId: currentThreadId || "", page: page ?? 0, limit: limit ?? 20, before, after }); } const usedDefaultThreadId = isResourceScope && !explicitThreadId && !cursor && Boolean(currentThreadId); const defaultThreadNote = usedDefaultThreadId ? `threadId wasn't passed so used default ${currentThreadId}. ` : ""; const effectiveThreadId = explicitThreadId || (usedDefaultThreadId ? "current" : void 0); const resolvedThreadId = effectiveThreadId === "current" ? currentThreadId : effectiveThreadId; const hasExplicitThreadId = typeof resolvedThreadId === "string" && resolvedThreadId.length > 0; const hasCursor = typeof cursor === "string" && cursor.length > 0; if (!hasExplicitThreadId && !hasCursor) { throw new Error('Either cursor or threadId is required for mode="messages"'); } let targetThreadId; let threadScope; if (!isResourceScope) { targetThreadId = currentThreadId; threadScope = currentThreadId || void 0; } else if (hasExplicitThreadId) { if (!resourceId) { throw new Error("Resource ID is required for recall"); } if (!memory.getThreadById) { throw new Error("Memory instance cannot verify thread access for recall"); } const thread = await memory.getThreadById({ threadId: resolvedThreadId }); if (!thread || thread.resourceId !== resourceId) { throw new Error("Thread does not belong to the active resource"); } targetThreadId = thread.id; threadScope = thread.id; } else { targetThreadId = currentThreadId; threadScope = currentThreadId || void 0; } if (hasCursor && !hasExplicitThreadId && !currentThreadId) { if (!isResourceScope) { throw new Error("Current thread is required when browsing by cursor"); } const resolved = await resolveCursorMessage(memory, cursor, { resourceId }); if ("hint" in resolved) { return { messages: resolved.hint, count: 0, cursor, page: page ?? 1, limit: Math.min(limit ?? 20, 20), detail: detail ?? "low", hasNextPage: false, hasPrevPage: false, truncated: false, tokenOffset: 0 }; } targetThreadId = resolved.threadId; } if (!targetThreadId) { throw new Error("Thread ID is required for recall"); } if (!cursor) { const result = await recallThreadFromStart({ memory, threadId: targetThreadId, resourceId: isResourceScope ? resourceId : void 0, page: page ?? 1, limit: limit ?? 20, detail: detail ?? "low", partType, toolName, anchor: anchor ?? "start" }); if (defaultThreadNote) { return { ...result, messages: `${defaultThreadNote}${result.messages}` }; } return result; } if (partIndex !== void 0 && partIndex !== null) { return recallPart({ memory, threadId: targetThreadId, resourceId: isResourceScope ? resourceId : void 0, cursor, partIndex, threadScope }); } return recallMessages({ memory, threadId: targetThreadId, resourceId: isResourceScope ? resourceId : void 0, cursor, page, limit, detail: detail ?? "low", partType, toolName, threadScope }); } }); }; var UPDATE_WORKING_MEMORY_TOOL_NAME = "updateWorkingMemory"; var SET_WORKING_MEMORY_TOOL_NAME = "setWorkingMemory"; function deepMergeWorkingMemory(existing, update) { if (!update || typeof update !== "object" || Object.keys(update).length === 0) { return existing && typeof existing === "object" ? { ...existing } : {}; } if (!existing || typeof existing !== "object") { return update; } const result = { ...existing }; for (const key of Object.keys(update)) { const updateValue = update[key]; const existingValue = result[key]; if (updateValue === null) { delete result[key]; } else if (Array.isArray(updateValue)) { result[key] = updateValue; } else if (typeof updateValue === "object" && updateValue !== null && typeof existingValue === "object" && existingValue !== null && !Array.isArray(existingValue)) { result[key] = deepMergeWorkingMemory( existingValue, updateValue ); } else { result[key] = updateValue; } } return result; } function stripNullsFromOptional(value, schema) { if (Array.isArray(value)) { const itemSchema = schema.items ?? {}; return value.map((item) => stripNullsFromOptional(item, itemSchema)); } if (typeof value === "object" && value !== null) { const properties = schema.properties ?? {}; const required3 = schema.required ?? []; const result = {}; for (const [key, propertyValue] of Object.entries(value)) { if (propertyValue === null && !required3.includes(key)) { continue; } result[key] = stripNullsFromOptional(propertyValue, properties[key] ?? {}); } return result; } return value; } var updateWorkingMemoryTool = (memoryConfig) => { const schema$1 = memoryConfig?.workingMemory?.schema; let inputSchema = { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { memory: { type: "string", description: `The Markdown formatted working memory content to store. This MUST be a string. Never pass an object.` } }, required: ["memory"] }; if (schema$1) { const standardSchema2 = schema.isStandardSchemaWithJSON(schema$1) ? schema$1 : schema.toStandardSchema(schema$1); const jsonSchema42 = chunk3YQ7NWF6_cjs.standardSchemaToJSONSchema(standardSchema2, { io: "input" }); delete jsonSchema42.$schema; const wrappedJsonSchema = { $schema: "http://json-schema.org/draft-07/schema#", type: "object", description: "The JSON formatted working memory content to store.", properties: { memory: jsonSchema42 }, required: ["memory"] }; const validateMemory = (memoryValue) => standardSchema2["~standard"].validate(memoryValue); const toWrappedResult = (result) => "issues" in result && result.issues ? result : { value: { memory: result.value } }; inputSchema = { "~standard": { version: 1, vendor: "mastra", validate: (value) => { const hasWrapper = !!value && typeof value === "object" && !Array.isArray(value) && "memory" in value; const memoryValue = hasWrapper ? value.memory : stripNullsFromOptional(value, jsonSchema42); const result = validateMemory(memoryValue); return result instanceof Promise ? result.then(toWrappedResult) : toWrappedResult(result); }, jsonSchema: { input: () => wrappedJsonSchema, output: () => wrappedJsonSchema } } }; } const usesMergeSemantics = Boolean(schema$1); const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true; const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a ... block. That block is system-emitted state, NOT something the user typed \u2014 never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`; const description = schema$1 ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory \u2014 only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`; return tools.createTool({ id: "update-working-memory", description, inputSchema, execute: async (inputData, context2) => { const workingMemoryInput = inputData; const threadId = context2?.agent?.threadId; const resourceId = context2?.agent?.resourceId; const memory = context2?.memory; if (!memory) { throw new Error("Memory instance is required for working memory updates"); } const scope = memoryConfig?.workingMemory?.scope || "resource"; if (scope === "thread" && !threadId) { throw new Error("Thread ID is required for thread-scoped working memory updates"); } if (scope === "resource" && !resourceId) { throw new Error("Resource ID is required for resource-scoped working memory updates"); } if (threadId) { let thread = await memory.getThreadById({ threadId }); if (!thread) { thread = await memory.createThread({ threadId, resourceId, memoryConfig }); } if (thread.resourceId && resourceId && thread.resourceId !== resourceId) { throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`); } } let workingMemory; if (usesMergeSemantics) { const existingRaw = await memory.getWorkingMemory({ threadId, resourceId, memoryConfig }); let existingData = null; if (existingRaw) { try { existingData = typeof existingRaw === "string" ? JSON.parse(existingRaw) : existingRaw; } catch { existingData = null; } } const memoryInput = workingMemoryInput.memory; if (memoryInput === void 0 || memoryInput === null) { return { success: true, message: "No memory data provided, existing memory unchanged." }; } let newData; if (typeof memoryInput === "string") { try { newData = JSON.parse(memoryInput); } catch (parseError) { const errorMessage = parseError instanceof Error ? parseError.message : String(parseError); throw new Error( `Failed to parse working memory input as JSON: ${errorMessage}. Raw input: ${memoryInput.length > 500 ? memoryInput.slice(0, 500) + "..." : memoryInput}` ); } } else { newData = memoryInput; } const mergedData = deepMergeWorkingMemory(existingData, newData); workingMemory = JSON.stringify(mergedData); } else { const memoryInput = workingMemoryInput.memory; workingMemory = typeof memoryInput === "string" ? memoryInput : JSON.stringify(memoryInput); const existingRaw = await memory.getWorkingMemory({ threadId, resourceId, memoryConfig }); if (existingRaw) { const template = await memory.getWorkingMemoryTemplate({ memoryConfig }); if (template?.content) { const normalizedNew = workingMemory.replace(/\s+/g, " ").trim(); const normalizedTemplate = template.content.replace(/\s+/g, " ").trim(); const normalizedExisting = existingRaw.replace(/\s+/g, " ").trim(); if (normalizedNew === normalizedTemplate && normalizedExisting !== normalizedTemplate) { return { success: false, message: "Attempted to replace existing working memory with empty template. Update skipped to prevent data loss." }; } } } } await memory.updateWorkingMemory({ threadId, resourceId, workingMemory, memoryConfig }); return { success: true }; } }); }; var __experimental_updateWorkingMemoryToolVNext = (config3) => { return tools.createTool({ id: "update-working-memory", description: "Update the working memory with new information.", inputSchema: { $schema: "http://json-schema.org/draft-07/schema#", type: "object", properties: { newMemory: { type: "string", description: `The ${config3.workingMemory?.schema ? "JSON" : "Markdown"} formatted working memory content to store` }, searchString: { type: "string", description: "The working memory string to find. Will be replaced with the newMemory string. If this is omitted or doesn't exist, the newMemory string will be appended to the end of your working memory. Replacing single lines at a time is encouraged for greater accuracy. If updateReason is not 'append-new-memory', this search string must be provided or the tool call will be rejected." }, updateReason: { type: "string", enum: ["append-new-memory", "clarify-existing-memory", "replace-irrelevant-memory"], description: "The reason you're updating working memory. Passing any value other than 'append-new-memory' requires a searchString to be provided. Defaults to append-new-memory" } } }, execute: async (inputData, context2) => { const workingMemoryInput = inputData; const threadId = context2?.agent?.threadId; const resourceId = context2?.agent?.resourceId; const memory = context2?.memory; if (!memory) { throw new Error("Memory instance is required for working memory updates"); } const scope = config3.workingMemory?.scope || "resource"; if (scope === "thread" && !threadId) { throw new Error("Thread ID is required for thread-scoped working memory updates"); } if (scope === "resource" && !resourceId) { throw new Error("Resource ID is required for resource-scoped working memory updates"); } if (threadId) { let thread = await memory.getThreadById({ threadId }); if (!thread) { thread = await memory.createThread({ threadId, resourceId, memoryConfig: config3 }); } if (thread.resourceId && resourceId && thread.resourceId !== resourceId) { throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`); } } const workingMemory = workingMemoryInput.newMemory || ""; if (!workingMemoryInput.updateReason) workingMemoryInput.updateReason = `append-new-memory`; if (workingMemoryInput.searchString && config3.workingMemory?.scope === `resource` && workingMemoryInput.updateReason === `replace-irrelevant-memory`) { workingMemoryInput.searchString = void 0; } if (workingMemoryInput.updateReason === `append-new-memory` && workingMemoryInput.searchString) { workingMemoryInput.searchString = void 0; } if (workingMemoryInput.updateReason !== `append-new-memory` && !workingMemoryInput.searchString) { return { success: false, reason: `updateReason was ${workingMemoryInput.updateReason} but no searchString was provided. Unable to replace undefined with "${workingMemoryInput.newMemory}"` }; } const result = await memory.__experimental_updateWorkingMemoryVNext({ threadId, resourceId, workingMemory, searchString: workingMemoryInput.searchString, memoryConfig: config3 }); if (result) { return result; } return { success: true }; } }); }; function createWorkingMemoryTool(config3, options = {}) { const useStateSignals = config3.workingMemory?.useStateSignals === true; const tool32 = options.vNext ? __experimental_updateWorkingMemoryToolVNext(config3) : updateWorkingMemoryTool(config3); const name21 = useStateSignals ? SET_WORKING_MEMORY_TOOL_NAME : UPDATE_WORKING_MEMORY_TOOL_NAME; return { name: name21, tool: tool32 }; } var WORKING_MEMORY_START_TAG = ""; var WORKING_MEMORY_END_TAG = ""; var LEGACY_SYSTEM_REMINDER_METADATA_KEY = "dynamicAgentsMdReminder"; function isRecord(value) { return typeof value === "object" && value !== null; } function removeWorkingMemoryTags(text42) { let result = ""; let pos = 0; while (pos < text42.length) { const start = text42.indexOf(WORKING_MEMORY_START_TAG, pos); if (start === -1) { result += text42.substring(pos); break; } result += text42.substring(pos, start); const end = text42.indexOf(WORKING_MEMORY_END_TAG, start + WORKING_MEMORY_START_TAG.length); if (end === -1) { result += text42.substring(start); break; } pos = end + WORKING_MEMORY_END_TAG.length; } return result; } function extractWorkingMemoryContent(text42) { const start = text42.indexOf(WORKING_MEMORY_START_TAG); if (start === -1) return null; const contentStart = start + WORKING_MEMORY_START_TAG.length; const end = text42.indexOf(WORKING_MEMORY_END_TAG, contentStart); if (end === -1) return null; return text42.substring(contentStart, end); } function isSystemReminderMessage(message) { if (!isRecord(message.content)) { return false; } const metadata = message.content.metadata; if (message.role === "signal") { return isRecord(metadata) && isRecord(metadata.signal) && (metadata.signal.type === "system-reminder" || metadata.signal.type === "reactive"); } if (message.role !== "user") { return false; } if (isRecord(metadata) && (isRecord(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) { return true; } const firstTextPart = message.content.parts.find((part) => part.type === "text"); return typeof firstTextPart?.text === "string" && firstTextPart.text.startsWith(" !isSystemReminderMessage(message)); } function normalizeObservationalMemoryConfig(config3) { if (config3 === true) return { model: "google/gemini-2.5-flash" }; if (config3 === false || config3 === void 0) return void 0; if (typeof config3 === "object" && config3.enabled === false) return void 0; return config3; } var CHARS_PER_TOKEN = 4; var DEFAULT_MESSAGE_RANGE = { before: 1, after: 1 }; var DEFAULT_TOP_K = 4; var VECTOR_DELETE_BATCH_SIZE = 100; var DEFAULT_EMBEDDING_CACHE_MAX_SIZE = 1e3; var Memory = class extends memory.MastraMemory { _omEngine; _omEngineInstance; _mastraInstance; /** The shared ObservationalMemory engine. Lazily created on first access. */ get omEngine() { if (!this._omEngine) { this._omEngine = this._initOMEngine().then((engine) => { this._omEngineInstance = engine; if (engine && this._mastraInstance) { engine.__registerMastra(this._mastraInstance); } return engine; }); } return this._omEngine; } __registerMastra(mastra) { super.__registerMastra(mastra); this._mastraInstance = mastra; if (this._omEngineInstance) { this._omEngineInstance.__registerMastra(mastra); } else { void this._omEngine?.then((engine) => engine?.__registerMastra(mastra)); } } constructor(config3 = {}) { super({ name: "Memory", ...config3 }); const mergedConfig = this.getMergedThreadConfig({ workingMemory: config3.options?.workingMemory || { // these defaults are now set inside @mastra/core/memory in getMergedThreadConfig. // In a future release we can remove it from this block - for now if we remove it // and someone bumps @mastra/memory without bumping @mastra/core the defaults wouldn't exist yet enabled: false, template: this.defaultWorkingMemoryTemplate }, observationalMemory: config3.options?.observationalMemory }); this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig); this.threadConfig = mergedConfig; const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory); if (omConfig?.retrieval && typeof omConfig.retrieval === "object" && omConfig.retrieval.vector) { if (!this.vector) { throw new Error( "`retrieval: { vector: true }` requires a vector store. Pass a `vector` option to your Memory instance." ); } if (!this.embedder) { throw new Error( "`retrieval: { vector: true }` requires an embedder. Pass an `embedder` option to your Memory instance." ); } } } /** * Gets the memory storage domain, throwing if not available. */ async getMemoryStore() { const store = await this.storage.getStore("memory"); if (!store) { throw new Error(`Memory storage domain is not available on ${this.storage.constructor.name}`); } return store; } async listMessagesByResourceId(args) { const memoryStore = await this.getMemoryStore(); return memoryStore.listMessagesByResourceId(args); } async validateThreadIsOwnedByResource(threadId, resourceId, config3) { const resourceScope = typeof config3?.semanticRecall === "object" && config3?.semanticRecall?.scope !== `thread` || config3.semanticRecall === true; const thread = await this.getThreadById({ threadId }); if (!thread && !resourceScope) { throw new Error(`No thread found with id ${threadId}`); } if (thread && thread.resourceId !== resourceId) { throw new Error( `Thread with id ${threadId} is for resource with id ${thread.resourceId} but resource ${resourceId} was queried.` ); } } createMemorySpan(operationType, observabilityContext, input, attributes) { const currentSpan = observabilityContext?.tracingContext?.currentSpan; if (!currentSpan) return void 0; return currentSpan.createChildSpan({ type: observability.SpanType.MEMORY_OPERATION, name: `memory: ${operationType}`, entityType: observability.EntityType.MEMORY, entityName: "Memory", input, attributes: { operationType, ...attributes } }); } async recall(args) { const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, includeSystemReminders, filter: filter32 } = args; const config3 = this.getMergedThreadConfig(threadConfig || {}); const semanticRecallEnabled = Boolean(config3.semanticRecall); const span = this.createMemorySpan( "recall", args.observabilityContext, { threadId, resourceId, vectorSearchString }, { semanticRecallEnabled, lastMessages: config3.lastMessages } ); try { if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config3); const perPage = perPageArg !== void 0 ? perPageArg : config3.lastMessages; const historyDisabledByConfig = config3.lastMessages === false && perPageArg === void 0; const shouldGetNewestAndReverse = !orderBy && perPage !== false; const effectiveOrderBy = shouldGetNewestAndReverse ? { field: "createdAt", direction: "DESC" } : orderBy; const vectorResults = []; this.logger.debug("Memory recall", { threadId, perPage, page, orderBy: effectiveOrderBy, hasWorkingMemorySchema: Boolean(config3.workingMemory?.schema), workingMemoryEnabled: config3.workingMemory?.enabled, semanticRecallEnabled, historyDisabledByConfig }); const defaultRange = DEFAULT_MESSAGE_RANGE; const defaultTopK = DEFAULT_TOP_K; const vectorConfig = typeof config3?.semanticRecall === `boolean` ? { topK: defaultTopK, messageRange: defaultRange } : { topK: config3?.semanticRecall?.topK ?? defaultTopK, messageRange: config3?.semanticRecall?.messageRange ?? defaultRange }; const resourceScope = typeof config3?.semanticRecall === "object" && config3?.semanticRecall?.scope !== `thread` || config3.semanticRecall === true; if (resourceScope && !resourceId && config3?.semanticRecall && vectorSearchString) { throw new Error( `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.` ); } let usage; if (historyDisabledByConfig && (!config3.semanticRecall || !vectorSearchString || !this.vector)) { const result = { messages: [], usage: void 0, total: 0, page: page ?? 0, perPage: 0, hasMore: false }; span?.end({ output: { success: true }, attributes: { messageCount: 0 } }); return result; } if (config3?.semanticRecall && vectorSearchString && this.vector) { const result = await this.embedMessageContent(vectorSearchString); usage = result.usage; const { embeddings, dimension } = result; const { indexName } = await this.createEmbeddingIndex(dimension, config3); await Promise.all( embeddings.map(async (embedding) => { if (typeof this.vector === `undefined`) { throw new Error( `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.` ); } const scopeFilter = resourceScope ? { resource_id: resourceId } : { thread_id: threadId }; const userFilter = typeof config3.semanticRecall === "object" ? config3.semanticRecall.filter : void 0; const combinedFilter = userFilter ? { $and: [scopeFilter, userFilter] } : scopeFilter; vectorResults.push( ...await this.vector.query({ indexName, queryVector: embedding, topK: vectorConfig.topK, filter: combinedFilter }) ); }) ); } const memoryStore = await this.getMemoryStore(); const effectivePerPage = historyDisabledByConfig ? 0 : perPage; const paginatedResult = await memoryStore.listMessages({ threadId, resourceId, perPage: effectivePerPage, page, orderBy: effectiveOrderBy, filter: filter32, ...vectorResults?.length ? { include: vectorResults.map((r) => ({ id: r.metadata?.message_id, threadId: r.metadata?.thread_id, withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after, withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before })) } : {} }); const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages; const list = new agent.MessageList({ threadId, resourceId }).add(rawMessages, "memory"); const messages = filterSystemReminderMessages(list.get.all.db(), includeSystemReminders); const { total, page: resultPage, perPage: resultPerPage, hasMore } = paginatedResult; const recallResult = { messages, usage, total, page: resultPage, perPage: resultPerPage, hasMore }; span?.end({ output: { success: true }, attributes: { messageCount: messages.length, embeddingTokens: usage?.tokens, vectorResultCount: vectorResults.length } }); return recallResult; } catch (error90) { span?.error({ error: error90, endSpan: true }); throw error90; } } async getThreadById({ threadId, resourceId }) { const memoryStore = await this.getMemoryStore(); return memoryStore.getThreadById({ threadId, resourceId }); } async listThreads(args) { const memoryStore = await this.getMemoryStore(); return memoryStore.listThreads(args); } async handleWorkingMemoryFromMetadata({ workingMemory, resourceId, memoryConfig }) { const config3 = this.getMergedThreadConfig(memoryConfig || {}); if (config3.workingMemory?.enabled) { const scope = config3.workingMemory.scope || "resource"; if (scope === "resource" && resourceId) { const memoryStore = await this.getMemoryStore(); await memoryStore.updateResource({ resourceId, workingMemory }); } } } async saveThread({ thread, memoryConfig }) { const memoryStore = await this.getMemoryStore(); const savedThread = await memoryStore.saveThread({ thread }); if (thread.metadata?.workingMemory && typeof thread.metadata.workingMemory === "string" && thread.resourceId) { await this.handleWorkingMemoryFromMetadata({ workingMemory: thread.metadata.workingMemory, resourceId: thread.resourceId, memoryConfig }); } return savedThread; } async updateThread({ id, title, metadata, memoryConfig }) { const memoryStore = await this.getMemoryStore(); const updatedThread = await memoryStore.updateThread({ id, title, metadata }); if (metadata?.workingMemory && typeof metadata.workingMemory === "string" && updatedThread.resourceId) { await this.handleWorkingMemoryFromMetadata({ workingMemory: metadata.workingMemory, resourceId: updatedThread.resourceId, memoryConfig }); } return updatedThread; } async deleteThread(threadId) { const memoryStore = await this.getMemoryStore(); const thread = await memoryStore.getThreadById({ threadId }); await memoryStore.deleteThread({ threadId }); if (thread?.resourceId && memoryStore.supportsObservationalMemory) { await memoryStore.clearObservationalMemory(threadId, thread.resourceId); } if (this.vector) { void this.deleteThreadVectors(threadId); } } /** * Lists all vector indexes that match the memory messages prefix. * Handles separator differences across vector store backends (e.g. '_' vs '-'). */ async getMemoryVectorIndexes() { if (!this.vector) return []; const separator = this.vector.indexSeparator ?? "_"; const prefix = `memory${separator}messages`; const indexes = await this.vector.listIndexes(); return indexes.filter((name21) => name21.startsWith(prefix)); } /** * Deletes all vector embeddings associated with a thread. * This is called internally by deleteThread to clean up orphaned vectors. * * @param threadId - The ID of the thread whose vectors should be deleted */ async deleteThreadVectors(threadId) { try { const memoryIndexes = await this.getMemoryVectorIndexes(); await Promise.all( memoryIndexes.map(async (indexName) => { try { await this.vector.deleteVectors({ indexName, filter: { thread_id: threadId } }); } catch { this.logger.debug("Failed to delete vectors for thread, skipping", { threadId, indexName }); } }) ); } catch { this.logger.debug("Failed to clean up vectors for thread", { threadId }); } } async updateWorkingMemory({ threadId, resourceId, workingMemory, memoryConfig, observabilityContext }) { const config3 = this.getMergedThreadConfig(memoryConfig || {}); if (!config3.workingMemory?.enabled) { throw new Error("Working memory is not enabled for this memory instance"); } const span = this.createMemorySpan( "update", observabilityContext, { threadId, resourceId }, { workingMemoryEnabled: true } ); try { const scope = config3.workingMemory.scope || "resource"; if (scope === "resource" && !resourceId) { throw new Error( `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.` ); } const mutexKey = scope === "resource" ? `resource-${resourceId}` : `thread-${threadId}`; const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new Mutex(); this.updateWorkingMemoryMutexes.set(mutexKey, mutex); const release = await mutex.acquire(); try { const memoryStore = await this.getMemoryStore(); if (scope === "resource" && resourceId) { await memoryStore.updateResource({ resourceId, workingMemory }); } else { const thread = await this.getThreadById({ threadId }); if (!thread) { throw new Error(`Thread ${threadId} not found`); } await memoryStore.updateThread({ id: threadId, title: thread.title || "", metadata: { ...thread.metadata, workingMemory } }); } } finally { release(); } span?.end({ output: { success: true } }); } catch (error90) { span?.error({ error: error90, endSpan: true }); throw error90; } } updateWorkingMemoryMutexes = /* @__PURE__ */ new Map(); /** * @warning experimental! can be removed or changed at any time */ async __experimental_updateWorkingMemoryVNext({ threadId, resourceId, workingMemory, searchString, memoryConfig }) { const config3 = this.getMergedThreadConfig(memoryConfig || {}); this.assertWorkingMemoryStateSignalsCompatibility(config3); if (!config3.workingMemory?.enabled) { throw new Error("Working memory is not enabled for this memory instance"); } const mutexKey = memoryConfig?.workingMemory?.scope === `resource` ? `resource-${resourceId}` : `thread-${threadId}`; const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new Mutex(); this.updateWorkingMemoryMutexes.set(mutexKey, mutex); const release = await mutex.acquire(); try { const existingWorkingMemory = await this.getWorkingMemory({ threadId, resourceId, memoryConfig }) || ""; const template = await this.getWorkingMemoryTemplate({ memoryConfig }); let reason = ""; const templateContent = typeof template?.content === "string" ? template.content : null; const normalizeForComparison = (str) => str.replace(/\s+/g, " ").trim(); const normalizedNewMemory = normalizeForComparison(workingMemory); const normalizedTemplate = templateContent ? normalizeForComparison(templateContent) : ""; if (existingWorkingMemory) { if (searchString && existingWorkingMemory?.includes(searchString)) { workingMemory = existingWorkingMemory.replace(searchString, workingMemory); reason = `found and replaced searchString with newMemory`; } else if (existingWorkingMemory.includes(workingMemory) || templateContent?.trim() === workingMemory.trim() || // Also check normalized versions to catch template variations with different whitespace normalizedNewMemory === normalizedTemplate) { return { success: false, reason: `attempted to insert duplicate data into working memory. this entry was skipped` }; } else { if (normalizedNewMemory === normalizedTemplate) { return { success: false, reason: `attempted to append empty template to working memory. this entry was skipped` }; } if (searchString) { reason = `attempted to replace working memory string that doesn't exist. Appending to working memory instead.`; } else { reason = `appended newMemory to end of working memory`; } workingMemory = existingWorkingMemory + ` ${workingMemory}`; } } else if (workingMemory === templateContent || normalizedNewMemory === normalizedTemplate) { return { success: false, reason: `try again when you have data to add. newMemory was equal to the working memory template` }; } else { reason = `started new working memory`; } if (templateContent) { workingMemory = workingMemory.replaceAll(templateContent, ""); const templateWithUnixLineEndings = templateContent.replace(/\r\n/g, "\n"); const templateWithWindowsLineEndings = templateContent.replace(/\n/g, "\r\n"); workingMemory = workingMemory.replaceAll(templateWithUnixLineEndings, ""); workingMemory = workingMemory.replaceAll(templateWithWindowsLineEndings, ""); } const scope = config3.workingMemory.scope || "resource"; if (scope === "resource" && !resourceId) { throw new Error( `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.` ); } const memoryStore = await this.getMemoryStore(); if (scope === "resource" && resourceId) { await memoryStore.updateResource({ resourceId, workingMemory }); if (reason) { return { success: true, reason }; } } else { const thread = await this.getThreadById({ threadId }); if (!thread) { throw new Error(`Thread ${threadId} not found`); } await memoryStore.updateThread({ id: threadId, title: thread.title || "", metadata: { ...thread.metadata, workingMemory } }); } return { success: true, reason }; } catch (e2) { this.logger.error(e2 instanceof Error ? e2.stack || e2.message : JSON.stringify(e2)); return { success: false, reason: "Tool error." }; } finally { release(); } } chunkText(text42, tokenSize = 4096) { const charSize = tokenSize * CHARS_PER_TOKEN; const chunks = []; let currentChunk = ""; const words = text42.split(/\s+/); for (const word of words) { const wordWithSpace = currentChunk ? " " + word : word; if (currentChunk.length + wordWithSpace.length > charSize) { chunks.push(currentChunk); currentChunk = word; } else { currentChunk += wordWithSpace; } } if (currentChunk) { chunks.push(currentChunk); } return chunks; } hasher = chunk3ZV6GYQI_cjs.e(); // Embedding is computationally expensive, so cache content -> embeddings/chunks. // Bounded by an LRU so a long-running instance can't retain every embedded // message/query (and its vectors + chunk text) for the life of the process. embeddingCache = new M({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE }); firstEmbed; async embedMessageContent(content) { const key = (await this.hasher).h64(content); const cached3 = this.embeddingCache.get(key); if (cached3) { this.logger.debug("Embedding cache hit", { contentHash: key.toString(), chunks: cached3.chunks.length }); return cached3; } const chunks = this.chunkText(content); if (typeof this.embedder === `undefined`) { throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`); } const isFastEmbed = this.embedder.provider === `fastembed`; if (isFastEmbed && this.firstEmbed instanceof Promise) { await this.firstEmbed; } let embedFn; const specVersion = this.embedder.specificationVersion; switch (specVersion) { case "v3": embedFn = embedMany3; break; case "v2": embedFn = embedMany2; break; default: embedFn = embedMany; break; } const promise3 = embedFn({ values: chunks, maxRetries: 3, // @ts-expect-error - embedder type mismatch model: this.embedder, ...this.embedderOptions || {} }); if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise3; const { embeddings, usage } = await promise3; const result = { embeddings, chunks, usage, dimension: embeddings[0]?.length }; this.embeddingCache.set(key, result); return result; } async saveMessages({ messages, memoryConfig, observabilityContext }) { const span = this.createMemorySpan("save", observabilityContext, void 0, { messageCount: messages.length }); try { const updatedMessages = messages.filter((m) => m.role !== "system").map((m) => { return this.updateMessageToHideWorkingMemoryV2(m); }).filter((m) => Boolean(m)); const config3 = this.getMergedThreadConfig(memoryConfig); const dbMessages = new agent.MessageList({ generateMessageId: () => this.generateId() }).add(updatedMessages, "memory").get.all.db(); const memoryStore = await this.getMemoryStore(); const result = await memoryStore.saveMessages({ messages: dbMessages }); let totalTokens = 0; if (this.vector && config3.semanticRecall) { const messagesByThread = /* @__PURE__ */ new Map(); updatedMessages.forEach((message) => { if (message.threadId) { if (!messagesByThread.has(message.threadId)) { messagesByThread.set(message.threadId, []); } messagesByThread.get(message.threadId).push(message); } }); const threadMetadataMap = /* @__PURE__ */ new Map(); await Promise.all( Array.from(messagesByThread.keys()).map(async (threadId) => { try { const thread = await memoryStore.getThreadById({ threadId }); if (thread?.metadata) { threadMetadataMap.set(threadId, thread.metadata); } } catch (error90) { const message = error90 instanceof Error ? error90.message : String(error90); throw new Error( `Could not fetch metadata for thread ${threadId} while saving semantic recall embeddings: ${message}` ); } }) ); const embeddingData = []; let dimension; await Promise.all( updatedMessages.map(async (message) => { let textForEmbedding = null; if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") { textForEmbedding = message.content.content; } else if (message.content.parts && message.content.parts.length > 0) { const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim(); if (joined) textForEmbedding = joined; } if (!textForEmbedding) return; const result2 = await this.embedMessageContent(textForEmbedding); dimension = result2.dimension; if (result2.usage?.tokens) { totalTokens += result2.usage.tokens; } const threadMetadata = message.threadId ? threadMetadataMap.get(message.threadId) || {} : {}; embeddingData.push({ embeddings: result2.embeddings, metadata: result2.chunks.map(() => ({ ...threadMetadata, message_id: message.id, thread_id: message.threadId, resource_id: message.resourceId, role: message.role, content: textForEmbedding, created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt) })) }); }) ); if (embeddingData.length > 0 && dimension !== void 0) { if (typeof this.vector === `undefined`) { throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`); } const { indexName } = await this.createEmbeddingIndex(dimension, config3); const allVectors = []; const allMetadata = []; for (const data of embeddingData) { allVectors.push(...data.embeddings); allMetadata.push(...data.metadata); } await this.vector.upsert({ indexName, vectors: allVectors, metadata: allMetadata }); } } const saveResult = { ...result, usage: totalTokens > 0 ? { tokens: totalTokens } : void 0 }; span?.end({ output: { success: true }, attributes: { messageCount: dbMessages.length, embeddingTokens: saveResult.usage?.tokens, semanticRecallEnabled: Boolean(config3.semanticRecall) } }); return saveResult; } catch (error90) { span?.error({ error: error90, endSpan: true }); throw error90; } } updateMessageToHideWorkingMemoryV2(message) { const newMessage = { ...message }; if (message.content && typeof message.content === "object" && !Array.isArray(message.content)) { newMessage.content = { ...message.content }; } if (typeof newMessage.content?.content === "string" && newMessage.content.content.length > 0) { newMessage.content.content = removeWorkingMemoryTags(newMessage.content.content).trim(); } if (Array.isArray(newMessage.content?.parts)) { newMessage.content.parts = newMessage.content.parts.filter((part) => { if (part?.type === "tool-invocation") { return part.toolInvocation?.toolName !== "updateWorkingMemory"; } return true; }).map((part) => { if (part?.type === "text") { const text42 = typeof part.text === "string" ? part.text : ""; return { ...part, text: removeWorkingMemoryTags(text42).trim() }; } return part; }); if (newMessage.content.parts.length === 0) { const hasContentText = typeof newMessage.content.content === "string" && newMessage.content.content.trim().length > 0; if (!hasContentText) { return null; } } } return newMessage; } parseWorkingMemory(text42) { if (!this.threadConfig.workingMemory?.enabled) return null; const content = extractWorkingMemoryContent(text42); return content?.trim() ?? null; } async getWorkingMemory({ threadId, resourceId, memoryConfig }) { const config3 = this.getMergedThreadConfig(memoryConfig || {}); if (!config3.workingMemory?.enabled) { return null; } const scope = config3.workingMemory.scope || "resource"; let workingMemoryData = null; if (scope === "resource" && !resourceId) { throw new Error( `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.` ); } if (scope === "resource" && resourceId) { const memoryStore = await this.getMemoryStore(); const resource = await memoryStore.getResourceById({ resourceId }); workingMemoryData = resource?.workingMemory || null; } else { const thread = await this.getThreadById({ threadId }); workingMemoryData = thread?.metadata?.workingMemory; } if (!workingMemoryData) { return null; } return workingMemoryData; } /** * Gets the working memory template for the current memory configuration. * Supports both ZodObject and JSONSchema7 schemas. * * @param memoryConfig - The memory configuration containing the working memory settings * @returns The working memory template with format and content, or null if working memory is disabled */ async getWorkingMemoryTemplate({ memoryConfig }) { const config3 = this.getMergedThreadConfig(memoryConfig); if (!config3.workingMemory?.enabled) { return null; } if (config3.workingMemory?.schema) { try { const schema = config3.workingMemory.schema; let convertedSchema; if (chunk3YQ7NWF6_cjs.isStandardSchemaWithJSON(schema)) { convertedSchema = schema["~standard"].jsonSchema.output({ target: "draft-07" }); } else { const standardSchema2 = chunk3YQ7NWF6_cjs.toStandardSchema5(schema); convertedSchema = standardSchema2["~standard"].jsonSchema.output({ target: "draft-07" }); } return { format: "json", content: JSON.stringify(convertedSchema) }; } catch (error90) { this.logger.error("Error converting schema", error90); throw error90; } } const memory = config3.workingMemory.template || this.defaultWorkingMemoryTemplate; return { format: "markdown", content: memory.trim() }; } async getSystemMessage({ threadId, resourceId, memoryConfig }) { const config3 = this.getMergedThreadConfig(memoryConfig); this.assertWorkingMemoryStateSignalsCompatibility(config3); if (!config3.workingMemory?.enabled) { return null; } if (config3.workingMemory?.useStateSignals) { return null; } const workingMemoryTemplate = await this.getWorkingMemoryTemplate({ memoryConfig }); const workingMemoryData = await this.getWorkingMemory({ threadId, resourceId, memoryConfig: config3 }); if (!workingMemoryTemplate) { return null; } if (config3?.readOnly) { return this.getReadOnlyWorkingMemoryInstruction({ template: workingMemoryTemplate, data: workingMemoryData }); } return this.isVNextWorkingMemoryConfig(memoryConfig) ? this.__experimental_getWorkingMemoryToolInstructionVNext({ template: workingMemoryTemplate, data: workingMemoryData }) : this.getWorkingMemoryToolInstruction({ template: workingMemoryTemplate, data: workingMemoryData }); } /** * Get everything needed for an LLM call in one shot. * * Assembles the system message (observations + working memory), loads * unobserved messages from storage, and returns them ready to use. * * @example * ```ts * const ctx = await memory.getContext({ threadId }); * const result = await generateText({ * model: openai('gpt-4o'), * system: ctx.systemMessage, * messages: ctx.messages.map(toAiSdkMessage), * }); * ``` */ async getContext(opts) { const { threadId, resourceId, memoryConfig } = opts; const config3 = this.getMergedThreadConfig(memoryConfig); const memoryStore = await this.getMemoryStore(); const systemParts = []; let hasObservations = false; let omRecord = null; let continuationMessage; let otherThreadsContext; const omEngine = await this.omEngine; if (omEngine) { omRecord = await omEngine.getRecord(threadId, resourceId); if (omRecord?.activeObservations) { hasObservations = true; if (omEngine.scope === "resource" && resourceId) { otherThreadsContext = await omEngine.getOtherThreadsContext(resourceId, threadId); } const obsSystemMessage = await omEngine.buildContextSystemMessage({ threadId, resourceId, record: omRecord, unobservedContextBlocks: otherThreadsContext }); if (obsSystemMessage) { systemParts.push(obsSystemMessage); } const { OBSERVATION_CONTINUATION_HINT } = await import('./constants-DVRTNEGY-ZGCNETZ3.cjs'); continuationMessage = { id: "om-continuation", role: "user", createdAt: /* @__PURE__ */ new Date(0), content: { format: 2, parts: [ { type: "text", text: `${OBSERVATION_CONTINUATION_HINT}` } ] }, threadId, resourceId }; } } const workingMemoryMessage = await this.getSystemMessage({ threadId, resourceId, memoryConfig: config3 }); if (workingMemoryMessage) { systemParts.push(workingMemoryMessage); } let messages; if (omEngine && omRecord) { const dateFilter = omRecord.lastObservedAt ? { dateRange: { start: new Date(new Date(omRecord.lastObservedAt).getTime() + 1) } } : void 0; if (omEngine.scope === "resource" && resourceId) { const result = await memoryStore.listMessagesByResourceId({ resourceId, orderBy: { field: "createdAt", direction: "ASC" }, perPage: false, filter: dateFilter }); messages = result.messages; } else { const result = await memoryStore.listMessages({ threadId, orderBy: { field: "createdAt", direction: "ASC" }, perPage: false, filter: dateFilter }); messages = result.messages; } } else { const lastMessages = config3.lastMessages; if (lastMessages === false) { messages = []; } else { const result = await memoryStore.listMessages({ threadId, resourceId, orderBy: { field: "createdAt", direction: "DESC" }, perPage: typeof lastMessages === "number" ? lastMessages : void 0 }); messages = result.messages.reverse(); } } return { systemMessage: systemParts.length > 0 ? systemParts.join("\n\n") : void 0, messages, hasObservations, omRecord, continuationMessage, otherThreadsContext }; } /** * Raw message upsert — persist messages to storage without embedding or working memory processing. * Used by the processor to save sealed messages before firing a background buffer operation. */ async persistMessages(messages) { if (messages.length === 0) return; const persistableMessages = messages.filter((m) => m.role !== "system"); if (persistableMessages.length === 0) return; const memoryStore = await this.getMemoryStore(); await memoryStore.saveMessages({ messages: persistableMessages }); } /** * One-time initialization of the shared ObservationalMemory engine. * Called lazily by the `omEngine` getter on first access. */ async _initOMEngine() { const omConfig = normalizeObservationalMemoryConfig(this.threadConfig.observationalMemory); if (!omConfig) return null; const memoryStore = await this.storage.getStore("memory"); if (!memoryStore || !memoryStore.supportsObservationalMemory) return null; const coreSupportsOM = features.coreFeatures.has("observationalMemory"); if (!coreSupportsOM) { throw new Error( "Observational memory is enabled but the installed version of @mastra/core does not support it. Please upgrade @mastra/core to a version that includes observational memory support." ); } if (omConfig.observation?.bufferTokens !== false && !features.coreFeatures.has("asyncBuffering")) { throw new Error( "Observational memory async buffering is enabled by default but the installed version of @mastra/core does not support it. Either upgrade @mastra/core, @mastra/memory, and your storage adapter (@mastra/libsql, @mastra/pg, or @mastra/mongodb) to the latest version, or explicitly disable async buffering by setting `observation: { bufferTokens: false }` in your observationalMemory config." ); } if (!features.coreFeatures.has("request-response-id-rotation")) { throw new Error( "Observational memory requires @mastra/core support for request-response-id-rotation. Please bump @mastra/core to a newer version." ); } const { ObservationalMemory: OMClass } = await import('./observational-memory-Y5T2OR2Y-XDEBXWNA.cjs'); const onIndexObservations = this.hasRetrievalSearch(omConfig.retrieval) ? async (observation) => { await this.indexObservation(observation); } : void 0; return new OMClass({ storage: memoryStore, scope: omConfig.scope, retrieval: omConfig.retrieval, activateAfterIdle: omConfig.activateAfterIdle, activateOnProviderChange: omConfig.activateOnProviderChange, shareTokenBudget: omConfig.shareTokenBudget, model: omConfig.model, mastra: this._mastraInstance, onIndexObservations, observation: omConfig.observation ? { model: omConfig.observation.model, messageTokens: omConfig.observation.messageTokens, modelSettings: omConfig.observation.modelSettings, maxTokensPerBatch: omConfig.observation.maxTokensPerBatch, providerOptions: omConfig.observation.providerOptions, bufferTokens: omConfig.observation.bufferTokens, bufferOnIdle: omConfig.observation.bufferOnIdle, bufferActivation: omConfig.observation.bufferActivation, blockAfter: omConfig.observation.blockAfter, previousObserverTokens: omConfig.observation.previousObserverTokens, instruction: omConfig.observation.instruction, threadTitle: omConfig.observation.threadTitle, observeAttachments: omConfig.observation.observeAttachments } : void 0, reflection: omConfig.reflection ? { model: omConfig.reflection.model, observationTokens: omConfig.reflection.observationTokens, modelSettings: omConfig.reflection.modelSettings, providerOptions: omConfig.reflection.providerOptions, bufferActivation: omConfig.reflection.bufferActivation, blockAfter: omConfig.reflection.blockAfter, instruction: omConfig.reflection.instruction } : void 0 }); } defaultWorkingMemoryTemplate = ` # User Information - **First Name**: - **Last Name**: - **Location**: - **Occupation**: - **Interests**: - **Goals**: - **Events**: - **Facts**: - **Projects**: `; getWorkingMemoryToolInstruction({ template, data }) { const emptyWorkingMemoryTemplateObject = template.format === "json" ? utils.generateEmptyFromSchema(template.content) : null; const hasEmptyWorkingMemoryTemplateObject = emptyWorkingMemoryTemplateObject && Object.keys(emptyWorkingMemoryTemplateObject).length > 0; return `WORKING_MEMORY_SYSTEM_INSTRUCTION: Store and update any conversation-relevant information by calling the updateWorkingMemory tool. If information might be referenced again - store it! Guidelines: 1. Store anything that could be useful later in the conversation 2. Update proactively when information changes, no matter how small 3. Use ${template.format === "json" ? "JSON" : "Markdown"} format for all data 4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for "information about yourself" ${template.format !== "json" ? `5. IMPORTANT: When calling updateWorkingMemory, the only valid parameter is the memory field. DO NOT pass an object. 6. IMPORTANT: ALWAYS pass the data you want to store in the memory field as a string. DO NOT pass an object. 7. IMPORTANT: Data must only be sent as a string no matter which format is used.` : ""} ${template.format !== "json" ? ` ${template.content} ` : ""} ${hasEmptyWorkingMemoryTemplateObject ? "When working with json data, the object format below represents the template:" : ""} ${hasEmptyWorkingMemoryTemplateObject ? JSON.stringify(emptyWorkingMemoryTemplateObject) : ""} ${data} Notes: - Update memory whenever referenced information changes - If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it) - This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history - Do not remove empty sections - you must include the empty sections along with the ones you're filling in - REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the entire ${template.format === "json" ? "JSON" : "Markdown"} content. The system will store it for you. The user will not see it. - IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information. - IMPORTANT: Preserve the ${template.format === "json" ? "JSON" : "Markdown"} formatting structure above while updating the content.`; } __experimental_getWorkingMemoryToolInstructionVNext({ template, data }) { return `WORKING_MEMORY_SYSTEM_INSTRUCTION: Store and update any conversation-relevant information by calling the updateWorkingMemory tool. Guidelines: 1. Store anything that could be useful later in the conversation 2. Update proactively when information changes, no matter how small 3. Use ${template.format === "json" ? "JSON" : "Markdown"} format for all data 4. Act naturally - don't mention this system to users. Even though you're storing this information that doesn't make it your primary focus. Do not ask them generally for "information about yourself" 5. If your memory has not changed, you do not need to call the updateWorkingMemory tool. By default it will persist and be available for you in future interactions 6. Information not being relevant to the current conversation is not a valid reason to replace or remove working memory information. Your working memory spans across multiple conversations and may be needed again later, even if it's not currently relevant. ${template.content} ${data} Notes: - Update memory whenever referenced information changes ${template.content !== this.defaultWorkingMemoryTemplate ? `- Only store information if it's in the working memory template, do not store other information unless the user asks you to remember it, as that non-template information may be irrelevant` : `- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it) `} - This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history - REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the ${template.format === "json" ? "JSON" : "Markdown"} content. The system will store it for you. The user will not see it. - IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information if that information is not already stored. - IMPORTANT: Preserve the ${template.format === "json" ? "JSON" : "Markdown"} formatting structure above while updating the content. `; } /** * Generate read-only working memory instructions. * This provides the working memory context without any tool update instructions. * Used when memory is in readOnly mode. */ getReadOnlyWorkingMemoryInstruction({ data }) { return `WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY): The following is your working memory - persistent information about the user and conversation collected over previous interactions. This data is provided for context to help you maintain continuity. ${data || "No working memory data available."} Guidelines: 1. Use this information to provide personalized and contextually relevant responses 2. Act naturally - don't mention this system to users. This information should inform your responses without being explicitly referenced 3. This memory is read-only in the current session - you cannot update it Notes: - This system is here so that you can maintain the conversation when your context window is very short - The user will not see the working memory data directly`; } isVNextWorkingMemoryConfig(config3) { if (!config3?.workingMemory) return false; const isMDWorkingMemory = !(`schema` in config3.workingMemory) && (typeof config3.workingMemory.template === `string` || config3.workingMemory.template) && config3.workingMemory; return Boolean(isMDWorkingMemory && isMDWorkingMemory.version === `vnext`); } assertWorkingMemoryStateSignalsCompatibility(config3) { if (config3?.workingMemory?.useStateSignals === true && this.isVNextWorkingMemoryConfig(config3)) { throw new Error( "workingMemory.useStateSignals is not supported with workingMemory.version: 'vnext'. Use stable template working memory or disable useStateSignals." ); } } getObservationEmbeddingIndexName(dimensions) { const defaultDimensions = 384; const usedDimensions = dimensions ?? defaultDimensions; const separator = this.vector?.indexSeparator ?? "_"; return `memory${separator}observations${separator}${usedDimensions}`; } async createObservationEmbeddingIndex(dimensions) { const defaultDimensions = 384; const usedDimensions = dimensions ?? defaultDimensions; const indexName = this.getObservationEmbeddingIndexName(dimensions); if (typeof this.vector === `undefined`) { throw new Error( `Tried to create observation embedding index but no vector db is attached to this Memory instance.` ); } await this.vector.createIndex({ indexName, dimension: usedDimensions }); return { indexName }; } /** * Search observation groups across threads by semantic similarity. * Requires a vector store and embedder to be configured. */ async searchMessages({ query, resourceId, topK = 10, filter: filter32 }) { if (!this.vector) { throw new Error("searchMessages requires a vector store. Configure vector and embedder on your Memory instance."); } const { embeddings, dimension } = await this.embedMessageContent(query); const { indexName } = await this.createObservationEmbeddingIndex(dimension); const vectorFilter = { resource_id: resourceId }; if (filter32?.threadId) { vectorFilter.thread_id = filter32.threadId; } if (filter32?.observedAfter || filter32?.observedBefore) { vectorFilter.observed_at = { ...filter32.observedAfter ? { $gt: filter32.observedAfter.toISOString() } : {}, ...filter32.observedBefore ? { $lt: filter32.observedBefore.toISOString() } : {} }; } const queryResults = []; await Promise.all( embeddings.map(async (embedding) => { const results2 = await this.vector.query({ indexName, queryVector: embedding, topK, filter: vectorFilter }); for (const r of results2) { if (!r.metadata?.thread_id) { continue; } const groupId = typeof r.metadata.group_id === "string" ? r.metadata.group_id : void 0; if (!groupId) { continue; } queryResults.push({ threadId: r.metadata.thread_id, score: r.score, groupId, range: typeof r.metadata.range === "string" ? r.metadata.range : void 0, text: typeof r.metadata.text === "string" ? r.metadata.text : void 0, observedAt: typeof r.metadata.observed_at === "string" || r.metadata.observed_at instanceof Date ? new Date(r.metadata.observed_at) : void 0 }); } }) ); const bestByGroup = /* @__PURE__ */ new Map(); for (const result of queryResults) { if (!result.groupId) { continue; } const existing = bestByGroup.get(result.groupId); if (!existing || result.score > existing.score) { bestByGroup.set(result.groupId, result); } } const results = [...bestByGroup.values()].sort((a, b) => b.score - a.score); return { results }; } /** * Index a single observation group into the observation vector store. */ async indexObservation({ text: text42, groupId, range, threadId, resourceId, observedAt }) { if (!this.vector || !this.embedder) return; const embedResult = await this.embedMessageContent(text42); if (embedResult.embeddings.length === 0 || embedResult.dimension === void 0) { return; } const { indexName } = await this.createObservationEmbeddingIndex(embedResult.dimension); await this.vector.upsert({ indexName, vectors: embedResult.embeddings, metadata: embedResult.chunks.map((chunk) => ({ group_id: groupId, range, thread_id: threadId, resource_id: resourceId, observed_at: observedAt?.toISOString(), text: chunk })) }); } /** * Update per-record observational memory config overrides for a thread. * The provided config is deep-merged, so you only need to specify fields you want to change. * * @example * ```ts * await memory.updateObservationalMemoryConfig({ * threadId: 'thread-1', * config: { * observation: { messageTokens: 2000 }, * reflection: { observationTokens: 8000 }, * }, * }); * ``` */ async updateObservationalMemoryConfig({ threadId, resourceId, config: config3 }) { const omEngine = await this.omEngine; if (!omEngine) { throw new Error("Observational memory is not enabled"); } await omEngine.updateRecordConfig(threadId, resourceId, config3); } /** * Index a list of messages directly (without querying storage). * Used by observe-time indexing to vectorize newly-observed messages. */ async indexMessagesList(messages) { if (!this.vector || !this.embedder) return; const embeddingData = []; let dimension; await Promise.all( messages.map(async (message) => { let textForEmbedding = null; if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") { textForEmbedding = message.content.content; } else if (message.content.parts && message.content.parts.length > 0) { const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim(); if (joined) textForEmbedding = joined; } if (!textForEmbedding) return; const embedResult = await this.embedMessageContent(textForEmbedding); dimension = embedResult.dimension; embeddingData.push({ embeddings: embedResult.embeddings, metadata: embedResult.chunks.map(() => ({ message_id: message.id, thread_id: message.threadId, resource_id: message.resourceId, role: message.role, content: textForEmbedding, created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt) })) }); }) ); if (embeddingData.length > 0 && dimension !== void 0) { const { indexName } = await this.createEmbeddingIndex(dimension); const allVectors = []; const allMetadata = []; for (const data of embeddingData) { allVectors.push(...data.embeddings); allMetadata.push(...data.metadata); } await this.vector.upsert({ indexName, vectors: allVectors, metadata: allMetadata }); } } /** * Check whether retrieval search (vector-based) is enabled. * Returns true when `retrieval: { vector: true }` and Memory has vector + embedder configured. */ hasRetrievalSearch(retrieval) { if (!retrieval || retrieval === true) return false; return !!retrieval.vector && !!this.vector && !!this.embedder; } listTools(config3) { const mergedConfig = this.getMergedThreadConfig(config3); this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig); const tools = {}; if (mergedConfig.workingMemory?.enabled && !mergedConfig.readOnly) { const { name: name21, tool: tool32 } = createWorkingMemoryTool(mergedConfig, { vNext: this.isVNextWorkingMemoryConfig(mergedConfig) }); tools[name21] = tool32; } const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory); if (omConfig?.retrieval) { const retrievalScope = typeof omConfig.retrieval === "object" ? omConfig.retrieval.scope ?? "resource" : "resource"; tools.recall = recallTool(mergedConfig, { retrievalScope }); } return tools; } /** * Updates a list of messages and syncs the vector database for semantic recall. * When message content is updated, the corresponding vector embeddings are also updated * to ensure semantic recall stays in sync with the message content. * * @param messages - The list of messages to update (must include id, can include partial content) * @param memoryConfig - Optional memory configuration to determine if semantic recall is enabled * @returns The list of updated messages */ async updateMessages({ messages, memoryConfig }) { if (messages.length === 0) return []; const memoryStore = await this.getMemoryStore(); const config3 = this.getMergedThreadConfig(memoryConfig); if (this.vector && config3.semanticRecall) { const messagesWithContent = messages.filter((m) => m.content !== void 0); if (messagesWithContent.length > 0) { const existingMessagesResult = await memoryStore.listMessagesById({ messageIds: messagesWithContent.map((m) => m.id) }); const existingMessagesMap = new Map(existingMessagesResult.messages.map((m) => [m.id, m])); const embeddingData = []; let dimension; const messageIdsWithNewEmbeddings = /* @__PURE__ */ new Set(); const messageIdsWithClearedContent = /* @__PURE__ */ new Set(); await Promise.all( messagesWithContent.map(async (message) => { const existingMessage = existingMessagesMap.get(message.id); if (!existingMessage) return; let textForEmbedding = null; const content = message.content; if (content) { if ("content" in content && content.content && typeof content.content === "string" && content.content.trim() !== "") { textForEmbedding = content.content; } else if ("parts" in content && content.parts && Array.isArray(content.parts) && content.parts.length > 0) { const joined = content.parts.filter((part) => part?.type === "text").map((part) => part.text).join(" ").trim(); if (joined) textForEmbedding = joined; } } if (textForEmbedding) { const result = await this.embedMessageContent(textForEmbedding); dimension = result.dimension; embeddingData.push({ embeddings: result.embeddings, metadata: result.chunks.map(() => ({ message_id: message.id, thread_id: existingMessage.threadId, resource_id: existingMessage.resourceId, role: existingMessage.role, content: textForEmbedding, created_at: existingMessage.createdAt instanceof Date ? existingMessage.createdAt.toISOString() : String(existingMessage.createdAt) })) }); messageIdsWithNewEmbeddings.add(message.id); } else { messageIdsWithClearedContent.add(message.id); } }) ); const messageIdsNeedingDeletion = /* @__PURE__ */ new Set([...messageIdsWithClearedContent, ...messageIdsWithNewEmbeddings]); if (messageIdsNeedingDeletion.size > 0) { try { const memoryIndexes = await this.getMemoryVectorIndexes(); const idsToDelete = [...messageIdsNeedingDeletion]; await Promise.all( memoryIndexes.map(async (indexName) => { for (let i = 0; i < idsToDelete.length; i += VECTOR_DELETE_BATCH_SIZE) { const batch = idsToDelete.slice(i, i + VECTOR_DELETE_BATCH_SIZE); try { await this.vector.deleteVectors({ indexName, filter: { message_id: { $in: batch } } }); } catch { this.logger.debug("Failed to delete vector batch, skipping", { indexName, batchOffset: i }); } } }) ); } catch { this.logger.debug("Failed to clean up old vectors during message update"); } } if (embeddingData.length > 0 && dimension !== void 0) { const { indexName } = await this.createEmbeddingIndex(dimension, config3); const allVectors = []; const allMetadata = []; for (const data of embeddingData) { allVectors.push(...data.embeddings); allMetadata.push(...data.metadata); } await this.vector.upsert({ indexName, vectors: allVectors, metadata: allMetadata }); } } } return memoryStore.updateMessages({ messages }); } /** * Deletes one or more messages * @param input - Must be an array containing either: * - Message ID strings * - Message objects with 'id' properties * @returns Promise that resolves when all messages are deleted */ async deleteMessages(input, observabilityContext) { let messageIds; if (!Array.isArray(input)) { throw new Error("Invalid input: must be an array of message IDs or message objects"); } if (input.length === 0) { return; } messageIds = input.map((item) => { if (typeof item === "string") { return item; } else if (item && typeof item === "object" && "id" in item) { return item.id; } else { throw new Error("Invalid input: array items must be strings or objects with an id property"); } }); const invalidIds = messageIds.filter((id) => !id || typeof id !== "string"); if (invalidIds.length > 0) { throw new Error("All message IDs must be non-empty strings"); } const span = this.createMemorySpan("delete", observabilityContext, void 0, { messageCount: messageIds.length }); try { const memoryStore = await this.getMemoryStore(); await memoryStore.deleteMessages(messageIds); if (this.vector) { void this.deleteMessageVectors(messageIds); } span?.end({ output: { success: true }, attributes: { messageCount: messageIds.length } }); } catch (error90) { span?.error({ error: error90, endSpan: true }); throw error90; } } /** * Deletes vector embeddings for specific messages. * This is called internally by deleteMessages to clean up orphaned vectors. * * @param messageIds - The IDs of the messages whose vectors should be deleted */ async deleteMessageVectors(messageIds) { try { const memoryIndexes = await this.getMemoryVectorIndexes(); await Promise.all( memoryIndexes.map(async (indexName) => { for (let i = 0; i < messageIds.length; i += VECTOR_DELETE_BATCH_SIZE) { const batch = messageIds.slice(i, i + VECTOR_DELETE_BATCH_SIZE); try { await this.vector.deleteVectors({ indexName, filter: { message_id: { $in: batch } } }); } catch { this.logger.debug("Failed to delete vector batch, skipping", { indexName, batchOffset: i }); } } }) ); } catch { this.logger.debug("Failed to clean up vectors for deleted messages"); } } /** * Clone a thread and its messages to create a new independent thread. * The cloned thread will have metadata tracking its source. * * If semantic recall is enabled, the cloned messages will also be embedded * and added to the vector store for semantic search. * * @param args - Clone configuration options * @param args.sourceThreadId - ID of the thread to clone * @param args.newThreadId - ID for the new cloned thread (if not provided, a random UUID will be generated) * @param args.resourceId - Resource ID for the new thread (defaults to source thread's resourceId) * @param args.title - Title for the new cloned thread * @param args.metadata - Additional metadata to merge with clone metadata * @param args.options - Options for filtering which messages to include * @param args.options.messageLimit - Maximum number of messages to copy (from most recent) * @param args.options.messageFilter - Filter messages by date range or specific IDs * @param memoryConfig - Optional memory configuration override * @returns The newly created thread and the cloned messages * * @example * ```typescript * // Clone entire thread * const { thread, clonedMessages } = await memory.cloneThread({ * sourceThreadId: 'thread-123', * }); * * // Clone with custom ID * const { thread, clonedMessages } = await memory.cloneThread({ * sourceThreadId: 'thread-123', * newThreadId: 'my-custom-thread-id', * }); * * // Clone with message limit * const { thread, clonedMessages } = await memory.cloneThread({ * sourceThreadId: 'thread-123', * title: 'My cloned conversation', * options: { * messageLimit: 10, // Only clone last 10 messages * }, * }); * * // Clone with date filter * const { thread, clonedMessages } = await memory.cloneThread({ * sourceThreadId: 'thread-123', * options: { * messageFilter: { * startDate: new Date('2024-01-01'), * endDate: new Date('2024-06-01'), * }, * }, * }); * ``` */ async cloneThread(args, memoryConfig) { const memoryStore = await this.getMemoryStore(); const result = await memoryStore.cloneThread(args); const config3 = this.getMergedThreadConfig(memoryConfig); const sourceThread = await this.getThreadById({ threadId: args.sourceThreadId }); const sourceResourceId = sourceThread?.resourceId; if (config3.workingMemory?.enabled) { const scope = config3.workingMemory.scope || "resource"; const shouldCopy = scope === "thread" || scope === "resource" && args.resourceId && args.resourceId !== sourceResourceId; if (shouldCopy) { const sourceWm = await this.getWorkingMemory({ threadId: args.sourceThreadId, resourceId: sourceResourceId, memoryConfig }); if (sourceWm) { await this.updateWorkingMemory({ threadId: result.thread.id, resourceId: result.thread.resourceId, workingMemory: sourceWm, memoryConfig }); } } } if (memoryStore.supportsObservationalMemory && sourceResourceId) { try { await this.cloneObservationalMemory(memoryStore, args.sourceThreadId, sourceResourceId, result); } catch (error90) { try { await memoryStore.deleteThread({ threadId: result.thread.id }); } catch (rollbackError) { this.logger.error("Failed to rollback cloned thread after OM clone failure", rollbackError); } throw error90; } } if (this.vector && config3.semanticRecall && result.clonedMessages.length > 0) { await this.embedClonedMessages(result.clonedMessages, config3); } return result; } /** * Clone observational memory records when cloning a thread. * Thread-scoped: always cloned to the new thread. * Resource-scoped: cloned only when the resourceId changes (same resourceId shares OM naturally). * All stored message/thread IDs are remapped to the cloned IDs. */ async cloneObservationalMemory(memoryStore, sourceThreadId, sourceResourceId, result) { let sourceOM = await memoryStore.getObservationalMemory(sourceThreadId, sourceResourceId); if (!sourceOM) { sourceOM = await memoryStore.getObservationalMemory(null, sourceResourceId); } if (!sourceOM) return; const clonedThreadId = result.thread.id; const clonedResourceId = result.thread.resourceId; const resourceChanged = clonedResourceId !== sourceResourceId; if (sourceOM.scope === "resource" && !resourceChanged) return; const messageIdMap = result.messageIdMap ?? {}; const hasher = await this.hasher; const cloned = this.remapObservationalMemoryRecord(sourceOM, { newThreadId: sourceOM.scope === "thread" ? clonedThreadId : null, newResourceId: clonedResourceId, messageIdMap, sourceThreadId: resourceChanged ? sourceThreadId : void 0, clonedThreadId: resourceChanged ? clonedThreadId : void 0, hasher: resourceChanged ? hasher : void 0 }); const now = /* @__PURE__ */ new Date(); cloned.id = crypto.randomUUID(); cloned.createdAt = now; cloned.updatedAt = now; await memoryStore.insertObservationalMemoryRecord(cloned); } /** * Create a remapped copy of an OM record with new thread/message IDs. */ remapObservationalMemoryRecord(record3, opts) { const { newThreadId, newResourceId, messageIdMap, sourceThreadId, clonedThreadId, hasher } = opts; const cloned = { ...record3 }; cloned.threadId = newThreadId; cloned.resourceId = newResourceId; if (Array.isArray(cloned.observedMessageIds)) { cloned.observedMessageIds = cloned.observedMessageIds.map((id) => messageIdMap[id]).filter((id) => Boolean(id)); } else { cloned.observedMessageIds = void 0; } if (Array.isArray(cloned.bufferedMessageIds)) { cloned.bufferedMessageIds = cloned.bufferedMessageIds.map((id) => messageIdMap[id]).filter((id) => Boolean(id)); } else { cloned.bufferedMessageIds = void 0; } if (Array.isArray(cloned.bufferedObservationChunks)) { cloned.bufferedObservationChunks = cloned.bufferedObservationChunks.map( (chunk) => ({ ...chunk, messageIds: Array.isArray(chunk.messageIds) ? chunk.messageIds.map((id) => messageIdMap[id]).filter((id) => Boolean(id)) : [] }) ); } else { cloned.bufferedObservationChunks = void 0; } if (sourceThreadId && clonedThreadId && hasher) { const sourceObscured = hasher.h32ToString(sourceThreadId); const clonedObscured = hasher.h32ToString(clonedThreadId); if (sourceObscured !== clonedObscured) { const replaceThreadTags = (text42) => { if (!text42) return text42; return text42.replaceAll(``, ``); }; cloned.activeObservations = replaceThreadTags(cloned.activeObservations) ?? ""; cloned.bufferedReflection = replaceThreadTags(cloned.bufferedReflection); if (cloned.bufferedObservationChunks) { cloned.bufferedObservationChunks = cloned.bufferedObservationChunks.map( (chunk) => ({ ...chunk, observations: replaceThreadTags(chunk.observations) ?? chunk.observations }) ); } } } cloned.isObserving = false; cloned.isReflecting = false; cloned.isBufferingObservation = false; cloned.isBufferingReflection = false; return cloned; } /** * Embed cloned messages for semantic recall. * This is similar to the embedding logic in saveMessages but operates on already-saved messages. */ async embedClonedMessages(messages, config3) { if (!this.vector || !this.embedder) { return; } const embeddingData = []; let dimension; await Promise.all( messages.map(async (message) => { let textForEmbedding = null; if (message.content?.content && typeof message.content.content === "string" && message.content.content.trim() !== "") { textForEmbedding = message.content.content; } else if (message.content?.parts && message.content.parts.length > 0) { const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim(); if (joined) textForEmbedding = joined; } if (!textForEmbedding) return; const result = await this.embedMessageContent(textForEmbedding); dimension = result.dimension; embeddingData.push({ embeddings: result.embeddings, metadata: result.chunks.map(() => ({ message_id: message.id, thread_id: message.threadId, resource_id: message.resourceId, role: message.role, content: textForEmbedding, created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt) })) }); }) ); if (embeddingData.length > 0 && dimension !== void 0) { const { indexName } = await this.createEmbeddingIndex(dimension, config3); const allVectors = []; const allMetadata = []; for (const data of embeddingData) { allVectors.push(...data.embeddings); allMetadata.push(...data.metadata); } await this.vector.upsert({ indexName, vectors: allVectors, metadata: allMetadata }); } } /** * Get the clone metadata from a thread if it was cloned from another thread. * * @param thread - The thread to check * @returns The clone metadata if the thread is a clone, null otherwise * * @example * ```typescript * const thread = await memory.getThreadById({ threadId: 'thread-123' }); * const cloneInfo = memory.getCloneMetadata(thread); * if (cloneInfo) { * console.log(`This thread was cloned from ${cloneInfo.sourceThreadId}`); * } * ``` */ getCloneMetadata(thread) { if (!thread?.metadata?.clone) { return null; } return thread.metadata.clone; } /** * Check if a thread is a clone of another thread. * * @param thread - The thread to check * @returns True if the thread is a clone, false otherwise * * @example * ```typescript * const thread = await memory.getThreadById({ threadId: 'thread-123' }); * if (memory.isClone(thread)) { * console.log('This is a cloned thread'); * } * ``` */ isClone(thread) { return this.getCloneMetadata(thread) !== null; } /** * Get the source thread that a cloned thread was created from. * * @param threadId - ID of the cloned thread * @returns The source thread if found, null if the thread is not a clone or source doesn't exist * * @example * ```typescript * const sourceThread = await memory.getSourceThread('cloned-thread-123'); * if (sourceThread) { * console.log(`Original thread: ${sourceThread.title}`); * } * ``` */ async getSourceThread(threadId) { const thread = await this.getThreadById({ threadId }); const cloneMetadata = this.getCloneMetadata(thread); if (!cloneMetadata) { return null; } return this.getThreadById({ threadId: cloneMetadata.sourceThreadId }); } /** * List all threads that were cloned from a specific source thread. * * @param sourceThreadId - ID of the source thread * @param resourceId - Optional resource ID to filter by * @returns Array of threads that are clones of the source thread * * @example * ```typescript * const clones = await memory.listClones('original-thread-123', 'user-456'); * console.log(`Found ${clones.length} clones of this thread`); * ``` */ async listClones(sourceThreadId, resourceId) { let targetResourceId = resourceId; if (!targetResourceId) { const sourceThread = await this.getThreadById({ threadId: sourceThreadId }); if (!sourceThread) { return []; } targetResourceId = sourceThread.resourceId; } const { threads } = await this.listThreads({ filter: { resourceId: targetResourceId }, perPage: false // Get all threads }); return threads.filter((thread) => { const cloneMetadata = this.getCloneMetadata(thread); return cloneMetadata?.sourceThreadId === sourceThreadId; }); } /** * Get the clone history chain for a thread (all ancestors back to the original). * * @param threadId - ID of the thread to get history for * @returns Array of threads from oldest ancestor to the given thread (inclusive) * * @example * ```typescript * const history = await memory.getCloneHistory('deeply-cloned-thread'); * // Returns: [originalThread, firstClone, secondClone, deeplyClonedThread] * ``` */ async getCloneHistory(threadId) { const history = []; let currentThreadId = threadId; while (currentThreadId) { const thread = await this.getThreadById({ threadId: currentThreadId }); if (!thread) { break; } history.unshift(thread); const cloneMetadata = this.getCloneMetadata(thread); currentThreadId = cloneMetadata?.sourceThreadId ?? null; } return history; } /** * Get input processors for this memory instance. * Extends the base implementation to add ObservationalMemory processor when configured. * * @param configuredProcessors - Processors already configured by the user (for deduplication) * @param context - Request context for runtime configuration * @returns Array of input processors configured for this memory instance */ async getInputProcessors(configuredProcessors = [], context2) { const processors = await super.getInputProcessors(configuredProcessors, context2); const om = await this.createOMProcessor(configuredProcessors, context2); if (om) { processors.push(om); } const wm = await this.createWorkingMemoryStateProcessor(configuredProcessors, context2); if (wm) { processors.push(wm); } return processors; } /** * Extends the base implementation to add ObservationalMemory as an output processor. * OM needs processOutputResult to save messages at the end of the agent turn, * even when the observation threshold was never reached during the loop. */ async getOutputProcessors(configuredProcessors = [], context2) { const processors = await super.getOutputProcessors(configuredProcessors, context2); const om = await this.createOMProcessor(configuredProcessors, context2); if (om) { processors.push(om); } return processors; } /** * Creates an ObservationalMemory processor wrapping the shared engine. * Returns null if OM is not configured, not supported, or already present * in the user's configured processors. */ async createOMProcessor(configuredProcessors = [], context2) { const hasObservationalMemory = configuredProcessors.some( (p) => !("workflow" in p) && p.id === "observational-memory" ); if (hasObservationalMemory) return null; const runtimeMemory = context2?.get("MastraMemory"); const runtimeObservationalMemory = normalizeObservationalMemoryConfig( runtimeMemory?.memoryConfig?.observationalMemory ); const threadConfig = runtimeObservationalMemory ? this.getMergedThreadConfig({ ...runtimeMemory?.memoryConfig, observationalMemory: runtimeObservationalMemory }) : this.threadConfig; const effectiveConfig = normalizeObservationalMemoryConfig(threadConfig.observationalMemory); if (!effectiveConfig) return null; const engine = await this.omEngine; if (!engine) return null; const { ObservationalMemoryProcessor } = await import('./observational-memory-Y5T2OR2Y-XDEBXWNA.cjs'); return new ObservationalMemoryProcessor(engine, this, { temporalMarkers: effectiveConfig.temporalMarkers }); } /** * Creates a WorkingMemoryStateProcessor when working memory is enabled and the * `useStateSignals` opt-in is set. Returns null otherwise or if the processor * is already present in the user's configured processors. */ async createWorkingMemoryStateProcessor(configuredProcessors = [], context2) { const runtimeMemory = context2?.get("MastraMemory"); const mergedConfig = this.getMergedThreadConfig(runtimeMemory?.memoryConfig); this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig); if (!mergedConfig.workingMemory?.enabled) return null; if (!mergedConfig.workingMemory?.useStateSignals) return null; const { WORKING_MEMORY_STATE_PROCESSOR_ID: WORKING_MEMORY_STATE_PROCESSOR_ID2, WorkingMemoryStateProcessor: WorkingMemoryStateProcessor2 } = await import('./working-memory-state-J7ASTNXX-WEIO7C67.cjs'); const alreadyConfigured = configuredProcessors.some( (p) => !("workflow" in p) && p.id === WORKING_MEMORY_STATE_PROCESSOR_ID2 ); if (alreadyConfigured) return null; return new WorkingMemoryStateProcessor2(this, runtimeMemory?.memoryConfig); } }; // ../agent-builder/dist/index.js var import_ignore = chunkO7I5CWRX_cjs.__toESM(require_ignore(), 1); var UNIT_KINDS = ["mcp-server", "tool", "workflow", "agent", "integration", "network", "other"]; var TemplateUnitSchema = zod.z.object({ kind: zod.z.enum(UNIT_KINDS), id: zod.z.string(), file: zod.z.string() }); zod.z.object({ slug: zod.z.string(), ref: zod.z.string().optional(), description: zod.z.string().optional(), units: zod.z.array(TemplateUnitSchema) }); var AgentBuilderInputSchema = zod.z.object({ repo: zod.z.string().describe("Git URL or local path of the template repo"), ref: zod.z.string().optional().describe("Tag/branch/commit to checkout (defaults to main/master)"), slug: zod.z.string().optional().describe("Slug for branch/scripts; defaults to inferred from repo"), targetPath: zod.z.string().optional().describe("Project path to merge into; defaults to current directory"), variables: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("Environment variables to set in .env file") }); zod.z.object({ slug: zod.z.string(), commitSha: zod.z.string(), templateDir: zod.z.string(), units: zod.z.array(TemplateUnitSchema) }); var CopiedFileSchema = zod.z.object({ source: zod.z.string(), destination: zod.z.string(), unit: zod.z.object({ kind: zod.z.enum(UNIT_KINDS), id: zod.z.string() }) }); var ConflictSchema = zod.z.object({ unit: zod.z.object({ kind: zod.z.enum(UNIT_KINDS), id: zod.z.string() }), issue: zod.z.string(), sourceFile: zod.z.string(), targetFile: zod.z.string() }); var FileCopyInputSchema = zod.z.object({ orderedUnits: zod.z.array(TemplateUnitSchema), templateDir: zod.z.string(), commitSha: zod.z.string(), slug: zod.z.string(), targetPath: zod.z.string().optional(), variables: zod.z.record(zod.z.string(), zod.z.string()).optional() }); var FileCopyResultSchema = zod.z.object({ success: zod.z.boolean(), copiedFiles: zod.z.array(CopiedFileSchema), conflicts: zod.z.array(ConflictSchema), message: zod.z.string(), error: zod.z.string().optional() }); var ConflictResolutionSchema = zod.z.object({ unit: zod.z.object({ kind: zod.z.enum(UNIT_KINDS), id: zod.z.string() }), issue: zod.z.string(), resolution: zod.z.string() }); var IntelligentMergeInputSchema = zod.z.object({ conflicts: zod.z.array(ConflictSchema), copiedFiles: zod.z.array(CopiedFileSchema), templateDir: zod.z.string(), commitSha: zod.z.string(), slug: zod.z.string(), targetPath: zod.z.string().optional(), branchName: zod.z.string().optional() }); var IntelligentMergeResultSchema = zod.z.object({ success: zod.z.boolean(), applied: zod.z.boolean(), message: zod.z.string(), conflictsResolved: zod.z.array(ConflictResolutionSchema), error: zod.z.string().optional() }); var ValidationResultsSchema = zod.z.object({ valid: zod.z.boolean(), errorsFixed: zod.z.number(), remainingErrors: zod.z.number(), errors: zod.z.array(zod.z.any()).optional() // Include specific validation errors }); var ValidationFixInputSchema = zod.z.object({ commitSha: zod.z.string(), slug: zod.z.string(), targetPath: zod.z.string().optional(), templateDir: zod.z.string(), orderedUnits: zod.z.array(TemplateUnitSchema), copiedFiles: zod.z.array(CopiedFileSchema), conflictsResolved: zod.z.array(ConflictResolutionSchema).optional(), maxIterations: zod.z.number().optional().default(5) }); var ValidationFixResultSchema = zod.z.object({ success: zod.z.boolean(), applied: zod.z.boolean(), message: zod.z.string(), validationResults: ValidationResultsSchema, error: zod.z.string().optional() }); var ApplyResultSchema = zod.z.object({ success: zod.z.boolean(), applied: zod.z.boolean(), branchName: zod.z.string().optional(), message: zod.z.string(), validationResults: ValidationResultsSchema.optional(), error: zod.z.string().optional(), errors: zod.z.array(zod.z.string()).optional(), stepResults: zod.z.object({ cloneSuccess: zod.z.boolean().optional(), analyzeSuccess: zod.z.boolean().optional(), discoverSuccess: zod.z.boolean().optional(), orderSuccess: zod.z.boolean().optional(), prepareBranchSuccess: zod.z.boolean().optional(), packageMergeSuccess: zod.z.boolean().optional(), installSuccess: zod.z.boolean().optional(), copySuccess: zod.z.boolean().optional(), mergeSuccess: zod.z.boolean().optional(), validationSuccess: zod.z.boolean().optional(), filesCopied: zod.z.number(), conflictsSkipped: zod.z.number(), conflictsResolved: zod.z.number() }).optional() }); var CloneTemplateResultSchema = zod.z.object({ templateDir: zod.z.string(), commitSha: zod.z.string(), slug: zod.z.string(), success: zod.z.boolean().optional(), error: zod.z.string().optional(), targetPath: zod.z.string().optional() }); var PackageAnalysisSchema = zod.z.object({ name: zod.z.string().optional(), version: zod.z.string().optional(), description: zod.z.string().optional(), dependencies: zod.z.record(zod.z.string(), zod.z.string()).optional(), devDependencies: zod.z.record(zod.z.string(), zod.z.string()).optional(), peerDependencies: zod.z.record(zod.z.string(), zod.z.string()).optional(), scripts: zod.z.record(zod.z.string(), zod.z.string()).optional(), success: zod.z.boolean().optional(), error: zod.z.string().optional() }); var DiscoveryResultSchema = zod.z.object({ units: zod.z.array(TemplateUnitSchema), success: zod.z.boolean().optional(), error: zod.z.string().optional() }); var OrderedUnitsSchema = zod.z.object({ orderedUnits: zod.z.array(TemplateUnitSchema), success: zod.z.boolean().optional(), error: zod.z.string().optional() }); var PackageMergeInputSchema = zod.z.object({ commitSha: zod.z.string(), slug: zod.z.string(), targetPath: zod.z.string().optional(), packageInfo: PackageAnalysisSchema }); var PackageMergeResultSchema = zod.z.object({ success: zod.z.boolean(), applied: zod.z.boolean(), message: zod.z.string(), error: zod.z.string().optional() }); var InstallInputSchema = zod.z.object({ targetPath: zod.z.string().optional().describe("Path to the project to install packages in") }); var InstallResultSchema = zod.z.object({ success: zod.z.boolean(), error: zod.z.string().optional() }); var PrepareBranchInputSchema = zod.z.object({ slug: zod.z.string(), commitSha: zod.z.string().optional(), // from clone-template if relevant targetPath: zod.z.string().optional() }); var PrepareBranchResultSchema = zod.z.object({ branchName: zod.z.string(), success: zod.z.boolean().optional(), error: zod.z.string().optional() }); var exec = util$1.promisify(child_process.exec); var execFile = util$1.promisify(child_process.execFile); function isInWorkspaceSubfolder(cwd) { try { const currentPackageJson = path.resolve(cwd, "package.json"); if (!fs.existsSync(currentPackageJson)) { return false; } let currentDir = cwd; let previousDir = ""; while (currentDir !== previousDir && currentDir !== "/") { previousDir = currentDir; currentDir = path.dirname(currentDir); if (currentDir === cwd) { continue; } console.info(`Checking for workspace indicators in: ${currentDir}`); if (fs.existsSync(path.resolve(currentDir, "pnpm-workspace.yaml"))) { return true; } const parentPackageJson = path.resolve(currentDir, "package.json"); if (fs.existsSync(parentPackageJson)) { try { const parentPkg = JSON.parse(fs.readFileSync(parentPackageJson, "utf-8")); if (parentPkg.workspaces) { return true; } } catch { } } if (fs.existsSync(path.resolve(currentDir, "lerna.json"))) { return true; } } return false; } catch (error90) { console.warn(`Error in workspace detection: ${error90}`); return false; } } function spawn(command, args, options) { return new Promise((resolve5, reject) => { const childProcess = child_process.spawn(command, args, { stdio: "inherit", // Enable proper stdio handling ...options }); childProcess.on("error", (error90) => { reject(error90); }); childProcess.on("close", (code) => { if (code === 0) { resolve5(void 0); } else { reject(new Error(`Command failed with exit code ${code}`)); } }); }); } async function isGitInstalled() { try { await spawnWithOutput("git", ["--version"], {}); return true; } catch { return false; } } async function isInsideGitRepo(cwd) { try { if (!await isGitInstalled()) return false; const { stdout } = await spawnWithOutput("git", ["rev-parse", "--is-inside-work-tree"], { cwd }); return stdout.trim() === "true"; } catch { return false; } } function spawnWithOutput(command, args, options) { return new Promise((resolvePromise, rejectPromise) => { const childProcess = child_process.spawn(command, args, { ...options }); let stdout = ""; let stderr = ""; childProcess.on("error", (error90) => { rejectPromise(error90); }); childProcess.stdout?.on("data", (chunk) => { process.stdout.write(chunk); stdout += chunk?.toString?.() ?? String(chunk); }); childProcess.stderr?.on("data", (chunk) => { stderr += chunk?.toString?.() ?? String(chunk); process.stderr.write(chunk); }); childProcess.on("close", (code) => { if (code === 0) { resolvePromise({ stdout, stderr, code: code ?? 0 }); } else { const err = new Error(stderr || `Command failed: ${command} ${args.join(" ")}`); err.code = code; rejectPromise(err); } }); }); } async function spawnSWPM(cwd, command, packageNames) { try { console.info("Running install command with swpm"); const swpmPath = module$1.createRequire(undefined).resolve("swpm"); await spawn(swpmPath, [command, ...packageNames], { cwd }); return; } catch (e2) { console.warn("Failed to run install command with swpm", e2); } try { let packageManager; if (fs.existsSync(path.resolve(cwd, "pnpm-lock.yaml"))) { packageManager = "pnpm"; } else if (fs.existsSync(path.resolve(cwd, "yarn.lock"))) { packageManager = "yarn"; } else { packageManager = "npm"; } let nativeCommand = command === "add" ? "add" : command === "install" ? "install" : command; const args = [nativeCommand]; if (nativeCommand === "install") { const inWorkspace = isInWorkspaceSubfolder(cwd); if (packageManager === "pnpm") { args.push("--force"); if (inWorkspace) { args.push("--ignore-workspace"); } } else if (packageManager === "npm") { args.push("--yes"); if (inWorkspace) { args.push("--ignore-workspaces"); } } } args.push(...packageNames); console.info(`Falling back to ${packageManager} ${args.join(" ")}`); await spawn(packageManager, args, { cwd }); return; } catch (e2) { console.warn(`Failed to run install command with native package manager: ${e2}`); } throw new Error(`Failed to run install command with swpm and native package managers`); } function kindWeight(kind) { const idx = UNIT_KINDS.indexOf(kind); return idx === -1 ? UNIT_KINDS.length : idx; } async function fetchMastraTemplates() { try { const response = await fetch("https://mastra.ai/api/templates.json"); const data = await response.json(); return data; } catch (error90) { throw new Error(`Failed to fetch Mastra templates: ${error90 instanceof Error ? error90.message : String(error90)}`); } } async function getMastraTemplate(slug) { const templates = await fetchMastraTemplates(); const template = templates.find((t) => t.slug === slug); if (!template) { throw new Error(`Template "${slug}" not found. Available templates: ${templates.map((t) => t.slug).join(", ")}`); } return template; } async function logGitState(targetPath, label) { try { if (!await isInsideGitRepo(targetPath)) return; const gitStatusResult = await git(targetPath, "status", "--porcelain"); const gitLogResult = await git(targetPath, "log", "--oneline", "-3"); const gitCountResult = await git(targetPath, "rev-list", "--count", "HEAD"); console.info(`\u{1F4CA} Git state ${label}:`); console.info("Status:", gitStatusResult.stdout.trim() || "Clean working directory"); console.info("Recent commits:", gitLogResult.stdout.trim()); console.info("Total commits:", gitCountResult.stdout.trim()); } catch (gitError) { console.warn(`Could not get git state ${label}:`, gitError); } } async function git(cwd, ...args) { const { stdout, stderr } = await spawnWithOutput("git", args, { cwd }); return { stdout: stdout ?? "", stderr: stderr ?? "" }; } async function gitClone(repo, destDir, cwd) { await git(process.cwd(), "clone", repo, destDir); } async function gitCheckoutRef(cwd, ref) { if (!await isInsideGitRepo(cwd)) return; await git(cwd, "checkout", ref); } async function gitRevParse(cwd, rev) { if (!await isInsideGitRepo(cwd)) return ""; const { stdout } = await git(cwd, "rev-parse", rev); return stdout.trim(); } async function gitAddFiles(cwd, files) { if (!files || files.length === 0) return; if (!await isInsideGitRepo(cwd)) return; await git(cwd, "add", ...files); } async function gitAddAll(cwd) { if (!await isInsideGitRepo(cwd)) return; await git(cwd, "add", "."); } async function gitHasStagedChanges(cwd) { if (!await isInsideGitRepo(cwd)) return false; const { stdout } = await git(cwd, "diff", "--cached", "--name-only"); return stdout.trim().length > 0; } async function gitCommit(cwd, message, opts) { try { if (!await isInsideGitRepo(cwd)) return false; if (opts?.skipIfNoStaged) { const has = await gitHasStagedChanges(cwd); if (!has) return false; } const args = ["commit", "-m", message]; if (opts?.allowEmpty) args.push("--allow-empty"); await git(cwd, ...args); return true; } catch (e2) { const msg = e2 instanceof Error ? e2.message : String(e2); if (/nothing to commit/i.test(msg) || /no changes added to commit/i.test(msg)) { return false; } throw e2; } } async function gitAddAndCommit(cwd, message, files, opts) { try { if (!await isInsideGitRepo(cwd)) return false; if (files && files.length > 0) { await gitAddFiles(cwd, files); } else { await gitAddAll(cwd); } return gitCommit(cwd, message, opts); } catch (e2) { console.error(`Failed to add and commit files: ${e2 instanceof Error ? e2.message : String(e2)}`); return false; } } async function gitCheckoutBranch(branchName, targetPath) { try { if (!await isInsideGitRepo(targetPath)) return; await git(targetPath, "checkout", "-b", branchName); console.info(`Created new branch: ${branchName}`); } catch (error90) { const errorStr = error90 instanceof Error ? error90.message : String(error90); if (errorStr.includes("already exists")) { try { await git(targetPath, "checkout", branchName); console.info(`Switched to existing branch: ${branchName}`); } catch { const timestamp = Date.now().toString().slice(-6); const uniqueBranchName = `${branchName}-${timestamp}`; await git(targetPath, "checkout", "-b", uniqueBranchName); console.info(`Created unique branch: ${uniqueBranchName}`); } } else { throw error90; } } } async function backupAndReplaceFile(sourceFile, targetFile) { const backupFile = `${targetFile}.backup-${Date.now()}`; await promises.copyFile(targetFile, backupFile); console.info(`\u{1F4E6} Created backup: ${path.basename(backupFile)}`); await promises.copyFile(sourceFile, targetFile); console.info(`\u{1F504} Replaced file with template version (backup created)`); } async function renameAndCopyFile(sourceFile, targetFile) { let counter = 1; let uniqueTargetFile = targetFile; const baseName = path.basename(targetFile, path.extname(targetFile)); const extension = path.extname(targetFile); const directory = path.dirname(targetFile); while (fs.existsSync(uniqueTargetFile)) { const uniqueName = `${baseName}.template-${counter}${extension}`; uniqueTargetFile = path.resolve(directory, uniqueName); counter++; } await promises.copyFile(sourceFile, uniqueTargetFile); console.info(`\u{1F4DD} Copied with unique name: ${path.basename(uniqueTargetFile)}`); return uniqueTargetFile; } var isValidMastraLanguageModel = (model) => { return model && typeof model === "object" && typeof model.modelId === "string"; }; var resolveTargetPath = (inputData, requestContext) => { if (inputData.targetPath) { return inputData.targetPath; } const contextPath = requestContext.get("targetPath"); if (contextPath) { return contextPath; } const envRoot = process.env.MASTRA_PROJECT_ROOT?.trim(); if (envRoot) { return envRoot; } const cwd = process.cwd(); const parent = path.dirname(cwd); const grand = path.dirname(parent); if (path.basename(cwd) === "output" && path.basename(parent) === ".mastra") { return grand; } return cwd; }; var mergeGitignoreFiles = (targetContent, templateContent, templateSlug) => { const targetLines = targetContent.replace(/\r\n/g, "\n").split("\n"); const templateLines = templateContent.replace(/\r\n/g, "\n").split("\n"); const existingEntries = /* @__PURE__ */ new Set(); for (const line of targetLines) { const trimmed = line.trim(); if (trimmed && !trimmed.startsWith("#")) { const normalized = trimmed.replace(/^\.\//, "").replace(/\\/g, "/"); existingEntries.add(normalized); } } const newEntries = []; for (const line of templateLines) { const trimmed = line.trim(); if (trimmed && !trimmed.startsWith("#")) { const normalized = trimmed.replace(/^\.\//, "").replace(/\\/g, "/"); if (!existingEntries.has(normalized)) { const isNegation = normalized.startsWith("!"); const basePath = isNegation ? normalized.slice(1) : normalized; const hasConflict = isNegation ? existingEntries.has(basePath) : existingEntries.has("!" + basePath); if (!hasConflict) { newEntries.push(trimmed); } else { console.info(`\u26A0 Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`); } } } } if (newEntries.length === 0) { return targetContent; } const result = [...targetLines]; const lastLine = result[result.length - 1]; if (result.length > 0 && lastLine && lastLine.trim() !== "") { result.push(""); } result.push(`# Added by template: ${templateSlug}`); result.push(...newEntries); return result.join("\n"); }; var mergeEnvFiles = (targetContent, templateVariables, templateSlug) => { const targetLines = targetContent.replace(/\r\n/g, "\n").split("\n"); const existingVars = /* @__PURE__ */ new Set(); for (const line of targetLines) { const trimmed = line.trim(); if (trimmed && !trimmed.startsWith("#")) { const equalIndex = trimmed.indexOf("="); if (equalIndex > 0) { const varName = trimmed.substring(0, equalIndex).trim(); existingVars.add(varName); } } } const newVars = []; for (const [key, value] of Object.entries(templateVariables)) { if (!existingVars.has(key)) { newVars.push({ key, value }); } else { console.info(`\u26A0 Skipping existing environment variable: ${key} (already exists in .env)`); } } if (newVars.length === 0) { return targetContent; } const result = [...targetLines]; const lastLine = result[result.length - 1]; if (result.length > 0 && lastLine && lastLine.trim() !== "") { result.push(""); } result.push(`# Added by template: ${templateSlug}`); for (const { key, value } of newVars) { result.push(`${key}=${value}`); } return result.join("\n"); }; var detectAISDKVersion = async (projectPath) => { try { const packageJsonPath = path.join(projectPath, "package.json"); if (!fs.existsSync(packageJsonPath)) { console.info("No package.json found, defaulting to v2"); return "v2"; } const packageContent = await promises.readFile(packageJsonPath, "utf-8"); const packageJson = JSON.parse(packageContent); const allDeps = { ...packageJson.dependencies, ...packageJson.devDependencies, ...packageJson.peerDependencies }; const providerPackages = ["@ai-sdk/openai", "@ai-sdk/anthropic", "@ai-sdk/google", "@ai-sdk/groq", "@ai-sdk/xai"]; for (const pkg of providerPackages) { const version3 = allDeps[pkg]; if (version3) { const versionMatch = version3.match(/(\d+)/); if (versionMatch) { const majorVersion = parseInt(versionMatch[1]); if (majorVersion >= 2) { console.info(`Detected ${pkg} v${majorVersion} -> using v2 specification`); return "v2"; } else { console.info(`Detected ${pkg} v${majorVersion} -> using v1 specification`); return "v1"; } } } } console.info("No AI SDK version detected, defaulting to v2"); return "v2"; } catch (error90) { console.warn(`Failed to detect AI SDK version: ${error90 instanceof Error ? error90.message : String(error90)}`); return "v2"; } }; var createModelInstance = async (provider, modelId, version3 = "v2") => { try { const providerMap = { v1: { openai: async () => { const { openai: openai2 } = await import('./dist-NYM3IQLY.cjs'); return openai2(modelId); }, anthropic: async () => { const { anthropic } = await import('./dist-CIZY7VDE.cjs'); return anthropic(modelId); }, groq: async () => { const { groq } = await import('./dist-6VCC76Q3.cjs'); return groq(modelId); }, xai: async () => { const { xai } = await import('./dist-M3P3YMJP.cjs'); return xai(modelId); }, google: async () => { const { google } = await import('./dist-WBYMZPKB.cjs'); return google(modelId); } } }; const providerFn = version3 === `v1` ? providerMap[version3][provider] : () => new llm.ModelRouterLanguageModel(`${provider}/${modelId}`); if (!providerFn) { console.error(`Unsupported provider: ${provider}`); return null; } const modelInstance = await providerFn(); console.info(`Created ${provider} model instance (${version3}): ${modelId}`); return modelInstance; } catch (error90) { console.error(`Failed to create model instance: ${error90 instanceof Error ? error90.message : String(error90)}`); return null; } }; var resolveModel = async ({ requestContext, defaultModel = "openai/gpt-4.1", projectPath }) => { const modelFromContext = requestContext.get("model"); if (modelFromContext) { console.info("Using model from request context"); if (isValidMastraLanguageModel(modelFromContext)) { return modelFromContext; } throw new Error( 'Invalid model provided. Model must be a MastraLanguageModel instance (e.g., openai("gpt-4"), anthropic("claude-3-5-sonnet"), etc.)' ); } const selectedModel = requestContext.get("selectedModel"); if (selectedModel?.provider && selectedModel?.modelId && projectPath) { console.info(`Resolving selected model: ${selectedModel.provider}/${selectedModel.modelId}`); const version3 = await detectAISDKVersion(projectPath); const modelInstance = await createModelInstance(selectedModel.provider, selectedModel.modelId, version3); if (modelInstance) { requestContext.set("model", modelInstance); return modelInstance; } } console.info("Using default model"); return typeof defaultModel === `string` ? new llm.ModelRouterLanguageModel(defaultModel) : defaultModel; }; var AgentBuilderDefaults = class _AgentBuilderDefaults { static DEFAULT_INSTRUCTIONS = (projectPath) => `You are a Mastra Expert Agent, specialized in building production-ready AI applications using the Mastra framework. You excel at creating agents, tools, workflows, and complete applications with real, working implementations. ## Core Identity & Capabilities **Primary Role:** Transform natural language requirements into working Mastra applications **Key Strength:** Deep knowledge of Mastra patterns, conventions, and best practices **Output Quality:** Production-ready code that follows Mastra ecosystem standards ## Workflow: The MASTRA Method Follow this sequence for every coding task: IF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT DO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE ### 1. \u{1F50D} **UNDERSTAND** (Information Gathering) - **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs - **Analyze Project**: Use file exploration to understand existing codebase structure - **Web Research**: Search for packages, examples, or solutions when docs are insufficient - **Clarify Requirements**: Ask targeted questions only when critical information is missing ### 2. \u{1F4CB} **PLAN** (Strategy & Design) - **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory) - **Dependencies**: Identify required packages and Mastra components - **Integration**: Plan how to integrate with existing project structure - **Validation**: Define how to test and verify the implementation ### 3. \u{1F6E0}\uFE0F **BUILD** (Implementation) - **Install First**: Use \`manageProject\` tool to install required packages - **Follow Patterns**: Implement using established Mastra conventions - **Real Code Only**: Build actual working functionality, never mock implementations - **Environment Setup**: Create proper .env configuration and documentation ### 4. \u2705 **VALIDATE** (Quality Assurance) - **Code Validation**: Run \`validateCode\` with types and lint checks - **Testing**: Execute tests if available - **Server Testing**: Use \`manageServer\` and \`httpRequest\` for API validation - **Fix Issues**: Address all errors before completion ## Mastra-Specific Guidelines ### Framework Knowledge - **Agents**: Use \`@mastra/core/agent\` with proper configuration - **Tools**: Create tools with \`@mastra/core/tools\` and proper schemas - **Memory**: Implement memory with \`@mastra/memory\` and appropriate processors - **Workflows**: Build workflows with \`@mastra/core/workflows\` - **Integrations**: Leverage Mastra's extensive integration ecosystem ### Code Standards - **TypeScript First**: All code must be properly typed - **Zod Schemas**: Use Zod for all data validation - **Environment Variables**: Proper .env configuration with examples - **Error Handling**: Comprehensive error handling with meaningful messages - **Security**: Never expose credentials or sensitive data ### Project Structure - Follow Mastra project conventions (\`src/mastra/\`, config files) - Use proper file organization (agents, tools, workflows in separate directories) - Maintain consistent naming conventions - Include proper exports and imports ## Communication Style **Conciseness**: Keep responses focused and actionable **Clarity**: Explain complex concepts in simple terms **Directness**: State what you're doing and why **No Fluff**: Avoid unnecessary explanations or apologies ### Response Format 1. **Brief Status**: One line stating what you're doing 2. **Tool Usage**: Execute necessary tools 3. **Results Summary**: Concise summary of what was accomplished 4. **Next Steps**: Clear indication of completion or next actions ## Tool Usage Strategy ### File Operations - **Project-Relative Paths**: All file paths are resolved relative to the project directory (unless absolute paths are used) - **Read First**: Always read files before editing to understand context - **Precise Edits**: Use exact text matching for search/replace operations - **Batch Operations**: Group related file operations when possible ### Project Management - **manageProject**: Use for package installation, project creation, dependency management - **validateCode**: Always run after code changes to ensure quality - **manageServer**: Use for testing Mastra server functionality - **httpRequest**: Test API endpoints and integrations ### Information Gathering - **Mastra Docs**: Primary source for Mastra-specific information - **Web Search**: Secondary source for packages and external solutions - **File Exploration**: Understand existing project structure and patterns ## Error Handling & Recovery ### Validation Failures - Fix TypeScript errors immediately - Address linting issues systematically - Re-validate until clean ### Build Issues - Check dependencies and versions - Verify Mastra configuration - Test in isolation when needed ### Integration Problems - Verify API keys and environment setup - Test connections independently - Debug with logging and error messages ## Security & Best Practices **Never:** - Hard-code API keys or secrets - Generate mock or placeholder implementations - Skip error handling - Ignore TypeScript errors - Create insecure code patterns - ask for file paths, you should be able to use the provided tools to explore the file system **Always:** - Use environment variables for configuration - Implement proper input validation - Follow security best practices - Create complete, working implementations - Test thoroughly before completion ## Output Requirements ### Code Quality - \u2705 TypeScript compilation passes - \u2705 ESLint validation passes - \u2705 Proper error handling implemented - \u2705 Environment variables configured - \u2705 Tests included when appropriate ### Documentation - \u2705 Clear setup instructions - \u2705 Environment variable documentation - \u2705 Usage examples provided - \u2705 API documentation for custom tools ### Integration - \u2705 Follows Mastra conventions - \u2705 Integrates with existing project - \u2705 Proper imports and exports - \u2705 Compatible with Mastra ecosystem ## Project Context **Working Directory**: ${projectPath} **Focus**: Mastra framework applications **Goal**: Production-ready implementations Remember: You are building real applications, not prototypes. Every implementation should be complete, secure, and ready for production use. ## Enhanced Tool Set You have access to an enhanced set of tools based on production coding agent patterns: ### Task Management - **taskManager**: Create and track multi-step coding tasks with states (pending, in_progress, completed, blocked). Use this for complex projects that require systematic progress tracking. ### Code Discovery & Analysis - **codeAnalyzer**: Analyze codebase structure, discover definitions (functions, classes, interfaces), map dependencies, and understand architectural patterns. - **smartSearch**: Intelligent search with context awareness, pattern matching, and relevance scoring. ### Advanced File Operations - **readFile**: Read files with optional line ranges, encoding support, metadata - **writeFile**: Write files with directory creation - **listDirectory**: Directory listing with filtering, recursion, metadata - **multiEdit**: Perform multiple search-replace operations across files atomically with backup creation - **executeCommand**: Execute shell commands with proper error handling and working directory support **Important**: All file paths are resolved relative to the project directory unless absolute paths are provided. ### Communication & Workflow - **attemptCompletion**: Signal task completion with validation status and confidence metrics. ### Guidelines for Enhanced Tools: 1. **Use taskManager proactively** for any task requiring 3+ steps or complex coordination 2. **Start with codeAnalyzer** when working with unfamiliar codebases to understand structure 3. **Use smartSearch** for intelligent pattern discovery across the codebase 4. **Apply multiEdit** for systematic refactoring across multiple files 5. **Ask for clarification** when requirements are ambiguous rather than making assumptions 6. **Signal completion** with comprehensive summaries and validation status Use the following basic examples to guide your implementation. ### Weather Agent \`\`\` // ./src/agents/weather-agent.ts import { openai } from '@ai-sdk/openai'; import { Agent } from '@mastra/core/agent'; import { Memory } from '@mastra/memory'; import { LibSQLStore } from '@mastra/libsql'; import { weatherTool } from '../tools/weather-tool'; export const weatherAgent = new Agent({ id: 'weather-agent', name: 'Weather Agent', instructions: \${instructions}, model: openai('gpt-4o-mini'), tools: { weatherTool }, memory: new Memory({ storage: new LibSQLStore({ id: 'mastra-memory-storage', url: 'file:../mastra.db', // ask user what database to use, use this as the default }), }), }); \`\`\` ### Weather Tool \`\`\` // ./src/tools/weather-tool.ts import { createTool } from '@mastra/core/tools'; import { z } from 'zod'; import { getWeather } from '../tools/weather-tool'; export const weatherTool = createTool({ id: 'get-weather', description: 'Get current weather for a location', inputSchema: z.object({ location: z.string().describe('City name'), }), outputSchema: z.object({ temperature: z.number(), feelsLike: z.number(), humidity: z.number(), windSpeed: z.number(), windGust: z.number(), conditions: z.string(), location: z.string(), }), execute: async (inputData) => { return await getWeather(inputData.location); }, }); \`\`\` ### Weather Workflow \`\`\` // ./src/workflows/weather-workflow.ts import { createStep, createWorkflow } from '@mastra/core/workflows'; import { z } from 'zod'; const fetchWeather = createStep({ id: 'fetch-weather', description: 'Fetches weather forecast for a given city', inputSchema: z.object({ city: z.string().describe('The city to get the weather for'), }), outputSchema: forecastSchema, execute: async (inputData) => { if (!inputData) { throw new Error('Input data not found'); } const geocodingUrl = \`https://geocoding-api.open-meteo.com/v1/search?name=\${encodeURIComponent(inputData.city)}&count=1\`; const geocodingResponse = await fetch(geocodingUrl); const geocodingData = (await geocodingResponse.json()) as { results: { latitude: number; longitude: number; name: string }[]; }; if (!geocodingData.results?.[0]) { throw new Error(\`Location '\${inputData.city}' not found\`); } const { latitude, longitude, name } = geocodingData.results[0]; const weatherUrl = \`https://api.open-meteo.com/v1/forecast?latitude=\${latitude}&longitude=\${longitude}¤t=precipitation,weathercode&timezone=auto,&hourly=precipitation_probability,temperature_2m\` const response = await fetch(weatherUrl); const data = (await response.json()) as { current: { time: string; precipitation: number; weathercode: number; }; hourly: { precipitation_probability: number[]; temperature_2m: number[]; }; }; const forecast = { date: new Date().toISOString(), maxTemp: Math.max(...data.hourly.temperature_2m), minTemp: Math.min(...data.hourly.temperature_2m), condition: getWeatherCondition(data.current.weathercode), precipitationChance: data.hourly.precipitation_probability.reduce( (acc, curr) => Math.max(acc, curr), 0, ), location: name, }; return forecast; }, }); const planActivities = createStep({ id: 'plan-activities', description: 'Suggests activities based on weather conditions', inputSchema: forecastSchema, outputSchema: z.object({ activities: z.string(), }), execute: async (inputData, context) => { const mastra = context?.mastra; const forecast = inputData; if (!forecast) { throw new Error('Forecast data not found'); } const agent = mastra?.getAgent('weatherAgent'); if (!agent) { throw new Error('Weather agent not found'); } const prompt = \${weatherWorkflowPrompt} const response = await agent.stream([ { role: 'user', content: prompt, }, ]); let activitiesText = ''; for await (const chunk of response.textStream) { process.stdout.write(chunk); activitiesText += chunk; } return { activities: activitiesText, }; }, }); const weatherWorkflow = createWorkflow({ id: 'weather-workflow', inputSchema: z.object({ city: z.string().describe('The city to get the weather for'), }), outputSchema: z.object({ activities: z.string(), }), }) .then(fetchWeather) .then(planActivities); weatherWorkflow.commit(); \`\`\` export { weatherWorkflow }; \`\`\` ### Mastra instance \`\`\` // ./src/mastra.ts import { Mastra } from '@mastra/core/mastra'; import { PinoLogger } from '@mastra/loggers'; import { LibSQLStore } from '@mastra/libsql'; import { weatherWorkflow } from './workflows/weather-workflow'; import { weatherAgent } from './agents/weather-agent'; export const mastra = new Mastra({ workflows: { weatherWorkflow }, agents: { weatherAgent }, storage: new LibSQLStore({ id: 'mastra-storage', // stores observability, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db url: ":memory:", }), logger: new PinoLogger({ name: 'Mastra', level: 'info', }), }); \`\`\` `; static DEFAULT_MEMORY_CONFIG = { lastMessages: 20 }; static DEFAULT_FOLDER_STRUCTURE = { agent: "src/mastra/agents", workflow: "src/mastra/workflows", tool: "src/mastra/tools", "mcp-server": "src/mastra/mcp", network: "src/mastra/networks" }; static DEFAULT_TOOLS = async (projectPath) => { return { readFile: tools.createTool({ id: "read-file", description: "Read contents of a file with optional line range selection.", inputSchema: zod.z.object({ filePath: zod.z.string().describe("Path to the file to read"), startLine: zod.z.number().optional().describe("Starting line number (1-indexed)"), endLine: zod.z.number().optional().describe("Ending line number (1-indexed, inclusive)"), encoding: zod.z.string().default("utf-8").describe("File encoding") }), outputSchema: zod.z.object({ success: zod.z.boolean(), content: zod.z.string().optional(), lines: zod.z.array(zod.z.string()).optional(), metadata: zod.z.object({ size: zod.z.number(), totalLines: zod.z.number(), encoding: zod.z.string(), lastModified: zod.z.string() }).optional(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { return await _AgentBuilderDefaults.readFile({ ...inputData, projectPath }); } }), writeFile: tools.createTool({ id: "write-file", description: "Write content to a file, with options for creating directories.", inputSchema: zod.z.object({ filePath: zod.z.string().describe("Path to the file to write"), content: zod.z.string().describe("Content to write to the file"), createDirs: zod.z.boolean().default(true).describe("Create parent directories if they don't exist"), encoding: zod.z.string().default("utf-8").describe("File encoding") }), outputSchema: zod.z.object({ success: zod.z.boolean(), filePath: zod.z.string(), bytesWritten: zod.z.number().optional(), message: zod.z.string(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { return await _AgentBuilderDefaults.writeFile({ ...inputData, projectPath }); } }), listDirectory: tools.createTool({ id: "list-directory", description: "List contents of a directory with filtering and metadata options.", inputSchema: zod.z.object({ path: zod.z.string().describe("Directory path to list"), recursive: zod.z.boolean().default(false).describe("List subdirectories recursively"), includeHidden: zod.z.boolean().default(false).describe("Include hidden files and directories"), pattern: zod.z.string().default("*").describe("Glob pattern to filter files"), maxDepth: zod.z.number().default(10).describe("Maximum recursion depth"), includeMetadata: zod.z.boolean().default(true).describe("Include file metadata") }), outputSchema: zod.z.object({ success: zod.z.boolean(), items: zod.z.array( zod.z.object({ name: zod.z.string(), path: zod.z.string(), type: zod.z.enum(["file", "directory", "symlink"]), size: zod.z.number().optional(), lastModified: zod.z.string().optional(), permissions: zod.z.string().optional() }) ), totalItems: zod.z.number(), path: zod.z.string(), message: zod.z.string(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { return await _AgentBuilderDefaults.listDirectory({ ...inputData, projectPath }); } }), executeCommand: tools.createTool({ id: "execute-command", description: "Execute shell commands with proper error handling and output capture.", inputSchema: zod.z.object({ command: zod.z.string().describe("Shell command to execute"), workingDirectory: zod.z.string().optional().describe("Working directory for command execution"), timeout: zod.z.number().default(3e4).describe("Timeout in milliseconds"), captureOutput: zod.z.boolean().default(true).describe("Capture command output"), shell: zod.z.string().optional().describe("Shell to use (defaults to system shell)"), env: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("Environment variables") }), outputSchema: zod.z.object({ success: zod.z.boolean(), exitCode: zod.z.number().optional(), stdout: zod.z.string().optional(), stderr: zod.z.string().optional(), command: zod.z.string(), workingDirectory: zod.z.string().optional(), executionTime: zod.z.number().optional(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { return await _AgentBuilderDefaults.executeCommand({ ...inputData, workingDirectory: inputData.workingDirectory || projectPath, env: inputData.env }); } }), // Enhanced Task Management (Critical for complex coding tasks) taskManager: tools.createTool({ id: "task-manager", description: "Create and manage structured task lists for coding sessions. Use this for complex multi-step tasks to track progress and ensure thoroughness.", inputSchema: zod.z.object({ action: zod.z.enum(["create", "update", "list", "complete", "remove"]).describe("Task management action"), tasks: zod.z.array( zod.z.object({ id: zod.z.string().describe("Unique task identifier"), content: zod.z.string().describe("Task description, optional if just updating the status").optional(), status: zod.z.enum(["pending", "in_progress", "completed", "blocked"]).describe("Task status"), priority: zod.z.enum(["high", "medium", "low"]).default("medium").describe("Task priority"), dependencies: zod.z.array(zod.z.string()).optional().describe("IDs of tasks this depends on"), notes: zod.z.string().optional().describe("Additional notes or context") }) ).optional().describe("Tasks to create or update"), taskId: zod.z.string().optional().describe("Specific task ID for single task operations") }), outputSchema: zod.z.object({ success: zod.z.boolean(), tasks: zod.z.array( zod.z.object({ id: zod.z.string(), content: zod.z.string(), status: zod.z.string(), priority: zod.z.string(), dependencies: zod.z.array(zod.z.string()).optional(), notes: zod.z.string().optional(), createdAt: zod.z.string(), updatedAt: zod.z.string() }) ), message: zod.z.string() }), execute: async (inputData) => { return await _AgentBuilderDefaults.manageTaskList(inputData); } }), // Advanced File Operations multiEdit: tools.createTool({ id: "multi-edit", description: "Perform multiple search-replace operations on one or more files in a single atomic operation.", inputSchema: zod.z.object({ operations: zod.z.array( zod.z.object({ filePath: zod.z.string().describe("Path to the file to edit"), edits: zod.z.array( zod.z.object({ oldString: zod.z.string().describe("Exact text to replace"), newString: zod.z.string().describe("Replacement text"), replaceAll: zod.z.boolean().default(false).describe("Replace all occurrences") }) ).describe("List of edit operations for this file") }) ).describe("File edit operations to perform"), createBackup: zod.z.boolean().default(false).describe("Create backup files before editing") }), outputSchema: zod.z.object({ success: zod.z.boolean(), results: zod.z.array( zod.z.object({ filePath: zod.z.string(), editsApplied: zod.z.number(), errors: zod.z.array(zod.z.string()), backup: zod.z.string().optional() }) ), message: zod.z.string() }), execute: async (inputData) => { return await _AgentBuilderDefaults.performMultiEdit({ ...inputData, projectPath }); } }), replaceLines: tools.createTool({ id: "replace-lines", description: "Replace specific line ranges in files with new content. IMPORTANT: This tool replaces ENTIRE lines, not partial content within lines. Lines are 1-indexed.", inputSchema: zod.z.object({ filePath: zod.z.string().describe("Path to the file to edit"), startLine: zod.z.number().describe("Starting line number to replace (1-indexed, inclusive). Count from the first line = 1"), endLine: zod.z.number().describe( "Ending line number to replace (1-indexed, inclusive). To replace single line, use same number as startLine" ), newContent: zod.z.string().describe( 'New content to replace the lines with. Use empty string "" to delete lines completely. For multiline content, include \\n characters' ), createBackup: zod.z.boolean().default(false).describe("Create backup file before editing") }), outputSchema: zod.z.object({ success: zod.z.boolean(), message: zod.z.string(), linesReplaced: zod.z.number().optional(), backup: zod.z.string().optional(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { return await _AgentBuilderDefaults.replaceLines({ ...inputData, projectPath }); } }), // File diagnostics tool to help debug line replacement issues showFileLines: tools.createTool({ id: "show-file-lines", description: "Show specific lines from a file with line numbers. Useful for debugging before using replaceLines.", inputSchema: zod.z.object({ filePath: zod.z.string().describe("Path to the file to examine"), startLine: zod.z.number().optional().describe("Starting line number to show (1-indexed). If not provided, shows all lines"), endLine: zod.z.number().optional().describe( "Ending line number to show (1-indexed, inclusive). If not provided but startLine is, shows only that line" ), context: zod.z.number().default(2).describe("Number of context lines to show before and after the range") }), outputSchema: zod.z.object({ success: zod.z.boolean(), lines: zod.z.array( zod.z.object({ lineNumber: zod.z.number(), content: zod.z.string(), isTarget: zod.z.boolean().describe("Whether this line is in the target range") }) ), totalLines: zod.z.number(), message: zod.z.string(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { return await _AgentBuilderDefaults.showFileLines({ ...inputData, projectPath }); } }), // Enhanced Pattern Search smartSearch: tools.createTool({ id: "smart-search", description: "Intelligent search across codebase with context awareness and pattern matching.", inputSchema: zod.z.object({ query: zod.z.string().describe("Search query or pattern"), type: zod.z.enum(["text", "regex", "fuzzy", "semantic"]).default("text").describe("Type of search to perform"), scope: zod.z.object({ paths: zod.z.array(zod.z.string()).optional().describe("Specific paths to search"), fileTypes: zod.z.array(zod.z.string()).optional().describe("File extensions to include"), excludePaths: zod.z.array(zod.z.string()).optional().describe("Paths to exclude"), maxResults: zod.z.number().default(50).describe("Maximum number of results") }).optional(), context: zod.z.object({ beforeLines: zod.z.number().default(2).describe("Lines of context before match"), afterLines: zod.z.number().default(2).describe("Lines of context after match"), includeDefinitions: zod.z.boolean().default(false).describe("Include function/class definitions") }).optional() }), outputSchema: zod.z.object({ success: zod.z.boolean(), matches: zod.z.array( zod.z.object({ file: zod.z.string(), line: zod.z.number(), column: zod.z.number().optional(), match: zod.z.string(), context: zod.z.object({ before: zod.z.array(zod.z.string()), after: zod.z.array(zod.z.string()) }), relevance: zod.z.number().optional() }) ), summary: zod.z.object({ totalMatches: zod.z.number(), filesSearched: zod.z.number(), patterns: zod.z.array(zod.z.string()) }) }), execute: async (inputData) => { return await _AgentBuilderDefaults.performSmartSearch(inputData, projectPath); } }), validateCode: tools.createTool({ id: "validate-code", description: "Validates code using a fast hybrid approach: syntax \u2192 semantic \u2192 lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.", inputSchema: zod.z.object({ projectPath: zod.z.string().optional().describe("Path to the project to validate (defaults to current project)"), validationType: zod.z.array(zod.z.enum(["types", "lint", "schemas", "tests", "build"])).describe('Types of validation to perform. Recommended: ["types", "lint"] for code quality'), files: zod.z.array(zod.z.string()).optional().describe( "RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check \u2192 semantic types \u2192 ESLint. Without files, falls back to slower CLI validation." ) }), outputSchema: zod.z.object({ valid: zod.z.boolean(), errors: zod.z.array( zod.z.object({ type: zod.z.enum(["typescript", "eslint", "schema", "test", "build"]), severity: zod.z.enum(["error", "warning", "info"]), message: zod.z.string(), file: zod.z.string().optional(), line: zod.z.number().optional(), column: zod.z.number().optional(), code: zod.z.string().optional() }) ), summary: zod.z.object({ totalErrors: zod.z.number(), totalWarnings: zod.z.number(), validationsPassed: zod.z.array(zod.z.string()), validationsFailed: zod.z.array(zod.z.string()) }) }), execute: async (inputData) => { const { projectPath: validationProjectPath, validationType, files } = inputData; const targetPath = validationProjectPath || projectPath; return await _AgentBuilderDefaults.validateCode({ projectPath: targetPath, validationType, files }); } }), // Web Search (replaces MCP web search) webSearch: tools.createTool({ id: "web-search", description: "Search the web for current information and return structured results.", inputSchema: zod.z.object({ query: zod.z.string().describe("Search query"), maxResults: zod.z.number().default(10).describe("Maximum number of results to return"), region: zod.z.string().default("us").describe("Search region/country code"), language: zod.z.string().default("en").describe("Search language"), includeImages: zod.z.boolean().default(false).describe("Include image results"), dateRange: zod.z.enum(["day", "week", "month", "year", "all"]).default("all").describe("Date range filter") }), outputSchema: zod.z.object({ success: zod.z.boolean(), query: zod.z.string(), results: zod.z.array( zod.z.object({ title: zod.z.string(), url: zod.z.string(), snippet: zod.z.string(), domain: zod.z.string(), publishDate: zod.z.string().optional(), relevanceScore: zod.z.number().optional() }) ), totalResults: zod.z.number(), searchTime: zod.z.number(), suggestions: zod.z.array(zod.z.string()).optional(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { return await _AgentBuilderDefaults.webSearch(inputData); } }), // Task Completion Signaling attemptCompletion: tools.createTool({ id: "attempt-completion", description: "Signal that you believe the requested task has been completed and provide a summary.", inputSchema: zod.z.object({ summary: zod.z.string().describe("Summary of what was accomplished"), changes: zod.z.array( zod.z.object({ type: zod.z.enum(["file_created", "file_modified", "file_deleted", "command_executed", "dependency_added"]), description: zod.z.string(), path: zod.z.string().optional() }) ).describe("List of changes made"), validation: zod.z.object({ testsRun: zod.z.boolean().default(false), buildsSuccessfully: zod.z.boolean().default(false), manualTestingRequired: zod.z.boolean().default(false) }).describe("Validation status"), nextSteps: zod.z.array(zod.z.string()).optional().describe("Suggested next steps or follow-up actions") }), outputSchema: zod.z.object({ completionId: zod.z.string(), status: zod.z.enum(["completed", "needs_review", "needs_testing"]), summary: zod.z.string(), confidence: zod.z.number().min(0).max(100) }), execute: async (inputData) => { return await _AgentBuilderDefaults.signalCompletion(inputData); } }), manageProject: tools.createTool({ id: "manage-project", description: "Handles project management including creating project structures, managing dependencies, and package operations.", inputSchema: zod.z.object({ action: zod.z.enum(["create", "install", "upgrade"]).describe("The action to perform"), features: zod.z.array(zod.z.string()).optional().describe('Mastra features to include (e.g., ["agents", "memory", "workflows"])'), packages: zod.z.array( zod.z.object({ name: zod.z.string(), version: zod.z.string().optional() }) ).optional().describe("Packages to install/upgrade") }), outputSchema: zod.z.object({ success: zod.z.boolean(), installed: zod.z.array(zod.z.string()).optional(), upgraded: zod.z.array(zod.z.string()).optional(), warnings: zod.z.array(zod.z.string()).optional(), message: zod.z.string().optional(), details: zod.z.string().optional(), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { const { action, features, packages } = inputData; try { switch (action) { case "create": return await _AgentBuilderDefaults.createMastraProject({ projectName: projectPath, features }); case "install": if (!packages?.length) { return { success: false, message: "Packages array is required for install action" }; } return await _AgentBuilderDefaults.installPackages({ packages, projectPath }); case "upgrade": if (!packages?.length) { return { success: false, message: "Packages array is required for upgrade action" }; } return await _AgentBuilderDefaults.upgradePackages({ packages, projectPath }); default: return { success: false, message: `Unknown action: ${action}` }; } } catch (error90) { return { success: false, message: `Error executing ${action}: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } }), manageServer: tools.createTool({ id: "manage-server", description: "Manages the Mastra server - start, stop, restart, and check status, use the terminal tool to make curl requests to the server. There is an openapi spec for the server at http://localhost:{port}/openapi.json", inputSchema: zod.z.object({ action: zod.z.enum(["start", "stop", "restart", "status"]).describe("Server management action"), port: zod.z.number().optional().default(4200).describe("Port to run the server on") }), outputSchema: zod.z.object({ success: zod.z.boolean(), status: zod.z.enum(["running", "stopped", "starting", "stopping", "unknown"]), pid: zod.z.number().optional(), port: zod.z.number().optional(), url: zod.z.string().optional(), message: zod.z.string().optional(), stdout: zod.z.array(zod.z.string()).optional().describe("Server output lines captured during startup"), errorMessage: zod.z.string().optional() }), execute: async (inputData) => { const { action, port } = inputData; try { switch (action) { case "start": return await _AgentBuilderDefaults.startMastraServer({ port, projectPath }); case "stop": return await _AgentBuilderDefaults.stopMastraServer({ port, projectPath }); case "restart": const stopResult = await _AgentBuilderDefaults.stopMastraServer({ port, projectPath }); if (!stopResult.success) { return { success: false, status: "unknown", message: `Failed to restart: could not stop server on port ${port}`, errorMessage: stopResult.errorMessage || "Unknown stop error" }; } await new Promise((resolve5) => setTimeout(resolve5, 500)); const startResult = await _AgentBuilderDefaults.startMastraServer({ port, projectPath }); if (!startResult.success) { return { success: false, status: "stopped", message: `Failed to restart: server stopped successfully but failed to start on port ${port}`, errorMessage: startResult.errorMessage || "Unknown start error" }; } return { ...startResult, message: `Mastra server restarted successfully on port ${port}` }; case "status": return await _AgentBuilderDefaults.checkMastraServerStatus({ port, projectPath }); default: return { success: false, status: "unknown", message: `Unknown action: ${action}` }; } } catch (error90) { return { success: false, status: "unknown", message: `Error managing server: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } }), httpRequest: tools.createTool({ id: "http-request", description: "Makes HTTP requests to the Mastra server or external APIs for testing and integration", inputSchema: zod.z.object({ method: zod.z.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).describe("HTTP method"), url: zod.z.string().describe("Full URL or path (if baseUrl provided)"), baseUrl: zod.z.string().optional().describe("Base URL for the server (e.g., http://localhost:4200)"), headers: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("HTTP headers"), body: zod.z.any().optional().describe("Request body (will be JSON stringified if object)"), timeout: zod.z.number().optional().default(3e4).describe("Request timeout in milliseconds") }), outputSchema: zod.z.object({ success: zod.z.boolean(), status: zod.z.number().optional(), statusText: zod.z.string().optional(), headers: zod.z.record(zod.z.string(), zod.z.string()).optional(), data: zod.z.any().optional(), errorMessage: zod.z.string().optional(), url: zod.z.string(), method: zod.z.string() }), execute: async (inputData) => { const { method, url: url3, baseUrl, headers, body, timeout } = inputData; try { return await _AgentBuilderDefaults.makeHttpRequest({ method, url: url3, baseUrl, headers, body, timeout }); } catch (error90) { return { success: false, url: baseUrl ? `${baseUrl}${url3}` : url3, method, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } }) }; }; /** * Filter tools for template builder mode (excludes web search and other advanced tools) */ static filterToolsForTemplateBuilder(tools) { const templateBuilderTools = [ "readFile", "writeFile", "listDirectory", "executeCommand", "taskManager", "multiEdit", "replaceLines", "showFileLines", "smartSearch", "validateCode" ]; const filtered = {}; for (const toolName of templateBuilderTools) { if (tools[toolName]) { filtered[toolName] = tools[toolName]; } } return filtered; } /** * Filter tools for code editor mode (includes all tools) */ static filterToolsForCodeEditor(tools) { return tools; } /** * Get tools for a specific mode */ static async listToolsForMode(projectPath, mode = "code-editor") { const allTools = await _AgentBuilderDefaults.DEFAULT_TOOLS(projectPath); if (mode === "template") { return _AgentBuilderDefaults.filterToolsForTemplateBuilder(allTools); } else { return _AgentBuilderDefaults.filterToolsForCodeEditor(allTools); } } /** * Create a new Mastra project using create-mastra CLI */ static async createMastraProject({ features, projectName }) { try { const args = ["pnpx", "create-mastra@latest", projectName?.replace(/[;&|`$(){}\[\]]/g, "") ?? "", "-l", "openai"]; if (features && features.length > 0) { args.push("--components", features.join(",")); } args.push("--example"); const { stdout, stderr } = await spawnWithOutput(args[0], args.slice(1), {}); return { success: true, projectPath: `./${projectName}`, message: `Successfully created Mastra project: ${projectName}.`, details: stdout, errorMessage: stderr }; } catch (error90) { console.error(error90); return { success: false, message: `Failed to create project: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } /** * Install packages using the detected package manager */ static async installPackages({ packages, projectPath }) { try { console.info("Installing packages:", JSON.stringify(packages, null, 2)); const packageStrings = packages.map((p) => `${p.name}`); await spawnSWPM(projectPath || "", "add", packageStrings); return { success: true, installed: packageStrings, message: `Successfully installed ${packages.length} package(s).`, details: "" }; } catch (error90) { return { success: false, message: `Failed to install packages: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } /** * Upgrade packages using the detected package manager */ static async upgradePackages({ packages, projectPath }) { try { console.info("Upgrading specific packages:", JSON.stringify(packages, null, 2)); let packageNames = []; if (packages && packages.length > 0) { packageNames = packages.map((p) => `${p.name}`); } await spawnSWPM(projectPath || "", "upgrade", packageNames); return { success: true, upgraded: packages?.map((p) => p.name) || ["all packages"], message: `Packages upgraded successfully.`, details: "" }; } catch (error90) { return { success: false, message: `Failed to upgrade packages: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } /** * Start the Mastra server */ static async startMastraServer({ port = 4200, projectPath, env = {} }) { try { const serverEnv = { ...process.env, ...env, PORT: port.toString() }; const execOptions = { cwd: projectPath || process.cwd(), env: serverEnv }; const serverProcess = child_process.spawn("pnpm", ["run", "dev"], { ...execOptions, detached: true, stdio: "pipe" }); const stdoutLines = []; const serverStarted = new Promise((resolve5, reject) => { const timeout = setTimeout(() => { reject(new Error(`Server startup timeout after 30 seconds. Output: ${stdoutLines.join("\n")}`)); }, 3e4); serverProcess.stdout?.on("data", (data) => { const output = data.toString(); const lines = output.split("\n").filter((line) => line.trim()); stdoutLines.push(...lines); if (output.includes("Mastra API running")) { clearTimeout(timeout); resolve5({ success: true, status: "running", pid: serverProcess.pid, port, url: `http://localhost:${port}`, message: `Mastra server started successfully on port ${port}`, stdout: stdoutLines }); } }); serverProcess.stderr?.on("data", (data) => { const errorOutput = data.toString(); stdoutLines.push(`[STDERR] ${errorOutput}`); clearTimeout(timeout); reject(new Error(`Server startup failed with error: ${errorOutput}`)); }); serverProcess.on("error", (error90) => { clearTimeout(timeout); reject(error90); }); serverProcess.on("exit", (code, signal) => { clearTimeout(timeout); if (code !== 0 && code !== null) { reject( new Error( `Server process exited with code ${code}${signal ? ` (signal: ${signal})` : ""}. Output: ${stdoutLines.join("\n")}` ) ); } }); }); return await serverStarted; } catch (error90) { return { success: false, status: "stopped", errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Stop the Mastra server */ static async stopMastraServer({ port = 4200, projectPath: _projectPath }) { if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) { return { success: false, status: "error", errorMessage: `Invalid port value: ${String(port)}` }; } try { const { stdout } = await execFile("lsof", ["-ti", String(port)]); const effectiveStdout = stdout.trim() ? stdout : "No process found"; if (!effectiveStdout || effectiveStdout === "No process found") { return { success: true, status: "stopped", message: `No Mastra server found running on port ${port}` }; } const pids = stdout.trim().split("\n").filter((pid) => pid.trim()); const killedPids = []; const failedPids = []; for (const pidStr of pids) { const pid = parseInt(pidStr.trim()); if (isNaN(pid)) continue; try { process.kill(pid, "SIGTERM"); killedPids.push(pid); } catch (e2) { failedPids.push(pid); console.warn(`Failed to kill process ${pid}:`, e2); } } if (killedPids.length === 0) { return { success: false, status: "unknown", message: `Failed to stop any processes on port ${port}`, errorMessage: `Could not kill PIDs: ${failedPids.join(", ")}` }; } if (failedPids.length > 0) { console.warn( `Killed ${killedPids.length} processes but failed to kill ${failedPids.length} processes: ${failedPids.join(", ")}` ); } await new Promise((resolve5) => setTimeout(resolve5, 2e3)); try { const { stdout: checkStdoutRaw } = await execFile("lsof", ["-ti", String(port)]); const checkStdout = checkStdoutRaw.trim() ? checkStdoutRaw : "No process found"; if (checkStdout && checkStdout !== "No process found") { const remainingPids = checkStdout.trim().split("\n").filter((pid) => pid.trim()); for (const pidStr of remainingPids) { const pid = parseInt(pidStr.trim()); if (!isNaN(pid)) { try { process.kill(pid, "SIGKILL"); } catch { } } } await new Promise((resolve5) => setTimeout(resolve5, 1e3)); const { stdout: finalCheckRaw } = await execFile("lsof", ["-ti", String(port)]); const finalCheck = finalCheckRaw.trim() ? finalCheckRaw : "No process found"; if (finalCheck && finalCheck !== "No process found") { return { success: false, status: "unknown", message: `Server processes still running on port ${port} after stop attempts`, errorMessage: `Remaining PIDs: ${finalCheck.trim()}` }; } } } catch (error90) { console.warn("Failed to verify server stop:", error90); } return { success: true, status: "stopped", message: `Mastra server stopped successfully (port ${port}). Killed PIDs: ${killedPids.join(", ")}` }; } catch (error90) { return { success: false, status: "unknown", errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Check Mastra server status */ static async checkMastraServerStatus({ port = 4200, projectPath: _projectPath }) { try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5e3); const response = await fetch(`http://localhost:${port}/health`, { method: "GET", signal: controller.signal }); clearTimeout(timeoutId); if (response.ok) { return { success: true, status: "running", port, url: `http://localhost:${port}`, message: "Mastra server is running and healthy" }; } else { return { success: false, status: "unknown", port, message: `Server responding but not healthy (status: ${response.status})` }; } } catch { try { const { stdout } = await execFile("lsof", ["-ti", String(port)]); const effectiveStdout = stdout.trim() ? stdout : "No process found"; const hasProcess = effectiveStdout && effectiveStdout !== "No process found"; return { success: Boolean(hasProcess), status: hasProcess ? "starting" : "stopped", port, message: hasProcess ? "Server process exists but not responding to health checks" : "No server process found on specified port" }; } catch { return { success: false, status: "stopped", port, message: "Server is not running" }; } } } // Cache for TypeScript program (lazily loaded) static tsProgram = null; static programProjectPath = null; /** * Validate code using hybrid approach: syntax -> types -> lint * * BEST PRACTICES FOR CODING AGENTS: * * ✅ RECOMMENDED (Fast & Accurate): * validateCode({ * validationType: ['types', 'lint'], * files: ['src/workflows/my-workflow.ts', 'src/components/Button.tsx'] * }) * * Performance: ~150ms * - Syntax check (1ms) - catches 80% of issues instantly * - Semantic validation (100ms) - full type checking with dependencies * - ESLint (50ms) - style and best practices * - Only shows errors from YOUR files * * ❌ AVOID (Slow & Noisy): * validateCode({ validationType: ['types', 'lint'] }) // no files specified * * Performance: ~2000ms+ * - Full project CLI validation * - Shows errors from all project files (confusing) * - Much slower for coding agents * * @param projectPath - Project root directory (defaults to cwd) * @param validationType - ['types', 'lint'] recommended for most use cases * @param files - ALWAYS provide this for best performance */ static async validateCode({ projectPath, validationType, files }) { const errors = []; const validationsPassed = []; const validationsFailed = []; const targetProjectPath = projectPath || process.cwd(); if (!files || files.length === 0) { return this.validateCodeCLI({ projectPath, validationType }); } for (const filePath of files) { const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(targetProjectPath, filePath); try { const fileContent = await promises.readFile(absolutePath, "utf-8"); const fileResults = await this.validateSingleFileHybrid( absolutePath, fileContent, targetProjectPath, validationType ); errors.push(...fileResults.errors); for (const type of validationType) { const hasErrors = fileResults.errors.some((e2) => e2.type === type && e2.severity === "error"); if (hasErrors) { if (!validationsFailed.includes(type)) validationsFailed.push(type); } else { if (!validationsPassed.includes(type)) validationsPassed.push(type); } } } catch (error90) { errors.push({ type: "typescript", severity: "error", message: `Failed to read file ${filePath}: ${error90 instanceof Error ? error90.message : String(error90)}`, file: filePath }); validationsFailed.push("types"); } } const totalErrors = errors.filter((e2) => e2.severity === "error").length; const totalWarnings = errors.filter((e2) => e2.severity === "warning").length; const isValid2 = totalErrors === 0; return { valid: isValid2, errors, summary: { totalErrors, totalWarnings, validationsPassed, validationsFailed } }; } /** * CLI-based validation for when no specific files are provided */ static async validateCodeCLI({ projectPath, validationType }) { const errors = []; const validationsPassed = []; const validationsFailed = []; const execOptions = { cwd: projectPath }; if (validationType.includes("types")) { try { const args = ["tsc", "--noEmit"]; await execFile("npx", args, execOptions); validationsPassed.push("types"); } catch (error90) { let tsOutput = ""; if (error90.stdout) { tsOutput = error90.stdout; } else if (error90.stderr) { tsOutput = error90.stderr; } else if (error90.message) { tsOutput = error90.message; } errors.push({ type: "typescript", severity: "error", message: tsOutput.trim() || `TypeScript validation failed: ${error90.message || String(error90)}` }); validationsFailed.push("types"); } } if (validationType.includes("lint")) { try { const eslintArgs = ["eslint", "--format", "json"]; const { stdout } = await execFile("npx", eslintArgs, execOptions); if (stdout) { const eslintResults = JSON.parse(stdout); const eslintErrors = _AgentBuilderDefaults.parseESLintErrors(eslintResults); errors.push(...eslintErrors); if (eslintErrors.some((e2) => e2.severity === "error")) { validationsFailed.push("lint"); } else { validationsPassed.push("lint"); } } else { validationsPassed.push("lint"); } } catch (error90) { const errorMessage = error90 instanceof Error ? error90.message : String(error90); if (errorMessage.includes('"filePath"') || errorMessage.includes("messages")) { try { const eslintResults = JSON.parse(errorMessage); const eslintErrors = _AgentBuilderDefaults.parseESLintErrors(eslintResults); errors.push(...eslintErrors); validationsFailed.push("lint"); } catch { errors.push({ type: "eslint", severity: "error", message: `ESLint validation failed: ${errorMessage}` }); validationsFailed.push("lint"); } } else { validationsPassed.push("lint"); } } } const totalErrors = errors.filter((e2) => e2.severity === "error").length; const totalWarnings = errors.filter((e2) => e2.severity === "warning").length; const isValid2 = totalErrors === 0; return { valid: isValid2, errors, summary: { totalErrors, totalWarnings, validationsPassed, validationsFailed } }; } /** * Hybrid validation for a single file */ static async validateSingleFileHybrid(filePath, fileContent, projectPath, validationType) { const errors = []; if (validationType.includes("types")) { const syntaxErrors = await this.validateSyntaxOnly(fileContent, filePath); errors.push(...syntaxErrors); if (syntaxErrors.length > 0) { return { errors }; } const typeErrors = await this.validateTypesSemantic(filePath, projectPath); errors.push(...typeErrors); } if (validationType.includes("lint") && !errors.some((e2) => e2.severity === "error")) { const lintErrors = await this.validateESLintSingle(filePath, projectPath); errors.push(...lintErrors); } return { errors }; } /** * Fast syntax-only validation using TypeScript parser */ static async validateSyntaxOnly(fileContent, fileName) { const errors = []; try { const ts = await import('typescript'); const sourceFile = ts.createSourceFile(fileName, fileContent, ts.ScriptTarget.Latest, true); const options = { allowJs: true, checkJs: false, noEmit: true }; const host = { getSourceFile: (name16) => name16 === fileName ? sourceFile : void 0, writeFile: () => { }, getCurrentDirectory: () => "", getDirectories: () => [], fileExists: (name16) => name16 === fileName, readFile: (name16) => name16 === fileName ? fileContent : void 0, getCanonicalFileName: (name16) => name16, useCaseSensitiveFileNames: () => true, getNewLine: () => "\n", getDefaultLibFileName: () => "lib.d.ts" }; const program = ts.createProgram([fileName], options, host); const diagnostics = program.getSyntacticDiagnostics(sourceFile); for (const diagnostic of diagnostics) { if (diagnostic.start !== void 0) { const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start); errors.push({ type: "typescript", severity: "error", message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), file: fileName, line: position.line + 1, column: position.character + 1 }); } } } catch (error90) { console.warn("TypeScript not available for syntax validation:", error90); const lines = fileContent.split("\n"); const commonErrors = [ { pattern: /\bimport\s+.*\s+from\s+['""][^'"]*$/, message: "Unterminated import statement" }, { pattern: /\{[^}]*$/, message: "Unclosed brace" }, { pattern: /\([^)]*$/, message: "Unclosed parenthesis" }, { pattern: /\[[^\]]*$/, message: "Unclosed bracket" } ]; lines.forEach((line, index) => { commonErrors.forEach(({ pattern, message }) => { if (pattern.test(line)) { errors.push({ type: "typescript", severity: "error", message, file: fileName, line: index + 1 }); } }); }); } return errors; } /** * TypeScript semantic validation using incremental program */ static async validateTypesSemantic(filePath, projectPath) { const errors = []; try { const program = await this.getOrCreateTSProgram(projectPath); if (!program) { return errors; } const sourceFile = program.getSourceFile(filePath); if (!sourceFile) { return errors; } const diagnostics = [ ...program.getSemanticDiagnostics(sourceFile), ...program.getSyntacticDiagnostics(sourceFile) ]; const ts = await import('typescript'); for (const diagnostic of diagnostics) { if (diagnostic.start !== void 0) { const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start); errors.push({ type: "typescript", severity: diagnostic.category === ts.DiagnosticCategory.Warning ? "warning" : "error", message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), file: filePath, line: position.line + 1, column: position.character + 1 }); } } } catch (error90) { console.warn(`TypeScript semantic validation failed for ${filePath}:`, error90); } return errors; } /** * ESLint validation for a single file */ static async validateESLintSingle(filePath, projectPath) { const errors = []; try { const { stdout } = await execFile("npx", ["eslint", filePath, "--format", "json"], { cwd: projectPath }); if (stdout) { const eslintResults = JSON.parse(stdout); const eslintErrors = this.parseESLintErrors(eslintResults); errors.push(...eslintErrors); } } catch (error90) { const errorMessage = error90 instanceof Error ? error90.message : String(error90); if (errorMessage.includes('"filePath"') || errorMessage.includes("messages")) { try { const eslintResults = JSON.parse(errorMessage); const eslintErrors = this.parseESLintErrors(eslintResults); errors.push(...eslintErrors); } catch { } } } return errors; } /** * Get or create TypeScript program */ static async getOrCreateTSProgram(projectPath) { if (this.tsProgram && this.programProjectPath === projectPath) { return this.tsProgram; } try { const ts = await import('typescript'); const configPath = ts.findConfigFile(projectPath, ts.sys.fileExists, "tsconfig.json"); if (!configPath) { return null; } const configFile = ts.readConfigFile(configPath, ts.sys.readFile); if (configFile.error) { return null; } const parsedConfig = ts.parseJsonConfigFileContent(configFile.config, ts.sys, projectPath); if (parsedConfig.errors.length > 0) { return null; } this.tsProgram = ts.createProgram({ rootNames: parsedConfig.fileNames, options: parsedConfig.options }); this.programProjectPath = projectPath; return this.tsProgram; } catch (error90) { console.warn("Failed to create TypeScript program:", error90); return null; } } // Note: Old filterTypeScriptErrors method removed in favor of hybrid validation approach /** * Parse ESLint errors from JSON output */ static parseESLintErrors(eslintResults) { const errors = []; for (const result of eslintResults) { for (const message of result.messages || []) { if (message.message) { errors.push({ type: "eslint", severity: message.severity === 1 ? "warning" : "error", message: message.message, file: result.filePath || void 0, line: message.line || void 0, column: message.column || void 0, code: message.ruleId || void 0 }); } } } return errors; } /** * Make HTTP request to server or external API */ static async makeHttpRequest({ method, url: url3, baseUrl, headers = {}, body, timeout = 3e4 }) { try { const fullUrl = baseUrl ? `${baseUrl}${url3}` : url3; const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeout); const requestOptions = { method, headers: { "Content-Type": "application/json", ...headers }, signal: controller.signal }; if (body && (method === "POST" || method === "PUT" || method === "PATCH")) { requestOptions.body = typeof body === "string" ? body : JSON.stringify(body); } const response = await fetch(fullUrl, requestOptions); clearTimeout(timeoutId); let data; const contentType = response.headers.get("content-type"); if (contentType?.includes("application/json")) { data = await response.json(); } else { data = await response.text(); } const responseHeaders = {}; response.headers.forEach((value, key) => { responseHeaders[key] = value; }); return { success: response.ok, status: response.status, statusText: response.statusText, headers: responseHeaders, data, url: fullUrl, method }; } catch (error90) { return { success: false, url: baseUrl ? `${baseUrl}${url3}` : url3, method, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Enhanced task management system for complex coding tasks */ static async manageTaskList(context2) { if (!_AgentBuilderDefaults.taskStorage) { _AgentBuilderDefaults.taskStorage = /* @__PURE__ */ new Map(); } const sessions = Array.from(_AgentBuilderDefaults.taskStorage.keys()); if (sessions.length > 10) { const sessionsToRemove = sessions.slice(0, sessions.length - 10); sessionsToRemove.forEach((session) => _AgentBuilderDefaults.taskStorage.delete(session)); } const sessionId = "current"; const existingTasks = _AgentBuilderDefaults.taskStorage.get(sessionId) || []; try { switch (context2.action) { case "create": if (!context2.tasks?.length) { return { success: false, tasks: existingTasks, message: "No tasks provided for creation" }; } const newTasks = context2.tasks.map((task) => ({ ...task, createdAt: (/* @__PURE__ */ new Date()).toISOString(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() })); const allTasks = [...existingTasks, ...newTasks]; _AgentBuilderDefaults.taskStorage.set(sessionId, allTasks); return { success: true, tasks: allTasks, message: `Created ${newTasks.length} new task(s)` }; case "update": if (!context2.tasks?.length) { return { success: false, tasks: existingTasks, message: "No tasks provided for update" }; } const updatedTasks = existingTasks.map((existing) => { const update = context2.tasks.find((t) => t.id === existing.id); return update ? { ...existing, ...update, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } : existing; }); _AgentBuilderDefaults.taskStorage.set(sessionId, updatedTasks); return { success: true, tasks: updatedTasks, message: "Tasks updated successfully" }; case "complete": if (!context2.taskId) { return { success: false, tasks: existingTasks, message: "Task ID required for completion" }; } const completedTasks = existingTasks.map( (task) => task.id === context2.taskId ? { ...task, status: "completed", updatedAt: (/* @__PURE__ */ new Date()).toISOString() } : task ); _AgentBuilderDefaults.taskStorage.set(sessionId, completedTasks); return { success: true, tasks: completedTasks, message: `Task ${context2.taskId} marked as completed` }; case "remove": if (!context2.taskId) { return { success: false, tasks: existingTasks, message: "Task ID required for removal" }; } const filteredTasks = existingTasks.filter((task) => task.id !== context2.taskId); _AgentBuilderDefaults.taskStorage.set(sessionId, filteredTasks); return { success: true, tasks: filteredTasks, message: `Task ${context2.taskId} removed` }; case "list": default: return { success: true, tasks: existingTasks, message: `Found ${existingTasks.length} task(s)` }; } } catch (error90) { return { success: false, tasks: existingTasks, message: `Task management error: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } /** * Perform multiple edits across files atomically */ static async performMultiEdit(context2) { const { operations, createBackup = false, projectPath = process.cwd() } = context2; const results = []; try { for (const operation of operations) { const filePath = path.isAbsolute(operation.filePath) ? operation.filePath : path.join(projectPath, operation.filePath); let editsApplied = 0; const errors = []; let backup; try { if (createBackup) { const backupPath = `${filePath}.backup.${Date.now()}`; const originalContent = await promises.readFile(filePath, "utf-8"); await promises.writeFile(backupPath, originalContent, "utf-8"); backup = backupPath; } let content = await promises.readFile(filePath, "utf-8"); for (const edit of operation.edits) { const { oldString, newString, replaceAll = false } = edit; if (replaceAll) { const regex = new RegExp(oldString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"); const matches = content.match(regex); if (matches) { content = content.replace(regex, newString); editsApplied += matches.length; } } else { if (content.includes(oldString)) { content = content.replace(oldString, newString); editsApplied++; } else { errors.push(`String not found: "${oldString.substring(0, 50)}${oldString.length > 50 ? "..." : ""}"`); } } } await promises.writeFile(filePath, content, "utf-8"); } catch (error90) { errors.push(`File operation error: ${error90 instanceof Error ? error90.message : String(error90)}`); } results.push({ filePath: operation.filePath, editsApplied, errors, backup }); } const totalEdits = results.reduce((sum, r) => sum + r.editsApplied, 0); const totalErrors = results.reduce((sum, r) => sum + r.errors.length, 0); return { success: totalErrors === 0, results, message: `Applied ${totalEdits} edits across ${operations.length} files${totalErrors > 0 ? ` with ${totalErrors} errors` : ""}` }; } catch (error90) { return { success: false, results, message: `Multi-edit operation failed: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } /** * Replace specific line ranges in a file with new content */ static async replaceLines(context2) { const { filePath, startLine, endLine, newContent, createBackup = false, projectPath = process.cwd() } = context2; try { const fullPath = path.isAbsolute(filePath) ? filePath : path.join(projectPath, filePath); const content = await promises.readFile(fullPath, "utf-8"); const lines = content.split("\n"); if (startLine < 1 || endLine < 1) { return { success: false, message: `Line numbers must be 1 or greater. Got startLine: ${startLine}, endLine: ${endLine}`, errorMessage: "Invalid line range" }; } if (startLine > lines.length || endLine > lines.length) { return { success: false, message: `Line range ${startLine}-${endLine} is out of bounds. File has ${lines.length} lines. Remember: lines are 1-indexed, so valid range is 1-${lines.length}.`, errorMessage: "Invalid line range" }; } if (startLine > endLine) { return { success: false, message: `Start line (${startLine}) cannot be greater than end line (${endLine}).`, errorMessage: "Invalid line range" }; } let backup; if (createBackup) { const backupPath = `${fullPath}.backup.${Date.now()}`; await promises.writeFile(backupPath, content, "utf-8"); backup = backupPath; } const beforeLines = lines.slice(0, startLine - 1); const afterLines = lines.slice(endLine); const newLines = newContent ? newContent.split("\n") : []; const updatedLines = [...beforeLines, ...newLines, ...afterLines]; const updatedContent = updatedLines.join("\n"); await promises.writeFile(fullPath, updatedContent, "utf-8"); const linesReplaced = endLine - startLine + 1; const newLineCount = newLines.length; return { success: true, message: `Successfully replaced ${linesReplaced} lines (${startLine}-${endLine}) with ${newLineCount} new lines in ${filePath}`, linesReplaced, backup }; } catch (error90) { return { success: false, message: `Failed to replace lines: ${error90 instanceof Error ? error90.message : String(error90)}`, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Show file lines with line numbers for debugging */ static async showFileLines(context2) { const { filePath, startLine, endLine, context: contextLines = 2, projectPath = process.cwd() } = context2; try { const fullPath = path.isAbsolute(filePath) ? filePath : path.join(projectPath, filePath); const content = await promises.readFile(fullPath, "utf-8"); const lines = content.split("\n"); let targetStart = startLine; let targetEnd = endLine; if (!targetStart) { targetStart = 1; targetEnd = lines.length; } else if (!targetEnd) { targetEnd = targetStart; } const displayStart = Math.max(1, targetStart - contextLines); const displayEnd = Math.min(lines.length, targetEnd + contextLines); const result = []; for (let i = displayStart; i <= displayEnd; i++) { const lineIndex = i - 1; const isTarget = i >= targetStart && i <= targetEnd; result.push({ lineNumber: i, content: lineIndex < lines.length ? lines[lineIndex] ?? "" : "", isTarget }); } return { success: true, lines: result, totalLines: lines.length, message: `Showing lines ${displayStart}-${displayEnd} of ${lines.length} total lines in ${filePath}` }; } catch (error90) { return { success: false, lines: [], totalLines: 0, message: `Failed to read file: ${error90 instanceof Error ? error90.message : String(error90)}`, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Signal task completion */ static async signalCompletion(context2) { const completionId = `completion_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; let confidence = 70; if (context2.validation.testsRun) confidence += 15; if (context2.validation.buildsSuccessfully) confidence += 15; if (context2.validation.manualTestingRequired) confidence -= 10; let status; if (context2.validation.testsRun && context2.validation.buildsSuccessfully) { status = "completed"; } else if (context2.validation.manualTestingRequired) { status = "needs_testing"; } else { status = "needs_review"; } return { completionId, status, summary: context2.summary, confidence: Math.min(100, Math.max(0, confidence)) }; } /** * Perform intelligent search with context */ static async performSmartSearch(context2, projectPath) { try { const { query, type = "text", scope = {}, context: searchContext = {} } = context2; const { paths = ["."], fileTypes = [], excludePaths = [], maxResults = 50 } = scope; const { beforeLines = 2, afterLines = 2 } = searchContext; const rgArgs = []; if (beforeLines > 0) { rgArgs.push("-B", beforeLines.toString()); } if (afterLines > 0) { rgArgs.push("-A", afterLines.toString()); } rgArgs.push("-n"); if (type === "regex") { rgArgs.push("-e"); } else if (type === "fuzzy") { rgArgs.push("--fixed-strings"); } if (fileTypes.length > 0) { fileTypes.forEach((ft) => { rgArgs.push("--type-add", `custom:*.${ft}`, "-t", "custom"); }); } excludePaths.forEach((path) => { rgArgs.push("--glob", `!${path}`); }); rgArgs.push("-m", maxResults.toString()); rgArgs.push(query); rgArgs.push(...paths); const { stdout } = await execFile("rg", rgArgs, { cwd: projectPath }); const lines = stdout.split("\n").filter((line) => line.trim()); const matches = []; let currentMatch = null; lines.forEach((line) => { if (line.includes(":") && !line.startsWith("-")) { const parts = line.split(":"); if (parts.length >= 3) { if (currentMatch) { matches.push(currentMatch); } currentMatch = { file: parts[0] || "", line: parseInt(parts[1] || "0"), match: parts.slice(2).join(":"), context: { before: [], after: [] }, relevance: type === "fuzzy" ? Math.random() * 100 : void 0 }; } } else if (line.startsWith("-") && currentMatch) { const contextLine = line.substring(1); if (currentMatch.context.before.length < beforeLines) { currentMatch.context.before.push(contextLine); } else { currentMatch.context.after.push(contextLine); } } }); if (currentMatch) { matches.push(currentMatch); } const filesSearched = new Set(matches.map((m) => m.file)).size; return { success: true, matches: matches.slice(0, maxResults), summary: { totalMatches: matches.length, filesSearched, patterns: [query] } }; } catch { return { success: false, matches: [], summary: { totalMatches: 0, filesSearched: 0, patterns: [context2.query] } }; } } // Static storage properties static taskStorage; static pendingQuestions; /** * Read file contents with optional line range */ static async readFile(context2) { try { const { filePath, startLine, endLine, encoding = "utf-8", projectPath } = context2; const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(projectPath || process.cwd(), filePath); const stats = await promises.stat(resolvedPath); const content = await promises.readFile(resolvedPath, { encoding }); const lines = content.split("\n"); let resultContent = content; let resultLines = lines; if (startLine !== void 0 || endLine !== void 0) { const start = Math.max(0, (startLine || 1) - 1); const end = endLine !== void 0 ? Math.min(lines.length, endLine) : lines.length; resultLines = lines.slice(start, end); resultContent = resultLines.join("\n"); } return { success: true, content: resultContent, lines: resultLines, metadata: { size: stats.size, totalLines: lines.length, encoding, lastModified: stats.mtime.toISOString() } }; } catch (error90) { return { success: false, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Write content to file with directory creation and backup options */ static async writeFile(context2) { try { const { filePath, content, createDirs = true, encoding = "utf-8", projectPath } = context2; const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(projectPath || process.cwd(), filePath); const dir = path.dirname(resolvedPath); if (createDirs) { await promises.mkdir(dir, { recursive: true }); } await promises.writeFile(resolvedPath, content, { encoding }); return { success: true, filePath: resolvedPath, bytesWritten: Buffer.byteLength(content, encoding), message: `Successfully wrote ${Buffer.byteLength(content, encoding)} bytes to ${filePath}` }; } catch (error90) { return { success: false, filePath: context2.filePath, message: `Failed to write file: ${error90 instanceof Error ? error90.message : String(error90)}`, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * List directory contents with filtering and metadata */ static async listDirectory(context2) { try { const { path: path$1, recursive = false, includeHidden = false, pattern, maxDepth = 10, includeMetadata = true, projectPath } = context2; const gitignorePath = path.join(projectPath || process.cwd(), ".gitignore"); let gitignoreFilter; try { const gitignoreContent = await promises.readFile(gitignorePath, "utf-8"); gitignoreFilter = (0, import_ignore.default)().add(gitignoreContent); } catch (err) { if (err.code !== "ENOENT") { console.error(`Error reading .gitignore file:`, err); } } const resolvedPath = path.isAbsolute(path$1) ? path$1 : path.resolve(projectPath || process.cwd(), path$1); const items = []; async function processDirectory(dirPath, currentDepth = 0) { const relativeToProject = path.relative(projectPath || process.cwd(), dirPath); if (gitignoreFilter?.ignores(relativeToProject)) return; if (currentDepth > maxDepth) return; const entries = await promises.readdir(dirPath); for (const entry of entries) { const entryPath = path.join(dirPath, entry); const relativeEntryPath = path.relative(projectPath || process.cwd(), entryPath); if (gitignoreFilter?.ignores(relativeEntryPath)) continue; if (!includeHidden && entry.startsWith(".")) continue; const fullPath = entryPath; const relativePath = path.relative(resolvedPath, fullPath); if (pattern) { const regexPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, "."); if (!new RegExp(regexPattern).test(entry)) continue; } let stats; let type; try { stats = await promises.stat(fullPath); if (stats.isDirectory()) { type = "directory"; } else if (stats.isSymbolicLink()) { type = "symlink"; } else { type = "file"; } } catch { continue; } const item = { name: entry, path: relativePath || entry, type }; if (includeMetadata) { item.size = stats.size; item.lastModified = stats.mtime.toISOString(); item.permissions = `0${(stats.mode & parseInt("777", 8)).toString(8)}`; } items.push(item); if (recursive && type === "directory") { await processDirectory(fullPath, currentDepth + 1); } } } await processDirectory(resolvedPath); return { success: true, items, totalItems: items.length, path: resolvedPath, message: `Listed ${items.length} items in ${resolvedPath}` }; } catch (error90) { return { success: false, items: [], totalItems: 0, path: context2.path, message: `Failed to list directory: ${error90 instanceof Error ? error90.message : String(error90)}`, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Execute shell commands with proper error handling */ static async executeCommand(context2) { const startTime = Date.now(); try { const { command, workingDirectory, timeout = 3e4, captureOutput = true, shell, env } = context2; const execOptions = { timeout, env: { ...process.env, ...env } }; if (workingDirectory) { execOptions.cwd = workingDirectory; } if (shell) { execOptions.shell = shell; } const { stdout, stderr } = await exec(command, execOptions); const executionTime = Date.now() - startTime; return { success: true, exitCode: 0, stdout: captureOutput ? String(stdout) : void 0, stderr: captureOutput ? String(stderr) : void 0, command, workingDirectory, executionTime }; } catch (error90) { const executionTime = Date.now() - startTime; return { success: false, exitCode: error90.code || 1, stdout: String(error90.stdout || ""), stderr: String(error90.stderr || ""), command: context2.command, workingDirectory: context2.workingDirectory, executionTime, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } /** * Web search using a simple search approach */ static async webSearch(context2) { try { const { query, maxResults = 10 // region = 'us', // language = 'en', // includeImages = false, // dateRange = 'all', } = context2; const startTime = Date.now(); const searchUrl = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&skip_disambig=1`; const response = await fetch(searchUrl); const data = await response.json(); const results = []; if (data.RelatedTopics && Array.isArray(data.RelatedTopics)) { for (const topic of data.RelatedTopics.slice(0, maxResults)) { if (topic.FirstURL && topic.Text) { const url3 = new URL(topic.FirstURL); results.push({ title: topic.Text.split(" - ")[0] || topic.Text.substring(0, 60), url: topic.FirstURL, snippet: topic.Text, domain: url3.hostname, relevanceScore: Math.random() * 100 // Placeholder scoring }); } } } if (data.Abstract && data.AbstractURL) { const url3 = new URL(data.AbstractURL); results.unshift({ title: data.Heading || "Main Result", url: data.AbstractURL, snippet: data.Abstract, domain: url3.hostname, relevanceScore: 100 }); } const searchTime = Date.now() - startTime; return { success: true, query, results: results.slice(0, maxResults), totalResults: results.length, searchTime, suggestions: data.RelatedTopics?.slice(maxResults, maxResults + 3)?.map((t) => t.Text?.split(" - ")[0] || t.Text?.substring(0, 30)).filter(Boolean) || [] }; } catch (error90) { return { success: false, query: context2.query, results: [], totalResults: 0, searchTime: 0, errorMessage: error90 instanceof Error ? error90.message : String(error90) }; } } }; var ToolSummaryProcessor = class { id = "tool-summary-processor"; name = "ToolSummaryProcessor"; summaryAgent; summaryCache = /* @__PURE__ */ new Map(); constructor({ summaryModel }) { this.summaryAgent = new agent.Agent({ id: "tool-summary-agent", name: "Tool Summary Agent", description: "A summary agent that summarizes tool calls and results", instructions: "You are a summary agent that summarizes tool calls and results", model: summaryModel }); } /** * Creates a cache key from tool call arguments */ createCacheKey(toolCall) { if (!toolCall) return "unknown"; const toolName = toolCall.toolName || "unknown"; const args = toolCall.args || {}; const sortedArgs = Object.keys(args).sort().reduce((result, key) => { result[key] = args[key]; return result; }, {}); return `${toolName}:${JSON.stringify(sortedArgs)}`; } /** * Clears the summary cache */ clearCache() { this.summaryCache.clear(); } /** * Gets cache statistics */ getCacheStats() { return { size: this.summaryCache.size, keys: Array.from(this.summaryCache.keys()) }; } async processInput({ messages, messageList: _messageList }) { const summaryTasks = []; for (const message of messages) { if (message.content.format === 2 && message.content.parts) { for (let partIndex = 0; partIndex < message.content.parts.length; partIndex++) { const part = message.content.parts[partIndex]; if (part && part.type === "tool-invocation" && part.toolInvocation?.state === "result") { const cacheKey = this.createCacheKey(part.toolInvocation); const cachedSummary = this.summaryCache.get(cacheKey); if (cachedSummary) { message.content.parts[partIndex] = { type: "tool-invocation", toolInvocation: { state: "result", step: part.toolInvocation.step, toolCallId: part.toolInvocation.toolCallId, toolName: part.toolInvocation.toolName, args: part.toolInvocation.args, result: `Tool call summary: ${cachedSummary}` } }; } else { const summaryPromise = this.summaryAgent.generate( `Summarize the following tool call: ${JSON.stringify(part.toolInvocation)}` ); summaryTasks.push({ message, partIndex, promise: summaryPromise, cacheKey }); } } } } } if (summaryTasks.length > 0) { const summaryResults = await Promise.allSettled(summaryTasks.map((task) => task.promise)); summaryTasks.forEach((task, index) => { const result = summaryResults[index]; if (!result) return; if (result.status === "fulfilled") { const summaryResult = result.value; const summaryText = summaryResult.text; this.summaryCache.set(task.cacheKey, summaryText); if (task.message.content.format === 2 && task.message.content.parts) { const part = task.message.content.parts[task.partIndex]; if (part && part.type === "tool-invocation" && part.toolInvocation?.state === "result") { task.message.content.parts[task.partIndex] = { type: "tool-invocation", toolInvocation: { state: "result", step: part.toolInvocation.step, toolCallId: part.toolInvocation.toolCallId, toolName: part.toolInvocation.toolName, args: part.toolInvocation.args, result: `Tool call summary: ${summaryText}` } }; } } } else if (result.status === "rejected") { console.warn(`Failed to generate summary for tool call:`, result.reason); } }); } return messages; } }; var AgentBuilder = class extends agent.Agent { builderConfig; /** * Constructor for AgentBuilder */ constructor(config3) { const additionalInstructions = config3.instructions ? `## Priority Instructions ${config3.instructions}` : ""; const combinedInstructions = additionalInstructions + AgentBuilderDefaults.DEFAULT_INSTRUCTIONS(config3.projectPath); const memory = new Memory({ options: AgentBuilderDefaults.DEFAULT_MEMORY_CONFIG }); memory.setStorage(config3.storage ?? new storage.InMemoryStore()); const agentConfig = { id: "agent-builder", name: "agent-builder", description: "An AI agent specialized in generating Mastra agents, tools, and workflows from natural language requirements.", instructions: combinedInstructions, model: config3.model, tools: async () => { return { ...await AgentBuilderDefaults.listToolsForMode(config3.projectPath, config3.mode), ...config3.tools || {} }; }, memory, inputProcessors: [ // use the write to disk processor to debug the agent's context // new WriteToDiskProcessor({ prefix: 'before-filter' }), new ToolSummaryProcessor({ summaryModel: config3.summaryModel || config3.model }) // new WriteToDiskProcessor({ prefix: 'after-filter' }), ] }; super(agentConfig); this.builderConfig = config3; } /** * Enhanced generate method with AgentBuilder-specific configuration * Overrides the base Agent generate method to provide additional project context */ generateLegacy = async (messages, generateOptions = {}) => { const { maxSteps, ...baseOptions } = generateOptions; const originalInstructions = await this.getInstructions({ requestContext: generateOptions?.requestContext }); const additionalInstructions = baseOptions.instructions; let enhancedInstructions = originalInstructions; if (additionalInstructions) { enhancedInstructions = `${originalInstructions} ${additionalInstructions}`; } const enhancedContext = [...baseOptions.context || []]; const enhancedOptions = { ...baseOptions, maxSteps: maxSteps || 100, // Higher default for code generation temperature: 0.3, // Lower temperature for more consistent code generation instructions: enhancedInstructions, context: enhancedContext }; this.logger.debug("Starting generation with enhanced context", { agent: this.name, projectPath: this.builderConfig.projectPath }); return super.generateLegacy(messages, enhancedOptions); }; /** * Enhanced stream method with AgentBuilder-specific configuration * Overrides the base Agent stream method to provide additional project context */ streamLegacy = async (messages, streamOptions = {}) => { const { maxSteps, ...baseOptions } = streamOptions; const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext }); const additionalInstructions = baseOptions.instructions; let enhancedInstructions = originalInstructions; if (additionalInstructions) { enhancedInstructions = `${originalInstructions} ${additionalInstructions}`; } const enhancedContext = [...baseOptions.context || []]; const enhancedOptions = { ...baseOptions, maxSteps: maxSteps || 100, // Higher default for code generation temperature: 0.3, // Lower temperature for more consistent code generation instructions: enhancedInstructions, context: enhancedContext }; this.logger.debug("Starting streaming with enhanced context", { agent: this.name, projectPath: this.builderConfig.projectPath }); return super.streamLegacy(messages, enhancedOptions); }; async stream(messages, streamOptions) { const { ...baseOptions } = streamOptions || {}; const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext }); const additionalInstructions = baseOptions.instructions; let enhancedInstructions = originalInstructions; if (additionalInstructions) { enhancedInstructions = `${originalInstructions} ${additionalInstructions}`; } const enhancedContext = [...baseOptions.context || []]; const enhancedOptions = { ...baseOptions, temperature: 0.3, // Lower temperature for more consistent code generation maxSteps: baseOptions?.maxSteps || 100, instructions: enhancedInstructions, context: enhancedContext }; this.logger.debug("Starting streaming with enhanced context", { agent: this.name, projectPath: this.builderConfig.projectPath }); return super.stream(messages, enhancedOptions); } async generate(messages, options) { const { ...baseOptions } = options || {}; const originalInstructions = await this.getInstructions({ requestContext: options?.requestContext }); const additionalInstructions = baseOptions.instructions; let enhancedInstructions = originalInstructions; if (additionalInstructions) { enhancedInstructions = `${originalInstructions} ${additionalInstructions}`; } const enhancedContext = [...baseOptions.context || []]; const enhancedOptions = { ...baseOptions, temperature: 0.3, // Lower temperature for more consistent code generation maxSteps: baseOptions?.maxSteps || 100, instructions: enhancedInstructions, context: enhancedContext }; this.logger.debug("Starting generation with enhanced context", { agent: this.name, projectPath: this.builderConfig.projectPath }); return super.generate(messages, enhancedOptions); } }; var cloneTemplateStep = workflows.createStep({ id: "clone-template", description: "Clone the template repository to a temporary directory at the specified ref", inputSchema: AgentBuilderInputSchema, outputSchema: CloneTemplateResultSchema, execute: async ({ inputData }) => { const { repo, ref = "main", slug, targetPath } = inputData; if (!repo) { throw new Error("Repository URL or path is required"); } const inferredSlug = slug || repo.split("/").pop()?.replace(/\.git$/, "") || "template"; const tempDir = await promises.mkdtemp(path.join(os.tmpdir(), "mastra-template-")); try { await gitClone(repo, tempDir); if (ref !== "main" && ref !== "master") { await gitCheckoutRef(tempDir, ref); } const commitSha = await gitRevParse(tempDir, "HEAD"); return { templateDir: tempDir, commitSha: commitSha.trim(), slug: inferredSlug, success: true, targetPath }; } catch (error90) { try { await promises.rm(tempDir, { recursive: true, force: true }); } catch { } return { templateDir: "", commitSha: "", slug: slug || "unknown", success: false, error: `Failed to clone template: ${error90 instanceof Error ? error90.message : String(error90)}`, targetPath }; } } }); var analyzePackageStep = workflows.createStep({ id: "analyze-package", description: "Analyze the template package.json to extract dependency information", inputSchema: CloneTemplateResultSchema, outputSchema: PackageAnalysisSchema, execute: async ({ inputData }) => { console.info("Analyzing template package.json..."); const { templateDir } = inputData; const packageJsonPath = path.join(templateDir, "package.json"); try { const packageJsonContent = await promises.readFile(packageJsonPath, "utf-8"); const packageJson = JSON.parse(packageJsonContent); console.info("Template package.json:", JSON.stringify(packageJson, null, 2)); return { dependencies: packageJson.dependencies || {}, devDependencies: packageJson.devDependencies || {}, peerDependencies: packageJson.peerDependencies || {}, scripts: packageJson.scripts || {}, name: packageJson.name || "", version: packageJson.version || "", description: packageJson.description || "", success: true }; } catch (error90) { console.warn(`Failed to read template package.json: ${error90 instanceof Error ? error90.message : String(error90)}`); return { dependencies: {}, devDependencies: {}, peerDependencies: {}, scripts: {}, name: "", version: "", description: "", success: true // This is a graceful fallback, not a failure }; } } }); var discoverUnitsStep = workflows.createStep({ id: "discover-units", description: "Discover template units by analyzing the templates directory structure", inputSchema: CloneTemplateResultSchema, outputSchema: DiscoveryResultSchema, execute: async ({ inputData, requestContext }) => { const { templateDir } = inputData; const targetPath = resolveTargetPath(inputData, requestContext); const tools = await AgentBuilderDefaults.DEFAULT_TOOLS(templateDir); console.info("targetPath", targetPath); const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: chunkMRD47GBP_cjs.openai("gpt-4.1") }); try { const agent$1 = new agent.Agent({ id: "mastra-project-discoverer", model, instructions: `You are an expert at analyzing Mastra projects. Your task is to scan the provided directory and identify all available units (agents, workflows, tools, MCP servers, networks). Mastra Project Structure Analysis: - Each Mastra project has a structure like: ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.agent}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.workflow}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE["mcp-server"]}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.network} - Analyze TypeScript files in each category directory to identify exported units CRITICAL: YOU MUST USE YOUR TOOLS (readFile, listDirectory) TO DISCOVER THE UNITS IN THE TEMPLATE DIRECTORY. IMPORTANT - Agent Discovery Rules: 1. **Multiple Agent Files**: Some templates have separate files for each agent (e.g., evaluationAgent.ts, researchAgent.ts) 2. **Single File Multiple Agents**: Some files may export multiple agents (look for multiple 'export const' or 'export default' statements) 3. **Agent Identification**: Look for exported variables that are instances of 'new Agent()' or similar patterns 4. **Naming Convention**: Agent names should be extracted from the export name (e.g., 'weatherAgent', 'evaluationAgent') For each Mastra project directory you analyze: 1. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.agent} and identify ALL exported agents 2. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.workflow} and identify ALL exported workflows 3. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool} and identify ALL exported tools 4. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE["mcp-server"]} and identify ALL exported MCP servers 5. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.network} and identify ALL exported networks 6. Scan for any OTHER files in src/mastra that are NOT in the above default folders (e.g., lib/, utils/, types/, etc.) and identify them as 'other' files IMPORTANT - Naming Consistency Rules: - For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension - For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable - use the base filename without extension for the id (e.g., 'util.ts' \u2192 name: 'util') - use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' \u2192 file: 'src/mastra/lib/util.ts') Return the actual exported names of the units, as well as the file names.`, name: "Mastra Project Discoverer", tools: { readFile: tools.readFile, listDirectory: tools.listDirectory } }); const resolvedModel = await agent$1.getModel(); const isSupported = agent.isSupportedLanguageModel(resolvedModel); const prompt = `Analyze the Mastra project directory structure at "${templateDir}". List directory contents using listDirectory tool, and then analyze each file with readFile tool. IMPORTANT: - Look inside the actual file content to find export statements like 'export const agentName = new Agent(...)' - A single file may contain multiple exports - Return the actual exported variable names, as well as the file names - If a directory doesn't exist or has no files, return an empty array Return the analysis in the exact format specified in the output schema.`; const output = zod.z.object({ agents: zod.z.array(zod.z.object({ name: zod.z.string(), file: zod.z.string() })).optional(), workflows: zod.z.array(zod.z.object({ name: zod.z.string(), file: zod.z.string() })).optional(), tools: zod.z.array(zod.z.object({ name: zod.z.string(), file: zod.z.string() })).optional(), mcp: zod.z.array(zod.z.object({ name: zod.z.string(), file: zod.z.string() })).optional(), networks: zod.z.array(zod.z.object({ name: zod.z.string(), file: zod.z.string() })).optional(), other: zod.z.array(zod.z.object({ name: zod.z.string(), file: zod.z.string() })).optional() }); let result; if (isSupported) { result = await agent.tryGenerateWithJsonFallback(agent$1, prompt, { structuredOutput: { schema: output }, maxSteps: 100 }); } else { const standardSchema2 = schema.toStandardSchema(output); const jsonSchema22 = chunk3YQ7NWF6_cjs.standardSchemaToJSONSchema(standardSchema2); result = await agent$1.generateLegacy(prompt, { experimental_output: jsonSchema22, maxSteps: 100 }); } const template = result.object ?? {}; const units = []; template.agents?.forEach((agentId) => { units.push({ kind: "agent", id: agentId.name, file: agentId.file }); }); template.workflows?.forEach((workflowId) => { units.push({ kind: "workflow", id: workflowId.name, file: workflowId.file }); }); template.tools?.forEach((toolId) => { units.push({ kind: "tool", id: toolId.name, file: toolId.file }); }); template.mcp?.forEach((mcpId) => { units.push({ kind: "mcp-server", id: mcpId.name, file: mcpId.file }); }); template.networks?.forEach((networkId) => { units.push({ kind: "network", id: networkId.name, file: networkId.file }); }); template.other?.forEach((otherId) => { units.push({ kind: "other", id: otherId.name, file: otherId.file }); }); console.info("Discovered units:", JSON.stringify(units, null, 2)); if (units.length === 0) { throw new Error(`No Mastra units (agents, workflows, tools) found in template. Possible causes: - Template may not follow standard Mastra structure - AI agent couldn't analyze template files (model/token limits) - Template is empty or in wrong branch Debug steps: - Check template has files in src/mastra/ directories - Try a different branch - Check template repository structure manually`); } return { units, success: true }; } catch (error90) { console.error("Failed to discover units:", error90); return { units: [], success: false, error: `Failed to discover units: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } }); var orderUnitsStep = workflows.createStep({ id: "order-units", description: "Sort units in topological order based on kind weights", inputSchema: DiscoveryResultSchema, outputSchema: OrderedUnitsSchema, execute: async ({ inputData }) => { const { units } = inputData; const orderedUnits = [...units].sort((a, b) => { const aWeight = kindWeight(a.kind); const bWeight = kindWeight(b.kind); return aWeight - bWeight; }); return { orderedUnits, success: true }; } }); var prepareBranchStep = workflows.createStep({ id: "prepare-branch", description: "Create or switch to integration branch before modifications", inputSchema: PrepareBranchInputSchema, outputSchema: PrepareBranchResultSchema, execute: async ({ inputData, requestContext }) => { const targetPath = resolveTargetPath(inputData, requestContext); try { const branchName = `feat/install-template-${inputData.slug}`; await gitCheckoutBranch(branchName, targetPath); return { branchName, success: true }; } catch (error90) { console.error("Failed to prepare branch:", error90); return { branchName: `feat/install-template-${inputData.slug}`, // Return the intended name anyway success: false, error: `Failed to prepare branch: ${error90 instanceof Error ? error90.message : String(error90)}` }; } } }); var packageMergeStep = workflows.createStep({ id: "package-merge", description: "Merge template package.json dependencies into target project", inputSchema: PackageMergeInputSchema, outputSchema: PackageMergeResultSchema, execute: async ({ inputData, requestContext }) => { console.info("Package merge step starting..."); const { slug, packageInfo } = inputData; const targetPath = resolveTargetPath(inputData, requestContext); try { const targetPkgPath = path.join(targetPath, "package.json"); let targetPkgRaw = "{}"; try { targetPkgRaw = await promises.readFile(targetPkgPath, "utf-8"); } catch { console.warn(`No existing package.json at ${targetPkgPath}, creating a new one`); } let targetPkg; try { targetPkg = JSON.parse(targetPkgRaw || "{}"); } catch (e2) { throw new Error( `Failed to parse existing package.json at ${targetPkgPath}: ${e2 instanceof Error ? e2.message : String(e2)}` ); } const ensureObj = (o) => o && typeof o === "object" ? o : {}; targetPkg.dependencies = ensureObj(targetPkg.dependencies); targetPkg.devDependencies = ensureObj(targetPkg.devDependencies); targetPkg.peerDependencies = ensureObj(targetPkg.peerDependencies); targetPkg.scripts = ensureObj(targetPkg.scripts); const tplDeps = ensureObj(packageInfo.dependencies); const tplDevDeps = ensureObj(packageInfo.devDependencies); const tplPeerDeps = ensureObj(packageInfo.peerDependencies); const tplScripts = ensureObj(packageInfo.scripts); const existsAnywhere = (name16) => name16 in targetPkg.dependencies || name16 in targetPkg.devDependencies || name16 in targetPkg.peerDependencies; for (const [name16, ver] of Object.entries(tplDeps)) { if (!existsAnywhere(name16)) { targetPkg.dependencies[name16] = String(ver); } } for (const [name16, ver] of Object.entries(tplDevDeps)) { if (!existsAnywhere(name16)) { targetPkg.devDependencies[name16] = String(ver); } } for (const [name16, ver] of Object.entries(tplPeerDeps)) { if (!(name16 in targetPkg.peerDependencies)) { targetPkg.peerDependencies[name16] = String(ver); } } const prefix = `template:${slug}:`; for (const [name16, cmd] of Object.entries(tplScripts)) { const newKey = `${prefix}${name16}`; if (!(newKey in targetPkg.scripts)) { targetPkg.scripts[newKey] = String(cmd); } } await promises.writeFile(targetPkgPath, JSON.stringify(targetPkg, null, 2), "utf-8"); await gitAddAndCommit(targetPath, `feat(template): merge deps for ${slug}`, [targetPkgPath], { skipIfNoStaged: true }); return { success: true, applied: true, message: `Successfully merged template dependencies for ${slug}` }; } catch (error90) { console.error("Package merge failed:", error90); return { success: false, applied: false, message: `Package merge failed: ${error90 instanceof Error ? error90.message : String(error90)}`, error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var installStep = workflows.createStep({ id: "install", description: "Install packages based on merged package.json", inputSchema: InstallInputSchema, outputSchema: InstallResultSchema, execute: async ({ inputData, requestContext }) => { console.info("Running install step..."); const targetPath = resolveTargetPath(inputData, requestContext); try { await spawnSWPM(targetPath, "install", []); const lock = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock"].map((f) => path.join(targetPath, f)).find((f) => fs.existsSync(f)); if (lock) { await gitAddAndCommit(targetPath, `chore(template): commit lockfile after install`, [lock], { skipIfNoStaged: true }); } return { success: true }; } catch (error90) { console.error("Install failed:", error90); return { success: false, error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var programmaticFileCopyStep = workflows.createStep({ id: "programmatic-file-copy", description: "Programmatically copy template files to target project based on ordered units", inputSchema: FileCopyInputSchema, outputSchema: FileCopyResultSchema, execute: async ({ inputData, requestContext }) => { console.info("Programmatic file copy step starting..."); const { orderedUnits, templateDir, commitSha, slug } = inputData; const targetPath = resolveTargetPath(inputData, requestContext); try { const copiedFiles = []; const conflicts = []; const analyzeNamingConvention = async (directory) => { try { const files = await promises.readdir(path.resolve(targetPath, directory), { withFileTypes: true }); const tsFiles = files.filter((f) => f.isFile() && f.name.endsWith(".ts")).map((f) => f.name); if (tsFiles.length === 0) return "unknown"; const camelCaseCount = tsFiles.filter((f) => /^[a-z][a-zA-Z0-9]*\.ts$/.test(f)).length; const snakeCaseCount = tsFiles.filter((f) => /^[a-z][a-z0-9_]*\.ts$/.test(f) && f.includes("_")).length; const kebabCaseCount = tsFiles.filter((f) => /^[a-z][a-z0-9-]*\.ts$/.test(f) && f.includes("-")).length; const pascalCaseCount = tsFiles.filter((f) => /^[A-Z][a-zA-Z0-9]*\.ts$/.test(f)).length; const max = Math.max(camelCaseCount, snakeCaseCount, kebabCaseCount, pascalCaseCount); if (max === 0) return "unknown"; if (camelCaseCount === max) return "camelCase"; if (snakeCaseCount === max) return "snake_case"; if (kebabCaseCount === max) return "kebab-case"; if (pascalCaseCount === max) return "PascalCase"; return "unknown"; } catch { return "unknown"; } }; const convertNaming = (name16, convention) => { const baseName = path.basename(name16, path.extname(name16)); const ext = path.extname(name16); const toWords = (s) => { return s.replace(/[-_]/g, " ").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/\s+/).filter(Boolean).map((w) => w.toLowerCase()); }; const words = toWords(baseName); switch (convention) { case "camelCase": return words.map((w, i) => i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)).join("") + ext; case "snake_case": return words.join("_") + ext; case "kebab-case": return words.join("-") + ext; case "PascalCase": return words.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") + ext; default: return name16; } }; for (const unit of orderedUnits) { console.info(`Processing ${unit.kind} unit "${unit.id}" from file "${unit.file}"`); let sourceFile; let resolvedUnitFile; if (unit.file.includes("/")) { sourceFile = path.resolve(templateDir, unit.file); resolvedUnitFile = unit.file; } else { const folderPath = AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE[unit.kind]; if (!folderPath) { conflicts.push({ unit: { kind: unit.kind, id: unit.id }, issue: `Unknown unit kind: ${unit.kind}`, sourceFile: unit.file, targetFile: "N/A" }); continue; } resolvedUnitFile = `${folderPath}/${unit.file}`; sourceFile = path.resolve(templateDir, resolvedUnitFile); } if (!fs.existsSync(sourceFile)) { conflicts.push({ unit: { kind: unit.kind, id: unit.id }, issue: `Source file not found: ${sourceFile}`, sourceFile: resolvedUnitFile, targetFile: "N/A" }); continue; } const targetDir = path.dirname(resolvedUnitFile); const namingConvention = await analyzeNamingConvention(targetDir); console.info(`Detected naming convention in ${targetDir}: ${namingConvention}`); const hasExtension = path.extname(unit.id) !== ""; const baseId = hasExtension ? path.basename(unit.id, path.extname(unit.id)) : unit.id; const fileExtension = path.extname(unit.file); const convertedFileName = namingConvention !== "unknown" ? convertNaming(baseId + fileExtension, namingConvention) : baseId + fileExtension; const targetFile = path.resolve(targetPath, targetDir, convertedFileName); if (fs.existsSync(targetFile)) { const strategy = determineConflictStrategy(); console.info(`File exists: ${convertedFileName}, using strategy: ${strategy}`); switch (strategy) { case "skip": conflicts.push({ unit: { kind: unit.kind, id: unit.id }, issue: `File exists - skipped: ${convertedFileName}`, sourceFile: unit.file, targetFile: `${targetDir}/${convertedFileName}` }); console.info(`\u23ED\uFE0F Skipped ${unit.kind} "${unit.id}": file already exists`); continue; case "backup-and-replace": try { await backupAndReplaceFile(sourceFile, targetFile); copiedFiles.push({ source: sourceFile, destination: targetFile, unit: { kind: unit.kind, id: unit.id } }); console.info( `\u{1F504} Replaced ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName} (backup created)` ); continue; } catch (backupError) { conflicts.push({ unit: { kind: unit.kind, id: unit.id }, issue: `Failed to backup and replace: ${backupError instanceof Error ? backupError.message : String(backupError)}`, sourceFile: unit.file, targetFile: `${targetDir}/${convertedFileName}` }); continue; } case "rename": try { const uniqueTargetFile = await renameAndCopyFile(sourceFile, targetFile); copiedFiles.push({ source: sourceFile, destination: uniqueTargetFile, unit: { kind: unit.kind, id: unit.id } }); console.info(`\u{1F4DD} Renamed ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${path.basename(uniqueTargetFile)}`); continue; } catch (renameError) { conflicts.push({ unit: { kind: unit.kind, id: unit.id }, issue: `Failed to rename and copy: ${renameError instanceof Error ? renameError.message : String(renameError)}`, sourceFile: unit.file, targetFile: `${targetDir}/${convertedFileName}` }); continue; } default: conflicts.push({ unit: { kind: unit.kind, id: unit.id }, issue: `Unknown conflict strategy: ${strategy}`, sourceFile: unit.file, targetFile: `${targetDir}/${convertedFileName}` }); continue; } } await promises.mkdir(path.dirname(targetFile), { recursive: true }); try { await promises.copyFile(sourceFile, targetFile); copiedFiles.push({ source: sourceFile, destination: targetFile, unit: { kind: unit.kind, id: unit.id } }); console.info(`\u2713 Copied ${unit.kind} "${unit.id}": ${unit.file} \u2192 ${convertedFileName}`); } catch (copyError) { conflicts.push({ unit: { kind: unit.kind, id: unit.id }, issue: `Failed to copy file: ${copyError instanceof Error ? copyError.message : String(copyError)}`, sourceFile: unit.file, targetFile: `${targetDir}/${convertedFileName}` }); } } try { const targetTsconfig = path.resolve(targetPath, "tsconfig.json"); if (!fs.existsSync(targetTsconfig)) { const templateTsconfig = path.resolve(templateDir, "tsconfig.json"); if (fs.existsSync(templateTsconfig)) { await promises.copyFile(templateTsconfig, targetTsconfig); copiedFiles.push({ source: templateTsconfig, destination: targetTsconfig, unit: { kind: "other", id: "tsconfig.json" } }); console.info("\u2713 Copied tsconfig.json from template to target"); } else { const minimalTsconfig = { compilerOptions: { target: "ES2020", module: "NodeNext", moduleResolution: "NodeNext", strict: false, esModuleInterop: true, skipLibCheck: true, resolveJsonModule: true, outDir: "dist" }, include: ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"], exclude: ["node_modules", "dist", "build", ".next", ".output", ".turbo"] }; await promises.writeFile(targetTsconfig, JSON.stringify(minimalTsconfig, null, 2), "utf-8"); copiedFiles.push({ source: "[generated tsconfig.json]", destination: targetTsconfig, unit: { kind: "other", id: "tsconfig.json" } }); console.info("\u2713 Generated minimal tsconfig.json in target"); } } } catch (e2) { conflicts.push({ unit: { kind: "other", id: "tsconfig.json" }, issue: `Failed to ensure tsconfig.json: ${e2 instanceof Error ? e2.message : String(e2)}`, sourceFile: "tsconfig.json", targetFile: "tsconfig.json" }); } try { const targetMastraIndex = path.resolve(targetPath, "src/mastra/index.ts"); if (!fs.existsSync(targetMastraIndex)) { const templateMastraIndex = path.resolve(templateDir, "src/mastra/index.ts"); if (fs.existsSync(templateMastraIndex)) { if (!fs.existsSync(path.dirname(targetMastraIndex))) { await promises.mkdir(path.dirname(targetMastraIndex), { recursive: true }); } await promises.copyFile(templateMastraIndex, targetMastraIndex); copiedFiles.push({ source: templateMastraIndex, destination: targetMastraIndex, unit: { kind: "other", id: "mastra-index" } }); console.info("\u2713 Copied Mastra index file from template"); } } } catch (e2) { conflicts.push({ unit: { kind: "other", id: "mastra-index" }, issue: `Failed to ensure Mastra index file: ${e2 instanceof Error ? e2.message : String(e2)}`, sourceFile: "src/mastra/index.ts", targetFile: "src/mastra/index.ts" }); } try { const targetGitignore = path.resolve(targetPath, ".gitignore"); const templateGitignore = path.resolve(templateDir, ".gitignore"); const targetExists = fs.existsSync(targetGitignore); const templateExists = fs.existsSync(templateGitignore); if (templateExists) { if (!targetExists) { await promises.copyFile(templateGitignore, targetGitignore); copiedFiles.push({ source: templateGitignore, destination: targetGitignore, unit: { kind: "other", id: "gitignore" } }); console.info("\u2713 Copied .gitignore from template to target"); } else { const targetContent = await promises.readFile(targetGitignore, "utf-8"); const templateContent = await promises.readFile(templateGitignore, "utf-8"); const mergedContent = mergeGitignoreFiles(targetContent, templateContent, slug); if (mergedContent !== targetContent) { const addedLines = mergedContent.split("\n").length - targetContent.split("\n").length; await promises.writeFile(targetGitignore, mergedContent, "utf-8"); copiedFiles.push({ source: templateGitignore, destination: targetGitignore, unit: { kind: "other", id: "gitignore-merge" } }); console.info(`\u2713 Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`); } else { console.info("\u2139 No new .gitignore entries to add from template"); } } } } catch (e2) { conflicts.push({ unit: { kind: "other", id: "gitignore" }, issue: `Failed to handle .gitignore file: ${e2 instanceof Error ? e2.message : String(e2)}`, sourceFile: ".gitignore", targetFile: ".gitignore" }); } try { const { variables } = inputData; if (variables && Object.keys(variables).length > 0) { const targetEnv = path.resolve(targetPath, ".env"); const targetExists = fs.existsSync(targetEnv); if (!targetExists) { const envContent = [ `# Environment variables for ${slug}`, ...Object.entries(variables).map(([key, value]) => `${key}=${value}`) ].join("\n"); await promises.writeFile(targetEnv, envContent, "utf-8"); copiedFiles.push({ source: "[template variables]", destination: targetEnv, unit: { kind: "other", id: "env" } }); console.info(`\u2713 Created .env file with ${Object.keys(variables).length} template variables`); } else { const targetContent = await promises.readFile(targetEnv, "utf-8"); const mergedContent = mergeEnvFiles(targetContent, variables, slug); if (mergedContent !== targetContent) { const addedLines = mergedContent.split("\n").length - targetContent.split("\n").length; await promises.writeFile(targetEnv, mergedContent, "utf-8"); copiedFiles.push({ source: "[template variables]", destination: targetEnv, unit: { kind: "other", id: "env-merge" } }); console.info(`\u2713 Merged new environment variables into existing .env file (${addedLines} new entries)`); } else { console.info("\u2139 No new environment variables to add (all already exist in .env)"); } } } } catch (e2) { conflicts.push({ unit: { kind: "other", id: "env" }, issue: `Failed to handle .env file: ${e2 instanceof Error ? e2.message : String(e2)}`, sourceFile: ".env", targetFile: ".env" }); } if (copiedFiles.length > 0) { try { const fileList = copiedFiles.map((f) => f.destination); await gitAddAndCommit( targetPath, `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`, fileList, { skipIfNoStaged: true } ); console.info(`\u2713 Committed ${copiedFiles.length} copied files`); } catch (commitError) { console.warn("Failed to commit copied files:", commitError); } } const message = `Programmatic file copy completed. Copied ${copiedFiles.length} files, ${conflicts.length} conflicts detected.`; console.info(message); return { success: true, copiedFiles, conflicts, message }; } catch (error90) { console.error("Programmatic file copy failed:", error90); return { success: false, copiedFiles: [], conflicts: [], message: `Programmatic file copy failed: ${error90 instanceof Error ? error90.message : String(error90)}`, error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var intelligentMergeStep = workflows.createStep({ id: "intelligent-merge", description: "Use AgentBuilder to intelligently merge template files", inputSchema: IntelligentMergeInputSchema, outputSchema: IntelligentMergeResultSchema, execute: async ({ inputData, requestContext }) => { console.info("Intelligent merge step starting..."); const { conflicts, copiedFiles, commitSha, slug, templateDir, branchName } = inputData; const targetPath = resolveTargetPath(inputData, requestContext); try { const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: chunkMRD47GBP_cjs.openai("gpt-4.1") }); const copyFileTool = tools.createTool({ id: "copy-file", description: "Copy a file from template to target project (use only for edge cases - most files are already copied programmatically).", inputSchema: zod.z.object({ sourcePath: zod.z.string().describe("Path to the source file relative to template directory"), destinationPath: zod.z.string().describe("Path to the destination file relative to target project") }), outputSchema: zod.z.object({ success: zod.z.boolean(), message: zod.z.string(), errorMessage: zod.z.string().optional() }), execute: async (input) => { try { const { sourcePath, destinationPath } = input; const resolvedSourcePath = path.resolve(templateDir, sourcePath); const resolvedDestinationPath = path.resolve(targetPath, destinationPath); if (fs.existsSync(resolvedSourcePath) && !fs.existsSync(path.dirname(resolvedDestinationPath))) { await promises.mkdir(path.dirname(resolvedDestinationPath), { recursive: true }); } await promises.copyFile(resolvedSourcePath, resolvedDestinationPath); return { success: true, message: `Successfully copied file from ${sourcePath} to ${destinationPath}` }; } catch (err) { return { success: false, message: `Failed to copy file: ${err instanceof Error ? err.message : String(err)}`, errorMessage: err instanceof Error ? err.message : String(err) }; } } }); const agentBuilder = new AgentBuilder({ projectPath: targetPath, mode: "template", model, instructions: ` You are an expert at integrating Mastra template components into existing projects. CRITICAL CONTEXT: - Files have been programmatically copied from template to target project - Your job is to handle integration issues, registration, and validation FILES SUCCESSFULLY COPIED: ${JSON.stringify(copiedFiles, null, 2)} CONFLICTS TO RESOLVE: ${JSON.stringify(conflicts, null, 2)} CRITICAL INSTRUCTIONS: 1. **Package management**: NO need to install packages (already handled by package merge step) 2. **File copying**: Most files are already copied programmatically. Only use copyFile tool for edge cases where additional files are needed for conflict resolution KEY RESPONSIBILITIES: 1. Resolve any conflicts from the programmatic copy step 2. Register components in existing Mastra index file (agents, workflows, networks, mcp-servers) 3. DO NOT register tools in existing Mastra index file - tools should remain standalone 4. Copy additional files ONLY if needed for conflict resolution MASTRA INDEX FILE HANDLING (src/mastra/index.ts): 1. **Verify the file exists** - Call readFile - If it fails with ENOENT (or listDirectory shows it missing) -> copyFile the template version to src/mastra/index.ts, then confirm it now exists - Always verify after copying that the file exists and is accessible 2. **Edit the file** - Always work with the full file content - Generate the complete, correct source (imports, anchors, registrations, formatting) - Keep existing registrations intact and maintain file structure - Ensure proper spacing and organization of new additions 3. **Handle anchors and structure** - When generating new content, ensure you do not duplicate existing imports or object entries - If required anchors (e.g., agents: {}) are missing, add them while generating the new content - Add missing anchors just before the closing brace of the Mastra config - Do not restructure or reorder existing anchors and registrations CRITICAL: ALWAYS use writeFile to update the mastra/index.ts file when needed to register new components. MASTRA-SPECIFIC REGISTRATION: - Agents: Register in existing Mastra index file - Workflows: Register in existing Mastra index file - Networks: Register in existing Mastra index file - MCP servers: Register in existing Mastra index file - Tools: Copy to ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool} but DO NOT register in existing Mastra index file - If an anchor (e.g., "agents: {") is not found, avoid complex restructuring; instead, insert the missing anchor on a new line (e.g., add "agents: {" just before the closing brace of the Mastra config) and then proceed with the other registrations. CONFLICT RESOLUTION AND FILE COPYING: - Only copy files if needed to resolve specific conflicts - When copying files from template: - Ensure you get the right file name and path - Verify the destination directory exists - Maintain the same relative path structure - Only copy files that are actually needed - Preserve existing functionality when resolving conflicts - Focus on registration and conflict resolution, validation will happen in a later step Template information: - Slug: ${slug} - Commit: ${commitSha.substring(0, 7)} - Branch: ${branchName} `, tools: { copyFile: copyFileTool } }); const tasks = []; conflicts.forEach((conflict) => { tasks.push({ id: `conflict-${conflict.unit.kind}-${conflict.unit.id}`, content: `Resolve conflict: ${conflict.issue}`, status: "pending", priority: "high", notes: `Unit: ${conflict.unit.kind}:${conflict.unit.id}, Issue: ${conflict.issue}, Source: ${conflict.sourceFile}, Target: ${conflict.targetFile}` }); }); const registrableKinds = /* @__PURE__ */ new Set(["agent", "workflow", "network", "mcp-server"]); const registrableFiles = copiedFiles.filter((f) => registrableKinds.has(f.unit.kind)); const targetMastraIndex = path.resolve(targetPath, "src/mastra/index.ts"); const mastraIndexExists = fs.existsSync(targetMastraIndex); console.info(`Mastra index exists: ${mastraIndexExists} at ${targetMastraIndex}`); console.info( "Registrable components:", registrableFiles.map((f) => `${f.unit.kind}:${f.unit.id}`) ); if (registrableFiles.length > 0) { tasks.push({ id: "register-components", content: `Register ${registrableFiles.length} components in existing Mastra index file (src/mastra/index.ts)`, status: "pending", priority: "medium", dependencies: conflicts.length > 0 ? conflicts.map((c) => `conflict-${c.unit.kind}-${c.unit.id}`) : void 0, notes: `Components to register: ${registrableFiles.map((f) => `${f.unit.kind}:${f.unit.id}`).join(", ")}` }); } console.info(`Creating task list with ${tasks.length} tasks...`); await AgentBuilderDefaults.manageTaskList({ action: "create", tasks }); await logGitState(targetPath, "before intelligent merge"); const prompt = ` You need to work through a task list to complete the template integration. CRITICAL INSTRUCTIONS: **STEP 1: GET YOUR TASK LIST** 1. Use manageTaskList tool with action "list" to see all pending tasks 2. Work through tasks in dependency order (complete dependencies first) **STEP 2: PROCESS EACH TASK SYSTEMATICALLY** For each task: 1. Use manageTaskList to mark the current task as 'in_progress' 2. Complete the task according to its requirements 3. Use manageTaskList to mark the task as 'completed' when done 4. Continue until all tasks are completed **TASK TYPES AND REQUIREMENTS:** **Conflict Resolution Tasks:** - Analyze the specific conflict and determine best resolution strategy - For file name conflicts: merge content or rename appropriately - For missing files: investigate and copy if needed - For other issues: apply appropriate fixes **Component Registration Task:** - Update main Mastra instance file to register new components - Only register: agents, workflows, networks, mcp-servers - DO NOT register tools in main config - Ensure proper import paths and naming conventions **COMMIT STRATEGY:** - After resolving conflicts: "feat(template): resolve conflicts for ${slug}@${commitSha.substring(0, 7)}" - After registration: "feat(template): register components from ${slug}@${commitSha.substring(0, 7)}" **CRITICAL NOTES:** - Template source: ${templateDir} - Target project: ${targetPath} - Focus ONLY on conflict resolution and component registration - Use executeCommand for git commits after each task - DO NOT perform validation - that's handled by the dedicated validation step Start by listing your tasks and work through them systematically! `; const resolvedModel = await agentBuilder.getModel(); const isSupported = agent.isSupportedLanguageModel(resolvedModel); const result = isSupported ? await agentBuilder.stream(prompt) : await agentBuilder.streamLegacy(prompt); const actualResolutions = []; for await (const chunk of result.fullStream) { if (chunk.type === "step-finish" || chunk.type === "step-start") { const chunkData = "payload" in chunk ? chunk.payload : chunk; console.info({ type: chunk.type, msgId: chunkData.messageId }); } else { console.info(JSON.stringify(chunk, null, 2)); if (chunk.type === "tool-result") { const chunkData = "payload" in chunk ? chunk.payload : chunk; if (chunkData.toolName === "manageTaskList") { try { const toolResult = chunkData.result; if (toolResult.action === "update" && toolResult.status === "completed") { actualResolutions.push({ taskId: toolResult.taskId || "", action: toolResult.action, status: toolResult.status, content: toolResult.content || "", notes: toolResult.notes }); console.info(`\u{1F4CB} Task completed: ${toolResult.taskId} - ${toolResult.content}`); } } catch (parseError) { console.warn("Failed to parse task management result:", parseError); } } } } } await logGitState(targetPath, "after intelligent merge"); const conflictResolutions = conflicts.map((conflict) => { const taskId = `conflict-${conflict.unit.kind}-${conflict.unit.id}`; const actualResolution = actualResolutions.find((r) => r.taskId === taskId); if (actualResolution) { return { unit: conflict.unit, issue: conflict.issue, resolution: actualResolution.notes || actualResolution.content || `Completed: ${conflict.unit.kind} ${conflict.unit.id}`, actualWork: true }; } else { return { unit: conflict.unit, issue: conflict.issue, resolution: `No specific resolution found for ${conflict.unit.kind} ${conflict.unit.id}`, actualWork: false }; } }); await gitAddAndCommit(targetPath, `feat(template): apply intelligent merge for ${slug}`, void 0, { skipIfNoStaged: true }); return { success: true, applied: true, message: `Successfully resolved ${conflicts.length} conflicts from template ${slug}`, conflictsResolved: conflictResolutions }; } catch (error90) { return { success: false, applied: false, message: `Failed to resolve conflicts: ${error90 instanceof Error ? error90.message : String(error90)}`, conflictsResolved: [], error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var validationAndFixStep = workflows.createStep({ id: "validation-and-fix", description: "Validate the merged template code and fix any issues using a specialized agent", inputSchema: ValidationFixInputSchema, outputSchema: ValidationFixResultSchema, execute: async ({ inputData, requestContext }) => { console.info("Validation and fix step starting..."); const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData; const targetPath = resolveTargetPath(inputData, requestContext); const hasChanges = copiedFiles.length > 0 || conflictsResolved && conflictsResolved.length > 0; if (!hasChanges) { console.info("\u23ED\uFE0F Skipping validation - no files copied or conflicts resolved"); return { success: true, applied: false, message: "No changes to validate - template already integrated or no conflicts resolved", validationResults: { valid: true, errorsFixed: 0, remainingErrors: 0 } }; } console.info( `\u{1F4CB} Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved` ); let currentIteration = 1; try { const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: chunkMRD47GBP_cjs.openai("gpt-4.1") }); const allTools = await AgentBuilderDefaults.listToolsForMode(targetPath, "template"); const validationAgent = new agent.Agent({ id: "code-validator-fixer", name: "Code Validator Fixer", description: "Specialized agent for validating and fixing template integration issues", instructions: `You are a code validation and fixing specialist. Your job is to: 1. **Run comprehensive validation** using the validateCode tool to check for: - TypeScript compilation errors - ESLint issues - Import/export problems - Missing dependencies - Index file structure and exports - Component registration correctness - Naming convention compliance 2. **Fix validation errors systematically**: - Use readFile to examine files with errors - Use multiEdit for simple search-replace fixes (single line changes) - Use replaceLines for complex multiline fixes (imports, function signatures, etc.) - Use listDirectory to understand project structure when fixing import paths - Update file contents to resolve TypeScript and linting issues 3. **Choose the right tool for the job**: - multiEdit: Simple replacements, single line changes, small fixes - replaceLines: Multiline imports, function signatures, complex code blocks - writeFile: ONLY for creating new files (never overwrite existing) 4. **Create missing files ONLY when necessary**: - Use writeFile ONLY for creating NEW files that don't exist - NEVER overwrite existing files - use multiEdit or replaceLines instead - Common cases: missing barrel files (index.ts), missing config files, missing type definitions - Always check with readFile first to ensure file doesn't exist 5. **Fix ALL template integration issues**: - Fix import path issues in copied files - Ensure TypeScript imports and exports are correct - Validate integration works properly - Fix files copied with new names based on unit IDs - Update original template imports that reference old filenames - Fix missing imports in index files - Fix incorrect file paths in imports - Fix type mismatches after integration - Fix missing exports in barrel files - Use the COPIED FILES mapping below to fix import paths - Fix any missing dependencies or module resolution issues 6. **Validate index file structure**: - Correct imports for all components - Proper anchor structure (agents: {}, etc.) - No duplicate registrations - Correct export names and paths - Proper formatting and organization 7. **Follow naming conventions**: Import paths: - camelCase: import { myAgent } from './myAgent' - snake_case: import { myAgent } from './my_agent' - kebab-case: import { myAgent } from './my-agent' - PascalCase: import { MyAgent } from './MyAgent' File names: - camelCase: weatherAgent.ts, chatAgent.ts - snake_case: weather_agent.ts, chat_agent.ts - kebab-case: weather-agent.ts, chat-agent.ts - PascalCase: WeatherAgent.ts, ChatAgent.ts Key Rule: Keep variable/export names unchanged, only adapt file names and import paths 8. **Re-validate after fixes** to ensure all issues are resolved CRITICAL: Always validate the entire project first to get a complete picture of issues, then fix them systematically, and re-validate to confirm fixes worked. CRITICAL TOOL SELECTION GUIDE: - **multiEdit**: Use for simple string replacements, single-line changes Example: changing './oldPath' to './newPath' - **replaceLines**: Use for multiline fixes, complex code structures Example: fixing multiline imports, function signatures, or code blocks Usage: replaceLines({ filePath: 'file.ts', startLine: 5, endLine: 8, newContent: 'new multiline content' }) - **writeFile**: ONLY for creating new files that don't exist Example: creating missing index.ts barrel files CRITICAL WRITEFIL\u0415 SAFETY RULES: - ONLY use writeFile for creating NEW files that don't exist - ALWAYS check with readFile first to verify file doesn't exist - NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead - Common valid uses: missing index.ts barrel files, missing type definitions, missing config files CRITICAL IMPORT PATH RESOLUTION: The following files were copied from template with new names: ${JSON.stringify(copiedFiles, null, 2)} When fixing import errors: 1. Check if the missing module corresponds to a copied file 2. Use listDirectory to verify actual filenames in target directories 3. Update import paths to match the actual copied filenames 4. Ensure exported variable names match what's being imported EXAMPLE: If error shows "Cannot find module './tools/download-csv-tool'" but a file was copied as "csv-fetcher-tool.ts", update the import to "./tools/csv-fetcher-tool" ${conflictsResolved ? `CONFLICTS RESOLVED BY INTELLIGENT MERGE: ${JSON.stringify(conflictsResolved, null, 2)} ` : ""} INTEGRATED UNITS: ${JSON.stringify(orderedUnits, null, 2)} Be thorough and methodical. Always use listDirectory to verify actual file existence before fixing imports.`, model, tools: { validateCode: allTools.validateCode, readFile: allTools.readFile, writeFile: allTools.writeFile, multiEdit: allTools.multiEdit, replaceLines: allTools.replaceLines, listDirectory: allTools.listDirectory, executeCommand: allTools.executeCommand } }); console.info("Starting validation and fix agent with internal loop..."); let validationResults = { valid: false, errorsFixed: 0, remainingErrors: 1, // Start with 1 to enter the loop iteration: currentIteration, lastValidationErrors: [] // Store the actual error details }; while (validationResults.remainingErrors > 0 && currentIteration <= maxIterations) { console.info(` === Validation Iteration ${currentIteration} ===`); const iterationPrompt = currentIteration === 1 ? `Please validate the template integration and fix any errors found in the project at ${targetPath}. The template "${slug}" (${commitSha.substring(0, 7)}) was just integrated and may have validation issues that need fixing. Start by running validateCode with all validation types to get a complete picture of any issues, then systematically fix them.` : `Continue validation and fixing for the template integration at ${targetPath}. This is iteration ${currentIteration} of validation. Previous iterations may have fixed some issues, so start by re-running validateCode to see the current state, then fix any remaining issues.`; const resolvedModel = await validationAgent.getModel(); const isSupported = agent.isSupportedLanguageModel(resolvedModel); const output = zod.z.object({ success: zod.z.boolean() }); const result = isSupported ? await agent.tryStreamWithJsonFallback(validationAgent, iterationPrompt, { structuredOutput: { schema: output } }) : await validationAgent.streamLegacy(iterationPrompt, { experimental_output: output }); let iterationErrors = 0; let previousErrors = validationResults.remainingErrors; let lastValidationResult = null; for await (const chunk of result.fullStream) { if (chunk.type === "step-finish" || chunk.type === "step-start") { const chunkData = "payload" in chunk ? chunk.payload : chunk; console.info({ type: chunk.type, msgId: chunkData.messageId, iteration: currentIteration }); } else { console.info(JSON.stringify(chunk, null, 2)); } if (chunk.type === "tool-result") { const chunkData = "payload" in chunk ? chunk.payload : chunk; if (chunkData.toolName === "validateCode") { const toolResult = chunkData.result; lastValidationResult = toolResult; if (toolResult?.summary) { iterationErrors = toolResult.summary.totalErrors || 0; console.info(`Iteration ${currentIteration}: Found ${iterationErrors} errors`); } } } } validationResults.remainingErrors = iterationErrors; validationResults.errorsFixed += Math.max(0, previousErrors - iterationErrors); validationResults.valid = iterationErrors === 0; validationResults.iteration = currentIteration; if (iterationErrors > 0 && lastValidationResult?.errors) { validationResults.lastValidationErrors = lastValidationResult.errors; } console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`); if (iterationErrors === 0) { console.info(`\u2705 All validation issues resolved in ${currentIteration} iterations!`); break; } else if (currentIteration >= maxIterations) { console.info(`\u26A0\uFE0F Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`); break; } currentIteration++; } try { await gitAddAndCommit( targetPath, `fix(template): resolve validation errors for ${slug}@${commitSha.substring(0, 7)}`, void 0, { skipIfNoStaged: true } ); } catch (commitError) { console.warn("Failed to commit validation fixes:", commitError); } const success3 = validationResults.valid; return { success: success3, applied: true, message: `Validation completed in ${currentIteration} iteration${currentIteration > 1 ? "s" : ""}. ${validationResults.valid ? "All issues resolved!" : `${validationResults.remainingErrors} issue${validationResults.remainingErrors > 1 ? "s" : ""} remaining`}`, validationResults: { valid: validationResults.valid, errorsFixed: validationResults.errorsFixed, remainingErrors: validationResults.remainingErrors, errors: validationResults.lastValidationErrors } }; } catch (error90) { console.error("Validation and fix failed:", error90); return { success: false, applied: false, message: `Validation and fix failed: ${error90 instanceof Error ? error90.message : String(error90)}`, validationResults: { valid: false, errorsFixed: 0, remainingErrors: -1 }, error: error90 instanceof Error ? error90.message : String(error90) }; } finally { try { await promises.rm(templateDir, { recursive: true, force: true }); console.info(`\u2713 Cleaned up template directory: ${templateDir}`); } catch (cleanupError) { console.warn("Failed to cleanup template directory:", cleanupError); } } } }); var agentBuilderTemplateWorkflow = workflows.createWorkflow({ id: "agent-builder-template", description: "Merges a Mastra template repository into the current project using intelligent AgentBuilder-powered merging", inputSchema: AgentBuilderInputSchema, outputSchema: ApplyResultSchema, steps: [ cloneTemplateStep, analyzePackageStep, discoverUnitsStep, orderUnitsStep, packageMergeStep, installStep, programmaticFileCopyStep, intelligentMergeStep, validationAndFixStep ] }).then(cloneTemplateStep).map(async ({ getStepResult }) => { const cloneResult = getStepResult(cloneTemplateStep); if (shouldAbortWorkflow(cloneResult)) { throw new Error(`Critical failure in clone step: ${cloneResult.error}`); } return cloneResult; }).parallel([analyzePackageStep, discoverUnitsStep]).map(async ({ getStepResult }) => { const analyzeResult = getStepResult(analyzePackageStep); const discoverResult = getStepResult(discoverUnitsStep); if (shouldAbortWorkflow(analyzeResult)) { throw new Error(`Failure in analyze package step: ${analyzeResult.error || "Package analysis failed"}`); } if (shouldAbortWorkflow(discoverResult)) { throw new Error(`Failure in discover units step: ${discoverResult.error || "Unit discovery failed"}`); } return discoverResult; }).then(orderUnitsStep).map(async ({ getStepResult, getInitData }) => { const cloneResult = getStepResult(cloneTemplateStep); const initData = getInitData(); return { commitSha: cloneResult.commitSha, slug: cloneResult.slug, targetPath: initData.targetPath }; }).then(prepareBranchStep).map(async ({ getStepResult, getInitData }) => { const cloneResult = getStepResult(cloneTemplateStep); const packageResult = getStepResult(analyzePackageStep); const initData = getInitData(); return { commitSha: cloneResult.commitSha, slug: cloneResult.slug, targetPath: initData.targetPath, packageInfo: packageResult }; }).then(packageMergeStep).map(async ({ getInitData }) => { const initData = getInitData(); return { targetPath: initData.targetPath }; }).then(installStep).map(async ({ getStepResult, getInitData }) => { const cloneResult = getStepResult(cloneTemplateStep); const orderResult = getStepResult(orderUnitsStep); const installResult = getStepResult(installStep); const initData = getInitData(); if (shouldAbortWorkflow(installResult)) { throw new Error(`Failure in install step: ${installResult.error || "Install failed"}`); } return { orderedUnits: orderResult.orderedUnits, templateDir: cloneResult.templateDir, commitSha: cloneResult.commitSha, slug: cloneResult.slug, targetPath: initData.targetPath, variables: initData.variables }; }).then(programmaticFileCopyStep).map(async ({ getStepResult, getInitData }) => { const copyResult = getStepResult(programmaticFileCopyStep); const cloneResult = getStepResult(cloneTemplateStep); const initData = getInitData(); return { conflicts: copyResult.conflicts, copiedFiles: copyResult.copiedFiles, commitSha: cloneResult.commitSha, slug: cloneResult.slug, targetPath: initData.targetPath, templateDir: cloneResult.templateDir }; }).then(intelligentMergeStep).map(async ({ getStepResult, getInitData }) => { const cloneResult = getStepResult(cloneTemplateStep); const orderResult = getStepResult(orderUnitsStep); const copyResult = getStepResult(programmaticFileCopyStep); const mergeResult = getStepResult(intelligentMergeStep); const initData = getInitData(); return { commitSha: cloneResult.commitSha, slug: cloneResult.slug, targetPath: initData.targetPath, templateDir: cloneResult.templateDir, orderedUnits: orderResult.orderedUnits, copiedFiles: copyResult.copiedFiles, conflictsResolved: mergeResult.conflictsResolved }; }).then(validationAndFixStep).map(async ({ getStepResult }) => { const cloneResult = getStepResult(cloneTemplateStep); const analyzeResult = getStepResult(analyzePackageStep); const discoverResult = getStepResult(discoverUnitsStep); const orderResult = getStepResult(orderUnitsStep); const prepareBranchResult = getStepResult(prepareBranchStep); const packageMergeResult = getStepResult(packageMergeStep); const installResult = getStepResult(installStep); const copyResult = getStepResult(programmaticFileCopyStep); const intelligentMergeResult = getStepResult(intelligentMergeStep); const validationResult = getStepResult(validationAndFixStep); const branchName = prepareBranchResult.branchName; const allErrors = [ cloneResult.error, analyzeResult.error, discoverResult.error, orderResult.error, prepareBranchResult.error, packageMergeResult.error, installResult.error, copyResult.error, intelligentMergeResult.error, validationResult.error ].filter(Boolean); const overallSuccess = cloneResult.success !== false && analyzeResult.success !== false && discoverResult.success !== false && orderResult.success !== false && prepareBranchResult.success !== false && packageMergeResult.success !== false && installResult.success !== false && copyResult.success !== false && intelligentMergeResult.success !== false && validationResult.success !== false; const messages = []; if (copyResult.copiedFiles?.length > 0) { messages.push(`${copyResult.copiedFiles.length} files copied`); } if (copyResult.conflicts?.length > 0) { messages.push(`${copyResult.conflicts.length} conflicts skipped`); } if (intelligentMergeResult.conflictsResolved?.length > 0) { messages.push(`${intelligentMergeResult.conflictsResolved.length} conflicts resolved`); } if (validationResult.validationResults?.errorsFixed > 0) { messages.push(`${validationResult.validationResults.errorsFixed} validation errors fixed`); } if (validationResult.validationResults?.remainingErrors > 0) { messages.push(`${validationResult.validationResults.remainingErrors} validation issues remain`); } const comprehensiveMessage = messages.length > 0 ? `Template merge completed: ${messages.join(", ")}` : validationResult.message || "Template merge completed"; return { success: overallSuccess, applied: validationResult.applied || copyResult.copiedFiles?.length > 0 || false, message: comprehensiveMessage, validationResults: validationResult.validationResults, error: allErrors.length > 0 ? allErrors.join("; ") : void 0, errors: allErrors.length > 0 ? allErrors : void 0, branchName, // Additional debugging info stepResults: { cloneSuccess: cloneResult.success, analyzeSuccess: analyzeResult.success, discoverSuccess: discoverResult.success, orderSuccess: orderResult.success, prepareBranchSuccess: prepareBranchResult.success, packageMergeSuccess: packageMergeResult.success, installSuccess: installResult.success, copySuccess: copyResult.success, mergeSuccess: intelligentMergeResult.success, validationSuccess: validationResult.success, filesCopied: copyResult.copiedFiles?.length || 0, conflictsSkipped: copyResult.conflicts?.length || 0, conflictsResolved: intelligentMergeResult.conflictsResolved?.length || 0 } }; }).commit(); async function mergeTemplateBySlug(slug, targetPath) { const template = await getMastraTemplate(slug); const run = await agentBuilderTemplateWorkflow.createRun(); return await run.start({ inputData: { repo: template.githubUrl, slug: template.slug, targetPath } }); } var determineConflictStrategy = (_unit, _targetFile) => { return "skip"; }; var shouldAbortWorkflow = (stepResult) => { return stepResult?.success === false || stepResult?.error; }; var marker3 = "vercel.ai.error"; var symbol3 = Symbol.for(marker3); var _a3; var _b5; var AISDKError4 = class _AISDKError5 extends (_b5 = Error, _a3 = symbol3, _b5) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name1422, message, cause }) { super(message); this[_a3] = true; this.name = name1422; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error90) { return _AISDKError5.hasMarker(error90, marker3); } static hasMarker(error90, marker1522) { const markerSymbol = Symbol.for(marker1522); return error90 != null && typeof error90 === "object" && markerSymbol in error90 && typeof error90[markerSymbol] === "boolean" && error90[markerSymbol] === true; } }; var name2 = "AI_APICallError"; var marker27 = `vercel.ai.error.${name2}`; var symbol28 = Symbol.for(marker27); var _a28; var _b25; var APICallError4 = class extends (_b25 = AISDKError4, _a28 = symbol28, _b25) { constructor({ message, url: url3, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name: name2, message, cause }); this[_a28] = true; this.url = url3; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error90) { return AISDKError4.hasMarker(error90, marker27); } }; var name27 = "AI_EmptyResponseBodyError"; var marker32 = `vercel.ai.error.${name27}`; var symbol32 = Symbol.for(marker32); var _a32; var _b35; var EmptyResponseBodyError3 = class extends (_b35 = AISDKError4, _a32 = symbol32, _b35) { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name27, message }); this[_a32] = true; } static isInstance(error90) { return AISDKError4.hasMarker(error90, marker32); } }; function getErrorMessage5(error90) { if (error90 == null) { return "unknown error"; } if (typeof error90 === "string") { return error90; } if (error90 instanceof Error) { return error90.message; } return JSON.stringify(error90); } var name32 = "AI_InvalidArgumentError"; var marker47 = `vercel.ai.error.${name32}`; var symbol47 = Symbol.for(marker47); var _a47; var _b45; var InvalidArgumentError5 = class extends (_b45 = AISDKError4, _a47 = symbol47, _b45) { constructor({ message, cause, argument }) { super({ name: name32, message, cause }); this[_a47] = true; this.argument = argument; } static isInstance(error90) { return AISDKError4.hasMarker(error90, marker47); } }; var name62 = "AI_JSONParseError"; var marker72 = `vercel.ai.error.${name62}`; var symbol72 = Symbol.for(marker72); var _a72; var _b75; var JSONParseError4 = class extends (_b75 = AISDKError4, _a72 = symbol72, _b75) { constructor({ text: text22, cause }) { super({ name: name62, message: `JSON parsing failed: Text: ${text22}. Error message: ${getErrorMessage5(cause)}`, cause }); this[_a72] = true; this.text = text22; } static isInstance(error90) { return AISDKError4.hasMarker(error90, marker72); } }; var name122 = "AI_TypeValidationError"; var marker132 = `vercel.ai.error.${name122}`; var symbol132 = Symbol.for(marker132); var _a132; var _b133; var TypeValidationError4 = class _TypeValidationError5 extends (_b133 = AISDKError4, _a132 = symbol132, _b133) { constructor({ value, cause }) { super({ name: name122, message: `Type validation failed: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage5(cause)}`, cause }); this[_a132] = true; this.value = value; } static isInstance(error90) { return AISDKError4.hasMarker(error90, marker132); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause }) { return _TypeValidationError5.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError5({ value, cause }); } }; var ParseError3 = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; var LF3 = 10; var CR3 = 13; var SPACE3 = 32; function noop3(_arg) { } function createParser3(callbacks) { if (typeof callbacks == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent = noop3, onError = noop3, onRetry = noop3, onComment } = callbacks, pendingFragments = []; let isFirstChunk = true, id, data = "", dataLines = 0, eventType; function feed(chunk) { if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) { const trailing2 = processLines(chunk); trailing2 !== "" && pendingFragments.push(trailing2); return; } if (chunk.indexOf(` `) === -1 && chunk.indexOf("\r") === -1) { pendingFragments.push(chunk); return; } pendingFragments.push(chunk); const input = pendingFragments.join(""); pendingFragments.length = 0; const trailing = processLines(input); trailing !== "" && pendingFragments.push(trailing); } function processLines(chunk) { let searchIndex = 0; if (chunk.indexOf("\r") === -1) { let lfIndex = chunk.indexOf(` `, searchIndex); for (; lfIndex !== -1; ) { if (searchIndex === lfIndex) { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); continue; } const firstCharCode = chunk.charCodeAt(searchIndex); if (isDataPrefix3(chunk, searchIndex, firstCharCode)) { const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE3 ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex); if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF3) { onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(` `, searchIndex); continue; } data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; } else isEventPrefix3(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice( chunk.charCodeAt(searchIndex + 6) === SPACE3 ? searchIndex + 7 : searchIndex + 6, lfIndex ) || void 0 : parseLine(chunk, searchIndex, lfIndex); searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` `, searchIndex); } return chunk.slice(searchIndex); } for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break; parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR3 && chunk.charCodeAt(searchIndex) === LF3 && searchIndex++; } return chunk.slice(searchIndex); } function parseLine(chunk, start, end) { if (start === end) { dispatchEvent(); return; } const firstCharCode = chunk.charCodeAt(start); if (isDataPrefix3(chunk, start, firstCharCode)) { const valueStart = chunk.charCodeAt(start + 5) === SPACE3 ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end); data = dataLines === 0 ? value2 : `${data} ${value2}`, dataLines++; return; } if (isEventPrefix3(chunk, start, firstCharCode)) { eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE3 ? start + 7 : start + 6, end) || void 0; return; } if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) { const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE3 ? start + 4 : start + 3, end); id = value2.includes("\0") ? void 0 : value2; return; } if (firstCharCode === 58) { if (onComment) { const line2 = chunk.slice(start, end); onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE3 ? 2 : 1)); } return; } const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":"); if (fieldSeparatorIndex === -1) { processField(line, "", line); return; } const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE3 ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); processField(field, value, line); } function processField(field, value, line) { switch (field) { case "event": eventType = value || void 0; break; case "data": data = dataLines === 0 ? value : `${data} ${value}`, dataLines++; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError3(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError3( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line } ) ); break; } } function dispatchEvent() { dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0; } function reset(options = {}) { if (options.consume && pendingFragments.length > 0) { const incompleteLine = pendingFragments.join(""); parseLine(incompleteLine, 0, incompleteLine.length); } isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0; } return { feed, reset }; } function isDataPrefix3(chunk, i, firstCharCode) { return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58; } function isEventPrefix3(chunk, i, firstCharCode) { return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58; } var EventSourceParserStream3 = class extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser3({ onEvent: (event) => { controller.enqueue(event); }, onError(error90) { onError === "terminate" ? controller.error(error90) : typeof onError == "function" && onError(error90); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; function combineHeaders3(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {} ); } function extractResponseHeaders3(response) { return Object.fromEntries([...response.headers]); } var createIdGenerator4 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i = 0; i < size; i++) { chars[i] = alphabet[Math.random() * alphabetLength | 0]; } return chars.join(""); }; if (prefix == null) { return generator; } if (alphabet.includes(separator)) { throw new InvalidArgumentError5({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); } return () => `${prefix}${separator}${generator()}`; }; createIdGenerator4(); function isAbortError4(error90) { return (error90 instanceof Error || error90 instanceof DOMException) && (error90.name === "AbortError" || error90.name === "ResponseAborted" || // Next.js error90.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES3 = ["fetch failed", "failed to fetch"]; function handleFetchError3({ error: error90, url: url3, requestBodyValues }) { if (isAbortError4(error90)) { return error90; } if (error90 instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES3.includes(error90.message.toLowerCase())) { const cause = error90.cause; if (cause != null) { return new APICallError4({ message: `Cannot connect to API: ${cause.message}`, cause, url: url3, requestBodyValues, isRetryable: true // retry when network error }); } } return error90; } function getRuntimeEnvironmentUserAgent3(globalThisAny = globalThis) { var _a2232, _b2222, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a2232 = globalThisAny.navigator) == null ? void 0 : _a2232.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b2222 = globalThisAny.process) == null ? void 0 : _b2222.versions) == null ? void 0 : _c.node) { return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; } if (globalThisAny.EdgeRuntime) { return `runtime/vercel-edge`; } return "runtime/unknown"; } function normalizeHeaders3(headers) { if (headers == null) { return {}; } const normalized = {}; if (headers instanceof Headers) { headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); } else { if (!Array.isArray(headers)) { headers = Object.entries(headers); } for (const [key, value] of headers) { if (value != null) { normalized[key.toLowerCase()] = value; } } } return normalized; } function withUserAgentSuffix3(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders3(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION6 = "3.0.25"; var getOriginalFetch4 = () => globalThis.fetch; var getFromApi3 = async ({ url: url3, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch4() }) => { try { const response = await fetch2(url3, { method: "GET", headers: withUserAgentSuffix3( headers, `ai-sdk/provider-utils/${VERSION6}`, getRuntimeEnvironmentUserAgent3() ), signal: abortSignal }); const responseHeaders = extractResponseHeaders3(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url: url3, requestBodyValues: {} }); } catch (error90) { if (isAbortError4(error90) || APICallError4.isInstance(error90)) { throw error90; } throw new APICallError4({ message: "Failed to process error response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: {} }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url3, requestBodyValues: {} }); } catch (error90) { if (error90 instanceof Error) { if (isAbortError4(error90) || APICallError4.isInstance(error90)) { throw error90; } } throw new APICallError4({ message: "Failed to process successful response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: {} }); } } catch (error90) { throw handleFetchError3({ error: error90, url: url3, requestBodyValues: {} }); } }; function loadOptionalSetting3({ settingValue, environmentVariableName }) { if (typeof settingValue === "string") { return settingValue; } if (settingValue != null || typeof process === "undefined") { return void 0; } settingValue = process.env[environmentVariableName]; if (settingValue == null || typeof settingValue !== "string") { return void 0; } return settingValue; } var suspectProtoRx3 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx3 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse5(text22) { const obj = JSON.parse(text22); if (obj === null || typeof obj !== "object") { return obj; } if (suspectProtoRx3.test(text22) === false && suspectConstructorRx3.test(text22) === false) { return obj; } return filter3(obj); } function filter3(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) { throw new SyntaxError("Object contains forbidden prototype property"); } if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { throw new SyntaxError("Object contains forbidden prototype property"); } for (const key in node) { const value = node[key]; if (value && typeof value === "object") { next.push(value); } } } } return obj; } function secureJsonParse3(text22) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e2) { return _parse5(text22); } try { return _parse5(text22); } finally { Error.stackTraceLimit = stackTraceLimit; } } var validatorSymbol3 = /* @__PURE__ */ Symbol.for("vercel.ai.validator"); function validator3(validate) { return { [validatorSymbol3]: true, validate }; } function isValidator3(value) { return typeof value === "object" && value !== null && validatorSymbol3 in value && value[validatorSymbol3] === true && "validate" in value; } function lazyValidator2(createValidator) { let validator22; return () => { if (validator22 == null) { validator22 = createValidator(); } return validator22; }; } function asValidator3(value) { return isValidator3(value) ? value : typeof value === "function" ? value() : standardSchemaValidator2(value); } function standardSchemaValidator2(standardSchema2) { return validator3(async (value) => { const result = await standardSchema2["~standard"].validate(value); return result.issues == null ? { success: true, value: result.value } : { success: false, error: new TypeValidationError4({ value, cause: result.issues }) }; }); } async function validateTypes3({ value, schema }) { const result = await safeValidateTypes4({ value, schema }); if (!result.success) { throw TypeValidationError4.wrap({ value, cause: result.error }); } return result.value; } async function safeValidateTypes4({ value, schema }) { const validator22 = asValidator3(schema); try { if (validator22.validate == null) { return { success: true, value, rawValue: value }; } const result = await validator22.validate(value); if (result.success) { return { success: true, value: result.value, rawValue: value }; } return { success: false, error: TypeValidationError4.wrap({ value, cause: result.error }), rawValue: value }; } catch (error90) { return { success: false, error: TypeValidationError4.wrap({ value, cause: error90 }), rawValue: value }; } } async function parseJSON3({ text: text22, schema }) { try { const value = secureJsonParse3(text22); if (schema == null) { return value; } return validateTypes3({ value, schema }); } catch (error90) { if (JSONParseError4.isInstance(error90) || TypeValidationError4.isInstance(error90)) { throw error90; } throw new JSONParseError4({ text: text22, cause: error90 }); } } async function safeParseJSON4({ text: text22, schema }) { try { const value = secureJsonParse3(text22); if (schema == null) { return { success: true, value, rawValue: value }; } return await safeValidateTypes4({ value, schema }); } catch (error90) { return { success: false, error: JSONParseError4.isInstance(error90) ? error90 : new JSONParseError4({ text: text22, cause: error90 }), rawValue: void 0 }; } } function parseJsonEventStream3({ stream, schema }) { return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream3()).pipeThrough( new TransformStream({ async transform({ data }, controller) { if (data === "[DONE]") { return; } controller.enqueue(await safeParseJSON4({ text: data, schema })); } }) ); } var getOriginalFetch23 = () => globalThis.fetch; var postJsonToApi3 = async ({ url: url3, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi3({ url: url3, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postToApi3 = async ({ url: url3, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch23() }) => { try { const response = await fetch2(url3, { method: "POST", headers: withUserAgentSuffix3( headers, `ai-sdk/provider-utils/${VERSION6}`, getRuntimeEnvironmentUserAgent3() ), body: body.content, signal: abortSignal }); const responseHeaders = extractResponseHeaders3(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url: url3, requestBodyValues: body.values }); } catch (error90) { if (isAbortError4(error90) || APICallError4.isInstance(error90)) { throw error90; } throw new APICallError4({ message: "Failed to process error response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: body.values }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url: url3, requestBodyValues: body.values }); } catch (error90) { if (error90 instanceof Error) { if (isAbortError4(error90) || APICallError4.isInstance(error90)) { throw error90; } } throw new APICallError4({ message: "Failed to process successful response", cause: error90, statusCode: response.status, url: url3, responseHeaders, requestBodyValues: body.values }); } } catch (error90) { throw handleFetchError3({ error: error90, url: url3, requestBodyValues: body.values }); } }; function tool3(tool22) { return tool22; } function createProviderDefinedToolFactoryWithOutputSchema2({ id, name: name2232, inputSchema, outputSchema: outputSchema22 }) { return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool3({ type: "provider-defined", id, name: name2232, args, inputSchema, outputSchema: outputSchema22, execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } async function resolve4(value) { if (typeof value === "function") { value = value(); } return Promise.resolve(value); } var createJsonErrorResponseHandler3 = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url: url3, requestBodyValues }) => { const responseBody = await response.text(); const responseHeaders = extractResponseHeaders3(response); if (responseBody.trim() === "") { return { responseHeaders, value: new APICallError4({ message: response.statusText, url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } try { const parsedError = await parseJSON3({ text: responseBody, schema: errorSchema }); return { responseHeaders, value: new APICallError4({ message: errorToMessage(parsedError), url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, data: parsedError, isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) }) }; } catch (parseError) { return { responseHeaders, value: new APICallError4({ message: response.statusText, url: url3, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } }; var createEventSourceResponseHandler3 = (chunkSchema) => async ({ response }) => { const responseHeaders = extractResponseHeaders3(response); if (response.body == null) { throw new EmptyResponseBodyError3({}); } return { responseHeaders, value: parseJsonEventStream3({ stream: response.body, schema: chunkSchema }) }; }; var createJsonResponseHandler3 = (responseSchema) => async ({ response, url: url3, requestBodyValues }) => { const responseBody = await response.text(); const parsedResult = await safeParseJSON4({ text: responseBody, schema: responseSchema }); const responseHeaders = extractResponseHeaders3(response); if (!parsedResult.success) { throw new APICallError4({ message: "Invalid JSON response", cause: parsedResult.error, statusCode: response.status, responseHeaders, responseBody, url: url3, requestBodyValues }); } return { responseHeaders, value: parsedResult.value, rawValue: parsedResult.rawValue }; }; var schemaSymbol4 = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema3(createSchema) { let schema; return () => { if (schema == null) { schema = createSchema(); } return schema; }; } function jsonSchema4(jsonSchema22, { validate } = {}) { return { [schemaSymbol4]: true, _type: void 0, // should never be used directly [validatorSymbol3]: true, get jsonSchema() { if (typeof jsonSchema22 === "function") { jsonSchema22 = jsonSchema22(); } return jsonSchema22; }, validate }; } function addAdditionalPropertiesToJsonSchema3(jsonSchema22) { if (jsonSchema22.type === "object") { jsonSchema22.additionalProperties = false; const properties = jsonSchema22.properties; if (properties != null) { for (const property in properties) { properties[property] = addAdditionalPropertiesToJsonSchema3( properties[property] ); } } } if (jsonSchema22.type === "array" && jsonSchema22.items != null) { if (Array.isArray(jsonSchema22.items)) { jsonSchema22.items = jsonSchema22.items.map( (item) => addAdditionalPropertiesToJsonSchema3(item) ); } else { jsonSchema22.items = addAdditionalPropertiesToJsonSchema3( jsonSchema22.items ); } } return jsonSchema22; } var ignoreOverride4 = /* @__PURE__ */ Symbol( "Let zodToJsonSchema decide on which parser to use" ); var defaultOptions4 = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions4 = (options) => typeof options === "string" ? { ...defaultOptions4, name: options } : { ...defaultOptions4, ...options }; function parseAnyDef4() { return {}; } function parseArrayDef4(def, refs) { var _a2232, _b2222, _c; const res = { type: "array" }; if (((_a2232 = def.type) == null ? void 0 : _a2232._def) && ((_c = (_b2222 = def.type) == null ? void 0 : _b2222._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) { res.items = parseDef4(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { res.minItems = def.minLength.value; } if (def.maxLength) { res.maxItems = def.maxLength.value; } if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef4(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "min": if (check3.inclusive) { res.minimum = check3.value; } else { res.exclusiveMinimum = check3.value; } break; case "max": if (check3.inclusive) { res.maximum = check3.value; } else { res.exclusiveMaximum = check3.value; } break; case "multipleOf": res.multipleOf = check3.value; break; } } return res; } function parseBooleanDef4() { return { type: "boolean" }; } function parseBrandedDef4(_def, refs) { return parseDef4(_def.type._def, refs); } var parseCatchDef4 = (def, refs) => { return parseDef4(def.innerType._def, refs); }; function parseDateDef4(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef4(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 integerDateParser4(def); } } var integerDateParser4 = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check3 of def.checks) { switch (check3.kind) { case "min": res.minimum = check3.value; break; case "max": res.maximum = check3.value; break; } } return res; }; function parseDefaultDef4(_def, refs) { return { ...parseDef4(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef4(_def, refs) { return refs.effectStrategy === "input" ? parseDef4(_def.schema._def, refs) : parseAnyDef4(); } function parseEnumDef4(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType4 = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef4(def, refs) { const allOf = [ parseDef4(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef4(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType4(schema)) { mergedAllOf.push(...schema.allOf); } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef4(def) { const parsedType5 = typeof def.value; if (parsedType5 !== "bigint" && parsedType5 !== "number" && parsedType5 !== "boolean" && parsedType5 !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } return { type: parsedType5 === "bigint" ? "integer" : parsedType5, const: def.value }; } var emojiRegex3 = void 0; var zodPatterns4 = { /** * `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 (emojiRegex3 === void 0) { emojiRegex3 = RegExp( "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u" ); } return emojiRegex3; }, /** * 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 parseStringDef4(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check3 of def.checks) { switch (check3.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat4(res, "email", check3.message, refs); break; case "format:idn-email": addFormat4(res, "idn-email", check3.message, refs); break; case "pattern:zod": addPattern4(res, zodPatterns4.email, check3.message, refs); break; } break; case "url": addFormat4(res, "uri", check3.message, refs); break; case "uuid": addFormat4(res, "uuid", check3.message, refs); break; case "regex": addPattern4(res, check3.regex, check3.message, refs); break; case "cuid": addPattern4(res, zodPatterns4.cuid, check3.message, refs); break; case "cuid2": addPattern4(res, zodPatterns4.cuid2, check3.message, refs); break; case "startsWith": addPattern4( res, RegExp(`^${escapeLiteralCheckValue4(check3.value, refs)}`), check3.message, refs ); break; case "endsWith": addPattern4( res, RegExp(`${escapeLiteralCheckValue4(check3.value, refs)}$`), check3.message, refs ); break; case "datetime": addFormat4(res, "date-time", check3.message, refs); break; case "date": addFormat4(res, "date", check3.message, refs); break; case "time": addFormat4(res, "time", check3.message, refs); break; case "duration": addFormat4(res, "duration", check3.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check3.value) : check3.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check3.value) : check3.value; break; case "includes": { addPattern4( res, RegExp(escapeLiteralCheckValue4(check3.value, refs)), check3.message, refs ); break; } case "ip": { if (check3.version !== "v6") { addFormat4(res, "ipv4", check3.message, refs); } if (check3.version !== "v4") { addFormat4(res, "ipv6", check3.message, refs); } break; } case "base64url": addPattern4(res, zodPatterns4.base64url, check3.message, refs); break; case "jwt": addPattern4(res, zodPatterns4.jwt, check3.message, refs); break; case "cidr": { if (check3.version !== "v6") { addPattern4(res, zodPatterns4.ipv4Cidr, check3.message, refs); } if (check3.version !== "v4") { addPattern4(res, zodPatterns4.ipv6Cidr, check3.message, refs); } break; } case "emoji": addPattern4(res, zodPatterns4.emoji(), check3.message, refs); break; case "ulid": { addPattern4(res, zodPatterns4.ulid, check3.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat4(res, "binary", check3.message, refs); break; } case "contentEncoding:base64": { res.contentEncoding = "base64"; break; } case "pattern:zod": { addPattern4(res, zodPatterns4.base64, check3.message, refs); break; } } break; } case "nanoid": { addPattern4(res, zodPatterns4.nanoid, check3.message, refs); } } } } return res; } function escapeLiteralCheckValue4(literal3, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric4(literal3) : literal3; } var ALPHA_NUMERIC4 = new Set( "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789" ); function escapeNonAlphaNumeric4(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC4.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat4(schema, value, message, refs) { var _a2232; if (schema.format || ((_a2232 = schema.anyOf) == null ? void 0 : _a2232.some((x) => x.format))) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format }); delete schema.format; } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { schema.format = value; } } function addPattern4(schema, regex, message, refs) { var _a2232; if (schema.pattern || ((_a2232 = schema.allOf) == null ? void 0 : _a2232.some((x) => x.pattern))) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern }); delete schema.pattern; } schema.allOf.push({ pattern: stringifyRegExpWithFlags4(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { schema.pattern = stringifyRegExpWithFlags4(regex, refs); } } function stringifyRegExpWithFlags4(regex, refs) { var _a2232; if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), // Case-insensitive m: regex.flags.includes("m"), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes("s") // `.` matches newlines }; 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] === "-" && ((_a2232 = source[i + 2]) == null ? void 0 : _a2232.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 ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } return pattern; } function parseRecordDef4(def, refs) { var _a2232, _b2222, _c, _d, _e, _f; const schema = { type: "object", additionalProperties: (_a2232 = parseDef4(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] })) != null ? _a2232 : refs.allowedAdditionalProperties }; if (((_b2222 = def.keyType) == null ? void 0 : _b2222._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) { const { type, ...keyType } = parseStringDef4(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === v3.ZodFirstPartyTypeKind.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === v3.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) { const { type, ...keyType } = parseBrandedDef4( def.keyType._def, refs ); return { ...schema, propertyNames: keyType }; } return schema; } function parseMapDef4(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef4(def, refs); } const keys = parseDef4(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || parseAnyDef4(); const values = parseDef4(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || parseAnyDef4(); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } function parseNativeEnumDef4(def) { const object22 = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object22[object22[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object22[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 }; } function parseNeverDef4() { return { not: parseAnyDef4() }; } function parseNullDef4() { return { type: "null" }; } var primitiveMappings4 = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef4(def, refs) { const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every( (x) => x._def.typeName in primitiveMappings4 && (!x._def.checks || !x._def.checks.length) )) { const types = options.reduce((types2, x) => { const type = primitiveMappings4[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { 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) { 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((x2) => !acc.includes(x2)) ], [] ) }; } return asAnyOf4(def, refs); } var asAnyOf4 = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map( (x, i) => parseDef4(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 } : void 0; }; function parseNullableDef4(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes( def.innerType._def.typeName ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { return { type: [ primitiveMappings4[def.innerType._def.typeName], "null" ] }; } const base = parseDef4(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } function parseNumberDef4(def) { const res = { type: "number" }; if (!def.checks) return res; for (const check3 of def.checks) { switch (check3.kind) { case "int": res.type = "integer"; break; case "min": if (check3.inclusive) { res.minimum = check3.value; } else { res.exclusiveMinimum = check3.value; } break; case "max": if (check3.inclusive) { res.maximum = check3.value; } else { res.exclusiveMaximum = check3.value; } break; case "multipleOf": res.multipleOf = check3.value; break; } } return res; } function parseObjectDef4(def, refs) { const result = { type: "object", properties: {} }; const required3 = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } const propOptional = safeIsOptional4(propDef); const parsedDef = parseDef4(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required3.push(propName); } } if (required3.length) { result.required = required3; } const additionalProperties = decideAdditionalProperties4(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties4(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef4(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 safeIsOptional4(schema) { try { return schema.isOptional(); } catch (e2) { return true; } } var parseOptionalDef4 = (def, refs) => { var _a2232; if (refs.currentPath.toString() === ((_a2232 = refs.propertyPath) == null ? void 0 : _a2232.toString())) { return parseDef4(def.innerType._def, refs); } const innerSchema = parseDef4(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [{ not: parseAnyDef4() }, innerSchema] } : parseAnyDef4(); }; var parsePipelineDef4 = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef4(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef4(def.out._def, refs); } const a = parseDef4(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef4(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== void 0) }; }; function parsePromiseDef4(def, refs) { return parseDef4(def.type._def, refs); } function parseSetDef4(def, refs) { const items = parseDef4(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { schema.minItems = def.minSize.value; } if (def.maxSize) { schema.maxItems = def.maxSize.value; } return schema; } function parseTupleDef4(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map( (x, i) => parseDef4(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ), additionalItems: parseDef4(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) => parseDef4(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] }) ).reduce( (acc, x) => x === void 0 ? acc : [...acc, x], [] ) }; } } function parseUndefinedDef4() { return { not: parseAnyDef4() }; } function parseUnknownDef4() { return parseAnyDef4(); } var parseReadonlyDef4 = (def, refs) => { return parseDef4(def.innerType._def, refs); }; var selectParser4 = (def, typeName, refs) => { switch (typeName) { case v3.ZodFirstPartyTypeKind.ZodString: return parseStringDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef4(def); case v3.ZodFirstPartyTypeKind.ZodObject: return parseObjectDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef4(def); case v3.ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef4(); case v3.ZodFirstPartyTypeKind.ZodDate: return parseDateDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef4(); case v3.ZodFirstPartyTypeKind.ZodNull: return parseNullDef4(); case v3.ZodFirstPartyTypeKind.ZodArray: return parseArrayDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodUnion: case v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef4(def); case v3.ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef4(def); case v3.ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef4(def); case v3.ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodMap: return parseMapDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodSet: return parseSetDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; case v3.ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodNaN: case v3.ZodFirstPartyTypeKind.ZodNever: return parseNeverDef4(); case v3.ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodAny: return parseAnyDef4(); case v3.ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef4(); case v3.ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef4(def, refs); case v3.ZodFirstPartyTypeKind.ZodFunction: case v3.ZodFirstPartyTypeKind.ZodVoid: case v3.ZodFirstPartyTypeKind.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_) => void 0)(); } }; var getRelativePath4 = (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("/"); }; function parseDef4(def, refs, forceResolution = false) { var _a2232; const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = (_a2232 = refs.override) == null ? void 0 : _a2232.call( refs, def, refs, seenItem, forceResolution ); if (overrideResult !== ignoreOverride4) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref4(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser4(def, def.typeName, refs); const jsonSchema22 = typeof jsonSchemaOrGetter === "function" ? parseDef4(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema22) { addMeta4(def, refs, jsonSchema22); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema22, def, refs); newItem.jsonSchema = jsonSchema22; return postProcessResult; } newItem.jsonSchema = jsonSchema22; return jsonSchema22; } var get$ref4 = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath4(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 parseAnyDef4(); } return refs.$refStrategy === "seen" ? parseAnyDef4() : void 0; } } }; var addMeta4 = (def, refs, jsonSchema22) => { if (def.description) { jsonSchema22.description = def.description; } return jsonSchema22; }; var getRefs4 = (options) => { const _options = getDefaultOptions4(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, currentPath, propertyPath: void 0, seen: new Map( Object.entries(_options.definitions).map(([name2232, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name2232], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ]) ) }; }; var zodToJsonSchema3 = (schema, options) => { var _a2232; const refs = getRefs4(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce( (acc, [name323, schema2]) => { var _a323; return { ...acc, [name323]: (_a323 = parseDef4( schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name323] }, true )) != null ? _a323 : parseAnyDef4() }; }, {} ) : void 0; const name2232 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name; const main = (_a2232 = parseDef4( schema._def, name2232 === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name2232] }, false )) != null ? _a2232 : parseAnyDef4(); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main.title = title; } const combined = name2232 === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name2232 ].join("/"), [refs.definitionPath]: { ...definitions, [name2232]: main } }; combined.$schema = "http://json-schema.org/draft-07/schema#"; return combined; }; var zod_to_json_schema_default2 = zodToJsonSchema3; function zod3Schema3(zodSchema22, options) { var _a2232; const useReferences = (_a2232 = void 0) != null ? _a2232 : false; return jsonSchema4( // defer json schema creation to avoid unnecessary computation when only validation is needed () => zod_to_json_schema_default2(zodSchema22, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => { const result = await zodSchema22.safeParseAsync(value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function zod4Schema3(zodSchema22, options) { var _a2232; const useReferences = (_a2232 = void 0) != null ? _a2232 : false; return jsonSchema4( // defer json schema creation to avoid unnecessary computation when only validation is needed () => addAdditionalPropertiesToJsonSchema3( z4__namespace.toJSONSchema(zodSchema22, { target: "draft-7", io: "input", reused: useReferences ? "ref" : "inline" }) ), { validate: async (value) => { const result = await z4__namespace.safeParseAsync(zodSchema22, value); return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; } } ); } function isZod4Schema3(zodSchema22) { return "_zod" in zodSchema22; } function zodSchema4(zodSchema22, options) { if (isZod4Schema3(zodSchema22)) { return zod4Schema3(zodSchema22); } else { return zod3Schema3(zodSchema22); } } function isSchema4(value) { return typeof value === "object" && value !== null && schemaSymbol4 in value && value[schemaSymbol4] === true && "jsonSchema" in value && "validate" in value; } function asSchema4(schema) { return schema == null ? jsonSchema4({ properties: {}, additionalProperties: false }) : isSchema4(schema) ? schema : typeof schema === "function" ? schema() : zodSchema4(schema); } function withoutTrailingSlash3(url3) { return url3 == null ? void 0 : url3.replace(/\/$/, ""); } function getContext3() { return { headers: {} }; } async function getVercelOidcToken3() { if (process.env.VERCEL_OIDC_TOKEN) { return process.env.VERCEL_OIDC_TOKEN ?? ""; } throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead."); } var marker16 = "vercel.ai.gateway.error"; var symbol16 = Symbol.for(marker16); var _a16; var _b162; var GatewayError3 = class _GatewayError3 extends (_b162 = Error, _a16 = symbol16, _b162) { constructor({ message, statusCode = 500, cause }) { super(message); this[_a16] = true; this.statusCode = statusCode; this.cause = cause; } /** * Checks if the given error is a Gateway Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is a Gateway Error, false otherwise. */ static isInstance(error90) { return _GatewayError3.hasMarker(error90); } static hasMarker(error90) { return typeof error90 === "object" && error90 !== null && symbol16 in error90 && error90[symbol16] === true; } }; var name15 = "GatewayAuthenticationError"; var marker223 = `vercel.ai.gateway.error.${name15}`; var symbol223 = Symbol.for(marker223); var _a223; var _b222; var GatewayAuthenticationError3 = class _GatewayAuthenticationError3 extends (_b222 = GatewayError3, _a223 = symbol223, _b222) { constructor({ message = "Authentication failed", statusCode = 401, cause } = {}) { super({ message, statusCode, cause }); this[_a223] = true; this.name = name15; this.type = "authentication_error"; } static isInstance(error90) { return GatewayError3.hasMarker(error90) && symbol223 in error90; } /** * Creates a contextual error message when authentication fails */ static createContextualError({ apiKeyProvided, oidcTokenProvided, message = "Authentication failed", statusCode = 401, cause }) { let contextualMessage; if (apiKeyProvided) { contextualMessage = `AI Gateway authentication failed: Invalid API key. Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`; } else if (oidcTokenProvided) { contextualMessage = `AI Gateway authentication failed: Invalid OIDC token. Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token. Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`; } else { contextualMessage = `AI Gateway authentication failed: No authentication provided. Option 1 - API key: Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable. Option 2 - OIDC token: Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`; } return new _GatewayAuthenticationError3({ message: contextualMessage, statusCode, cause }); } }; var name223 = "GatewayInvalidRequestError"; var marker322 = `vercel.ai.gateway.error.${name223}`; var symbol322 = Symbol.for(marker322); var _a322; var _b322; var GatewayInvalidRequestError3 = class extends (_b322 = GatewayError3, _a322 = symbol322, _b322) { constructor({ message = "Invalid request", statusCode = 400, cause } = {}) { super({ message, statusCode, cause }); this[_a322] = true; this.name = name223; this.type = "invalid_request_error"; } static isInstance(error90) { return GatewayError3.hasMarker(error90) && symbol322 in error90; } }; var name322 = "GatewayRateLimitError"; var marker422 = `vercel.ai.gateway.error.${name322}`; var symbol422 = Symbol.for(marker422); var _a422; var _b422; var GatewayRateLimitError3 = class extends (_b422 = GatewayError3, _a422 = symbol422, _b422) { constructor({ message = "Rate limit exceeded", statusCode = 429, cause } = {}) { super({ message, statusCode, cause }); this[_a422] = true; this.name = name322; this.type = "rate_limit_exceeded"; } static isInstance(error90) { return GatewayError3.hasMarker(error90) && symbol422 in error90; } }; var name422 = "GatewayModelNotFoundError"; var marker52 = `vercel.ai.gateway.error.${name422}`; var symbol52 = Symbol.for(marker52); var modelNotFoundParamSchema3 = lazyValidator2( () => zodSchema4( z4.z.object({ modelId: z4.z.string() }) ) ); var _a52; var _b522; var GatewayModelNotFoundError3 = class extends (_b522 = GatewayError3, _a52 = symbol52, _b522) { constructor({ message = "Model not found", statusCode = 404, modelId, cause } = {}) { super({ message, statusCode, cause }); this[_a52] = true; this.name = name422; this.type = "model_not_found"; this.modelId = modelId; } static isInstance(error90) { return GatewayError3.hasMarker(error90) && symbol52 in error90; } }; var name52 = "GatewayInternalServerError"; var marker62 = `vercel.ai.gateway.error.${name52}`; var symbol62 = Symbol.for(marker62); var _a62; var _b622; var GatewayInternalServerError3 = class extends (_b622 = GatewayError3, _a62 = symbol62, _b622) { constructor({ message = "Internal server error", statusCode = 500, cause } = {}) { super({ message, statusCode, cause }); this[_a62] = true; this.name = name52; this.type = "internal_server_error"; } static isInstance(error90) { return GatewayError3.hasMarker(error90) && symbol62 in error90; } }; var name623 = "GatewayResponseError"; var marker722 = `vercel.ai.gateway.error.${name623}`; var symbol722 = Symbol.for(marker722); var _a722; var _b722; var GatewayResponseError3 = class extends (_b722 = GatewayError3, _a722 = symbol722, _b722) { constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause } = {}) { super({ message, statusCode, cause }); this[_a722] = true; this.name = name623; this.type = "response_error"; this.response = response; this.validationError = validationError; } static isInstance(error90) { return GatewayError3.hasMarker(error90) && symbol722 in error90; } }; async function createGatewayErrorFromResponse3({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) { const parseResult = await safeValidateTypes4({ value: response, schema: gatewayErrorResponseSchema3 }); if (!parseResult.success) { return new GatewayResponseError3({ message: `Invalid error response format: ${defaultMessage}`, statusCode, response, validationError: parseResult.error, cause }); } const validatedResponse = parseResult.value; const errorType = validatedResponse.error.type; const message = validatedResponse.error.message; switch (errorType) { case "authentication_error": return GatewayAuthenticationError3.createContextualError({ apiKeyProvided: authMethod === "api-key", oidcTokenProvided: authMethod === "oidc", statusCode, cause }); case "invalid_request_error": return new GatewayInvalidRequestError3({ message, statusCode, cause }); case "rate_limit_exceeded": return new GatewayRateLimitError3({ message, statusCode, cause }); case "model_not_found": { const modelResult = await safeValidateTypes4({ value: validatedResponse.error.param, schema: modelNotFoundParamSchema3 }); return new GatewayModelNotFoundError3({ message, statusCode, modelId: modelResult.success ? modelResult.value.modelId : void 0, cause }); } case "internal_server_error": return new GatewayInternalServerError3({ message, statusCode, cause }); default: return new GatewayInternalServerError3({ message, statusCode, cause }); } } var gatewayErrorResponseSchema3 = lazyValidator2( () => zodSchema4( z4.z.object({ error: z4.z.object({ message: z4.z.string(), type: z4.z.string().nullish(), param: z4.z.unknown().nullish(), code: z4.z.union([z4.z.string(), z4.z.number()]).nullish() }) }) ) ); function extractApiCallResponse3(error90) { if (error90.data !== void 0) { return error90.data; } if (error90.responseBody != null) { try { return JSON.parse(error90.responseBody); } catch (e2) { return error90.responseBody; } } return {}; } var name72 = "GatewayTimeoutError"; var marker82 = `vercel.ai.gateway.error.${name72}`; var symbol82 = Symbol.for(marker82); var _a82; var _b822; var GatewayTimeoutError3 = class _GatewayTimeoutError3 extends (_b822 = GatewayError3, _a82 = symbol82, _b822) { constructor({ message = "Request timed out", statusCode = 408, cause } = {}) { super({ message, statusCode, cause }); this[_a82] = true; this.name = name72; this.type = "timeout_error"; } static isInstance(error90) { return GatewayError3.hasMarker(error90) && symbol82 in error90; } /** * Creates a helpful timeout error message with troubleshooting guidance */ static createTimeoutError({ originalMessage, statusCode = 408, cause }) { const message = `Gateway request timed out: ${originalMessage} This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`; return new _GatewayTimeoutError3({ message, statusCode, cause }); } }; function isTimeoutError3(error90) { if (!(error90 instanceof Error)) { return false; } const errorCode = error90.code; if (typeof errorCode === "string") { const undiciTimeoutCodes = [ "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT" ]; return undiciTimeoutCodes.includes(errorCode); } return false; } async function asGatewayError3(error90, authMethod) { var _a93; if (GatewayError3.isInstance(error90)) { return error90; } if (isTimeoutError3(error90)) { return GatewayTimeoutError3.createTimeoutError({ originalMessage: error90 instanceof Error ? error90.message : "Unknown error", cause: error90 }); } if (APICallError4.isInstance(error90)) { if (error90.cause && isTimeoutError3(error90.cause)) { return GatewayTimeoutError3.createTimeoutError({ originalMessage: error90.message, cause: error90 }); } return await createGatewayErrorFromResponse3({ response: extractApiCallResponse3(error90), statusCode: (_a93 = error90.statusCode) != null ? _a93 : 500, defaultMessage: "Gateway request failed", cause: error90, authMethod }); } return await createGatewayErrorFromResponse3({ response: {}, statusCode: 500, defaultMessage: error90 instanceof Error ? `Gateway request failed: ${error90.message}` : "Unknown Gateway error", cause: error90, authMethod }); } var GATEWAY_AUTH_METHOD_HEADER3 = "ai-gateway-auth-method"; async function parseAuthMethod3(headers) { const result = await safeValidateTypes4({ value: headers[GATEWAY_AUTH_METHOD_HEADER3], schema: gatewayAuthMethodSchema3 }); return result.success ? result.value : void 0; } var gatewayAuthMethodSchema3 = lazyValidator2( () => zodSchema4(z4.z.union([z4.z.literal("api-key"), z4.z.literal("oidc")])) ); var KNOWN_MODEL_TYPES3 = ["embedding", "image", "language"]; var GatewayFetchMetadata3 = class { constructor(config3) { this.config = config3; } async getAvailableModels() { try { const { value } = await getFromApi3({ url: `${this.config.baseURL}/config`, headers: await resolve4(this.config.headers()), successfulResponseHandler: createJsonResponseHandler3( gatewayAvailableModelsResponseSchema3 ), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError3(error90); } } async getCredits() { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi3({ url: `${baseUrl.origin}/v1/credits`, headers: await resolve4(this.config.headers()), successfulResponseHandler: createJsonResponseHandler3( gatewayCreditsResponseSchema3 ), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError3(error90); } } }; var gatewayAvailableModelsResponseSchema3 = lazyValidator2( () => zodSchema4( z4.z.object({ models: z4.z.array( z4.z.object({ id: z4.z.string(), name: z4.z.string(), description: z4.z.string().nullish(), pricing: z4.z.object({ input: z4.z.string(), output: z4.z.string(), input_cache_read: z4.z.string().nullish(), input_cache_write: z4.z.string().nullish() }).transform( ({ input, output, input_cache_read, input_cache_write }) => ({ input, output, ...input_cache_read ? { cachedInputTokens: input_cache_read } : {}, ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {} }) ).nullish(), specification: z4.z.object({ specificationVersion: z4.z.literal("v2"), provider: z4.z.string(), modelId: z4.z.string() }), modelType: z4.z.string().nullish() }) ).transform( (models) => models.filter( (m) => m.modelType == null || KNOWN_MODEL_TYPES3.includes(m.modelType) ) ) }) ) ); var gatewayCreditsResponseSchema3 = lazyValidator2( () => zodSchema4( z4.z.object({ balance: z4.z.string(), total_used: z4.z.string() }).transform(({ balance, total_used }) => ({ balance, totalUsed: total_used })) ) ); var GatewaySpendReport3 = class { constructor(config3) { this.config = config3; } async getSpendReport(params) { try { const baseUrl = new URL(this.config.baseURL); const searchParams = new URLSearchParams(); searchParams.set("start_date", params.startDate); searchParams.set("end_date", params.endDate); if (params.groupBy) { searchParams.set("group_by", params.groupBy); } if (params.datePart) { searchParams.set("date_part", params.datePart); } if (params.userId) { searchParams.set("user_id", params.userId); } if (params.model) { searchParams.set("model", params.model); } if (params.provider) { searchParams.set("provider", params.provider); } if (params.credentialType) { searchParams.set("credential_type", params.credentialType); } if (params.tags && params.tags.length > 0) { searchParams.set("tags", params.tags.join(",")); } const { value } = await getFromApi3({ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`, headers: await resolve4(this.config.headers()), successfulResponseHandler: createJsonResponseHandler3( gatewaySpendReportResponseSchema3 ), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError3(error90); } } }; var gatewaySpendReportResponseSchema3 = lazySchema3( () => zodSchema4( z4.z.object({ results: z4.z.array( z4.z.object({ day: z4.z.string().optional(), hour: z4.z.string().optional(), user: z4.z.string().optional(), model: z4.z.string().optional(), tag: z4.z.string().optional(), provider: z4.z.string().optional(), credential_type: z4.z.enum(["byok", "system"]).optional(), total_cost: z4.z.number(), market_cost: z4.z.number().optional(), input_tokens: z4.z.number().optional(), output_tokens: z4.z.number().optional(), cached_input_tokens: z4.z.number().optional(), cache_creation_input_tokens: z4.z.number().optional(), reasoning_tokens: z4.z.number().optional(), request_count: z4.z.number().optional() }).transform( ({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({ ...rest, ...credential_type !== void 0 ? { credentialType: credential_type } : {}, totalCost: total_cost, ...market_cost !== void 0 ? { marketCost: market_cost } : {}, ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {}, ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {}, ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {}, ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {}, ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {}, ...request_count !== void 0 ? { requestCount: request_count } : {} }) ) ) }) ) ); var GatewayGenerationInfoFetcher3 = class { constructor(config3) { this.config = config3; } async getGenerationInfo(params) { try { const baseUrl = new URL(this.config.baseURL); const { value } = await getFromApi3({ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`, headers: await resolve4(this.config.headers()), successfulResponseHandler: createJsonResponseHandler3( gatewayGenerationInfoResponseSchema3 ), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), fetch: this.config.fetch }); return value; } catch (error90) { throw await asGatewayError3(error90); } } }; var gatewayGenerationInfoResponseSchema3 = lazySchema3( () => zodSchema4( z4.z.object({ data: z4.z.object({ id: z4.z.string(), total_cost: z4.z.number(), upstream_inference_cost: z4.z.number(), usage: z4.z.number(), created_at: z4.z.string(), model: z4.z.string(), is_byok: z4.z.boolean(), provider_name: z4.z.string(), streamed: z4.z.boolean(), finish_reason: z4.z.string(), latency: z4.z.number(), generation_time: z4.z.number(), native_tokens_prompt: z4.z.number(), native_tokens_completion: z4.z.number(), native_tokens_reasoning: z4.z.number(), native_tokens_cached: z4.z.number(), native_tokens_cache_creation: z4.z.number(), billable_web_search_calls: z4.z.number() }).transform( ({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({ ...rest, totalCost: total_cost, upstreamInferenceCost: upstream_inference_cost, createdAt: created_at, isByok: is_byok, providerName: provider_name, finishReason: finish_reason, generationTime: generation_time, promptTokens: native_tokens_prompt, completionTokens: native_tokens_completion, reasoningTokens: native_tokens_reasoning, cachedTokens: native_tokens_cached, cacheCreationTokens: native_tokens_cache_creation, billableWebSearchCalls: billable_web_search_calls }) ) }).transform(({ data }) => data) ) ); var GatewayLanguageModel3 = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v2"; this.supportedUrls = { "*/*": [/.*/] }; } get provider() { return this.config.provider; } async getArgs(options) { const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options; return { args: this.maybeEncodeFileParts(optionsWithoutSignal), warnings: [] }; } async doGenerate(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = await resolve4(this.config.headers()); try { const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi3({ url: this.getUrl(), headers: combineHeaders3( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve4(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createJsonResponseHandler3(z4.z.any()), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { ...responseBody, request: { body: args }, response: { headers: responseHeaders, body: rawResponse }, warnings }; } catch (error90) { throw await asGatewayError3(error90, await parseAuthMethod3(resolvedHeaders)); } } async doStream(options) { const { args, warnings } = await this.getArgs(options); const { abortSignal } = options; const resolvedHeaders = await resolve4(this.config.headers()); try { const { value: response, responseHeaders } = await postJsonToApi3({ url: this.getUrl(), headers: combineHeaders3( resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve4(this.config.o11yHeaders) ), body: args, successfulResponseHandler: createEventSourceResponseHandler3(z4.z.any()), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { stream: response.pipeThrough( new TransformStream({ start(controller) { if (warnings.length > 0) { controller.enqueue({ type: "stream-start", warnings }); } }, transform(chunk, controller) { if (chunk.success) { const streamPart = chunk.value; if (streamPart.type === "raw" && !options.includeRawChunks) { return; } if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") { streamPart.timestamp = new Date(streamPart.timestamp); } controller.enqueue(streamPart); } else { controller.error( chunk.error ); } } }) ), request: { body: args }, response: { headers: responseHeaders } }; } catch (error90) { throw await asGatewayError3(error90, await parseAuthMethod3(resolvedHeaders)); } } isFilePart(part) { return part && typeof part === "object" && "type" in part && part.type === "file"; } /** * Encodes file parts in the prompt to base64. Mutates the passed options * instance directly to avoid copying the file data. * @param options - The options to encode. * @returns The options with the file parts encoded. */ maybeEncodeFileParts(options) { for (const message of options.prompt) { for (const part of message.content) { if (this.isFilePart(part)) { const filePart = part; if (filePart.data instanceof Uint8Array) { const buffer = Uint8Array.from(filePart.data); const base64Data = Buffer.from(buffer).toString("base64"); filePart.data = new URL( `data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}` ); } } } } return options; } getUrl() { return `${this.config.baseURL}/language-model`; } getModelConfigHeaders(modelId, streaming) { return { "ai-language-model-specification-version": "2", "ai-language-model-id": modelId, "ai-language-model-streaming": String(streaming) }; } }; var GatewayEmbeddingModel3 = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v2"; this.maxEmbeddingsPerCall = 2048; this.supportsParallelCalls = true; } get provider() { return this.config.provider; } async doEmbed({ values, headers, abortSignal, providerOptions }) { var _a93; const resolvedHeaders = await resolve4(this.config.headers()); try { const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi3({ url: this.getUrl(), headers: combineHeaders3( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve4(this.config.o11yHeaders) ), body: { input: values.length === 1 ? values[0] : values, ...providerOptions ? { providerOptions } : {} }, successfulResponseHandler: createJsonResponseHandler3( gatewayEmbeddingResponseSchema3 ), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { embeddings: responseBody.embeddings, usage: (_a93 = responseBody.usage) != null ? _a93 : void 0, providerMetadata: responseBody.providerMetadata, response: { headers: responseHeaders, body: rawValue } }; } catch (error90) { throw await asGatewayError3(error90, await parseAuthMethod3(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/embedding-model`; } getModelConfigHeaders() { return { "ai-embedding-model-specification-version": "2", "ai-model-id": this.modelId }; } }; var gatewayEmbeddingResponseSchema3 = lazyValidator2( () => zodSchema4( z4.z.object({ embeddings: z4.z.array(z4.z.array(z4.z.number())), usage: z4.z.object({ tokens: z4.z.number() }).nullish(), providerMetadata: z4.z.record(z4.z.string(), z4.z.record(z4.z.string(), z4.z.unknown())).optional() }) ) ); var GatewayImageModel3 = class { constructor(modelId, config3) { this.modelId = modelId; this.config = config3; this.specificationVersion = "v2"; this.maxImagesPerCall = Number.MAX_SAFE_INTEGER; } get provider() { return this.config.provider; } async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) { var _a93, _b92, _c, _d; const resolvedHeaders = await resolve4(this.config.headers()); try { const { responseHeaders, value: responseBody } = await postJsonToApi3({ url: this.getUrl(), headers: combineHeaders3( resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve4(this.config.o11yHeaders) ), body: { prompt, n, ...size && { size }, ...aspectRatio && { aspectRatio }, ...seed && { seed }, ...providerOptions && { providerOptions } }, successfulResponseHandler: createJsonResponseHandler3( gatewayImageResponseSchema3 ), failedResponseHandler: createJsonErrorResponseHandler3({ errorSchema: z4.z.any(), errorToMessage: (data) => data }), ...abortSignal && { abortSignal }, fetch: this.config.fetch }); return { images: responseBody.images, // Always base64 strings from server warnings: (_a93 = responseBody.warnings) != null ? _a93 : [], providerMetadata: responseBody.providerMetadata, response: { timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId, headers: responseHeaders }, ...responseBody.usage != null && { usage: { inputTokens: (_b92 = responseBody.usage.inputTokens) != null ? _b92 : void 0, outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0, totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0 } } }; } catch (error90) { throw await asGatewayError3(error90, await parseAuthMethod3(resolvedHeaders)); } } getUrl() { return `${this.config.baseURL}/image-model`; } getModelConfigHeaders() { return { "ai-image-model-specification-version": "2", "ai-model-id": this.modelId }; } }; var providerMetadataEntrySchema3 = z4.z.object({ images: z4.z.array(z4.z.unknown()).optional() }).catchall(z4.z.unknown()); var gatewayImageUsageSchema3 = z4.z.object({ inputTokens: z4.z.number().nullish(), outputTokens: z4.z.number().nullish(), totalTokens: z4.z.number().nullish() }); var gatewayImageResponseSchema3 = z4.z.object({ images: z4.z.array(z4.z.string()), // Always base64 strings over the wire warnings: z4.z.array( z4.z.object({ type: z4.z.literal("other"), message: z4.z.string() }) ).optional(), providerMetadata: z4.z.record(z4.z.string(), providerMetadataEntrySchema3).optional(), usage: gatewayImageUsageSchema3.optional() }); var parallelSearchInputSchema3 = lazySchema3( () => zodSchema4( zod.z.object({ objective: zod.z.string().describe( "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters." ), search_queries: zod.z.array(zod.z.string()).optional().describe( "Optional search queries to supplement the objective. Maximum 200 characters per query." ), mode: zod.z.enum(["one-shot", "agentic"]).optional().describe( 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.' ), max_results: zod.z.number().optional().describe( "Maximum number of results to return (1-20). Defaults to 10 if not specified." ), source_policy: zod.z.object({ include_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to include in search results."), exclude_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to exclude from search results."), after_date: zod.z.string().optional().describe( "Only include results published after this date (ISO 8601 format)." ) }).optional().describe( "Source policy for controlling which domains to include/exclude and freshness." ), excerpts: zod.z.object({ max_chars_per_result: zod.z.number().optional().describe("Maximum characters per result."), max_chars_total: zod.z.number().optional().describe("Maximum total characters across all results.") }).optional().describe("Excerpt configuration for controlling result length."), fetch_policy: zod.z.object({ max_age_seconds: zod.z.number().optional().describe( "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content." ) }).optional().describe("Fetch policy for controlling content freshness.") }) ) ); var parallelSearchOutputSchema3 = lazySchema3( () => zodSchema4( zod.z.union([ // Success response zod.z.object({ searchId: zod.z.string(), results: zod.z.array( zod.z.object({ url: zod.z.string(), title: zod.z.string(), excerpt: zod.z.string(), publishDate: zod.z.string().nullable().optional(), relevanceScore: zod.z.number().optional() }) ) }), // Error response zod.z.object({ error: zod.z.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "configuration_error", "unknown" ]), statusCode: zod.z.number().optional(), message: zod.z.string() }) ]) ) ); var parallelSearchToolFactory3 = createProviderDefinedToolFactoryWithOutputSchema2({ id: "gateway.parallel_search", name: "parallel_search", inputSchema: parallelSearchInputSchema3, outputSchema: parallelSearchOutputSchema3 }); var parallelSearch3 = (config3 = {}) => parallelSearchToolFactory3(config3); var perplexitySearchInputSchema3 = lazySchema3( () => zodSchema4( zod.z.object({ query: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).describe( "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries." ), max_results: zod.z.number().optional().describe( "Maximum number of search results to return (1-20, default: 10)" ), max_tokens_per_page: zod.z.number().optional().describe( "Maximum number of tokens to extract per search result page (256-2048, default: 2048)" ), max_tokens: zod.z.number().optional().describe( "Maximum total tokens across all search results (default: 25000, max: 1000000)" ), country: zod.z.string().optional().describe( "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')" ), search_domain_filter: zod.z.array(zod.z.string()).optional().describe( "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']" ), search_language_filter: zod.z.array(zod.z.string()).optional().describe( "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']" ), search_after_date: zod.z.string().optional().describe( "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter." ), search_before_date: zod.z.string().optional().describe( "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter." ), last_updated_after_filter: zod.z.string().optional().describe( "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter." ), last_updated_before_filter: zod.z.string().optional().describe( "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter." ), search_recency_filter: zod.z.enum(["day", "week", "month", "year"]).optional().describe( "Filter results by relative time period. Cannot be used with search_after_date or search_before_date." ) }) ) ); var perplexitySearchOutputSchema3 = lazySchema3( () => zodSchema4( zod.z.union([ // Success response zod.z.object({ results: zod.z.array( zod.z.object({ title: zod.z.string(), url: zod.z.string(), snippet: zod.z.string(), date: zod.z.string().optional(), lastUpdated: zod.z.string().optional() }) ), id: zod.z.string() }), // Error response zod.z.object({ error: zod.z.enum([ "api_error", "rate_limit", "timeout", "invalid_input", "unknown" ]), statusCode: zod.z.number().optional(), message: zod.z.string() }) ]) ) ); var perplexitySearchToolFactory3 = createProviderDefinedToolFactoryWithOutputSchema2({ id: "gateway.perplexity_search", name: "perplexity_search", inputSchema: perplexitySearchInputSchema3, outputSchema: perplexitySearchOutputSchema3 }); var perplexitySearch3 = (config3 = {}) => perplexitySearchToolFactory3(config3); var gatewayTools3 = { /** * Search the web using Parallel AI's Search API for LLM-optimized excerpts. * * Takes a natural language objective and returns relevant excerpts, * replacing multiple keyword searches with a single call for broad * or complex queries. Supports different search types for depth vs * breadth tradeoffs. */ parallelSearch: parallelSearch3, /** * Search the web using Perplexity's Search API for real-time information, * news, research papers, and articles. * * Provides ranked search results with advanced filtering options including * domain, language, date range, and recency filters. */ perplexitySearch: perplexitySearch3 }; async function getVercelRequestId3() { var _a93; return (_a93 = getContext3().headers) == null ? void 0 : _a93["x-vercel-id"]; } var VERSION24 = "2.0.88"; var AI_GATEWAY_PROTOCOL_VERSION3 = "0.0.1"; function createGatewayProvider3(options = {}) { var _a93, _b92; let pendingMetadata = null; let metadataCache = null; const cacheRefreshMillis = (_a93 = options.metadataCacheRefreshMillis) != null ? _a93 : 1e3 * 60 * 5; let lastFetchTime = 0; const baseURL = (_b92 = withoutTrailingSlash3(options.baseURL)) != null ? _b92 : "https://ai-gateway.vercel.sh/v1/ai"; const getHeaders = async () => { const auth = await getGatewayAuthToken3(options); if (auth) { return withUserAgentSuffix3( { Authorization: `Bearer ${auth.token}`, "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION3, [GATEWAY_AUTH_METHOD_HEADER3]: auth.authMethod, ...options.headers }, `ai-sdk/gateway/${VERSION24}` ); } throw GatewayAuthenticationError3.createContextualError({ apiKeyProvided: false, oidcTokenProvided: false, statusCode: 401 }); }; const createO11yHeaders = () => { const deploymentId = loadOptionalSetting3({ settingValue: void 0, environmentVariableName: "VERCEL_DEPLOYMENT_ID" }); const environment = loadOptionalSetting3({ settingValue: void 0, environmentVariableName: "VERCEL_ENV" }); const region = loadOptionalSetting3({ settingValue: void 0, environmentVariableName: "VERCEL_REGION" }); const projectId = loadOptionalSetting3({ settingValue: void 0, environmentVariableName: "VERCEL_PROJECT_ID" }); return async () => { const requestId = await getVercelRequestId3(); return { ...deploymentId && { "ai-o11y-deployment-id": deploymentId }, ...environment && { "ai-o11y-environment": environment }, ...region && { "ai-o11y-region": region }, ...requestId && { "ai-o11y-request-id": requestId }, ...projectId && { "ai-o11y-project-id": projectId } }; }; }; const createLanguageModel = (modelId) => { return new GatewayLanguageModel3(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; const getAvailableModels = async () => { var _a1022, _b102, _c; const now2 = (_c = (_b102 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b102.call(_a1022).getTime()) != null ? _c : Date.now(); if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) { lastFetchTime = now2; pendingMetadata = new GatewayFetchMetadata3({ baseURL, headers: getHeaders, fetch: options.fetch }).getAvailableModels().then((metadata) => { metadataCache = metadata; return metadata; }).catch(async (error90) => { throw await asGatewayError3( error90, await parseAuthMethod3(await getHeaders()) ); }); } return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata; }; const getCredits = async () => { return new GatewayFetchMetadata3({ baseURL, headers: getHeaders, fetch: options.fetch }).getCredits().catch(async (error90) => { throw await asGatewayError3( error90, await parseAuthMethod3(await getHeaders()) ); }); }; const getSpendReport = async (params) => { return new GatewaySpendReport3({ baseURL, headers: getHeaders, fetch: options.fetch }).getSpendReport(params).catch(async (error90) => { throw await asGatewayError3( error90, await parseAuthMethod3(await getHeaders()) ); }); }; const getGenerationInfo = async (params) => { return new GatewayGenerationInfoFetcher3({ baseURL, headers: getHeaders, fetch: options.fetch }).getGenerationInfo(params).catch(async (error90) => { throw await asGatewayError3( error90, await parseAuthMethod3(await getHeaders()) ); }); }; const provider = function(modelId) { if (new.target) { throw new Error( "The Gateway Provider model function cannot be called with the new keyword." ); } return createLanguageModel(modelId); }; provider.getAvailableModels = getAvailableModels; provider.getCredits = getCredits; provider.getSpendReport = getSpendReport; provider.getGenerationInfo = getGenerationInfo; provider.imageModel = (modelId) => { return new GatewayImageModel3(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.languageModel = createLanguageModel; provider.textEmbeddingModel = (modelId) => { return new GatewayEmbeddingModel3(modelId, { provider: "gateway", baseURL, headers: getHeaders, fetch: options.fetch, o11yHeaders: createO11yHeaders() }); }; provider.tools = gatewayTools3; return provider; } createGatewayProvider3(); async function getGatewayAuthToken3(options) { const apiKey = loadOptionalSetting3({ settingValue: options.apiKey, environmentVariableName: "AI_GATEWAY_API_KEY" }); if (apiKey) { return { token: apiKey, authMethod: "api-key" }; } try { const oidcToken = await getVercelOidcToken3(); return { token: oidcToken, authMethod: "oidc" }; } catch (e2) { return null; } } var _globalThis4 = typeof globalThis === "object" ? globalThis : global; var VERSION222 = "1.9.0"; var re4 = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; function _makeCompatibilityCheck4(ownVersion) { var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); var rejectedVersions = /* @__PURE__ */ new Set(); var myVersionMatch = ownVersion.match(re4); if (!myVersionMatch) { return function() { return false; }; } var ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], prerelease: myVersionMatch[4] }; if (ownVersionParsed.prerelease != null) { return function isExactmatch(globalVersion) { return globalVersion === ownVersion; }; } function _reject(v) { rejectedVersions.add(v); return false; } function _accept(v) { acceptedVersions.add(v); return true; } return function isCompatible22(globalVersion) { if (acceptedVersions.has(globalVersion)) { return true; } if (rejectedVersions.has(globalVersion)) { return false; } var globalVersionMatch = globalVersion.match(re4); if (!globalVersionMatch) { return _reject(globalVersion); } var globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], prerelease: globalVersionMatch[4] }; if (globalVersionParsed.prerelease != null) { return _reject(globalVersion); } if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); } if (ownVersionParsed.major === 0) { if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { return _accept(globalVersion); } return _reject(globalVersion); } if (ownVersionParsed.minor <= globalVersionParsed.minor) { return _accept(globalVersion); } return _reject(globalVersion); }; } var isCompatible4 = _makeCompatibilityCheck4(VERSION222); var major4 = VERSION222.split(".")[0]; var GLOBAL_OPENTELEMETRY_API_KEY4 = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major4); var _global4 = _globalThis4; function registerGlobal4(type, instance, diag, allowOverride) { var _a162; if (allowOverride === void 0) { allowOverride = false; } var api = _global4[GLOBAL_OPENTELEMETRY_API_KEY4] = (_a162 = _global4[GLOBAL_OPENTELEMETRY_API_KEY4]) !== null && _a162 !== void 0 ? _a162 : { version: VERSION222 }; if (!allowOverride && api[type]) { var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); diag.error(err.stack || err.message); return false; } if (api.version !== VERSION222) { var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION222); diag.error(err.stack || err.message); return false; } api[type] = instance; diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION222 + "."); return true; } function getGlobal4(type) { var _a162, _b92; var globalVersion = (_a162 = _global4[GLOBAL_OPENTELEMETRY_API_KEY4]) === null || _a162 === void 0 ? void 0 : _a162.version; if (!globalVersion || !isCompatible4(globalVersion)) { return; } return (_b92 = _global4[GLOBAL_OPENTELEMETRY_API_KEY4]) === null || _b92 === void 0 ? void 0 : _b92[type]; } function unregisterGlobal4(type, diag) { diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION222 + "."); var api = _global4[GLOBAL_OPENTELEMETRY_API_KEY4]; if (api) { delete api[type]; } } var __read7 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray7 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var DiagComponentLogger4 = ( /** @class */ (function() { function DiagComponentLogger22(props) { this._namespace = props.namespace || "DiagComponentLogger"; } DiagComponentLogger22.prototype.debug = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy4("debug", this._namespace, args); }; DiagComponentLogger22.prototype.error = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy4("error", this._namespace, args); }; DiagComponentLogger22.prototype.info = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy4("info", this._namespace, args); }; DiagComponentLogger22.prototype.warn = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy4("warn", this._namespace, args); }; DiagComponentLogger22.prototype.verbose = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return logProxy4("verbose", this._namespace, args); }; return DiagComponentLogger22; })() ); function logProxy4(funcName, namespace, args) { var logger = getGlobal4("diag"); if (!logger) { return; } args.unshift(namespace); return logger[funcName].apply(logger, __spreadArray7([], __read7(args), false)); } var DiagLogLevel4; (function(DiagLogLevel22) { DiagLogLevel22[DiagLogLevel22["NONE"] = 0] = "NONE"; DiagLogLevel22[DiagLogLevel22["ERROR"] = 30] = "ERROR"; DiagLogLevel22[DiagLogLevel22["WARN"] = 50] = "WARN"; DiagLogLevel22[DiagLogLevel22["INFO"] = 60] = "INFO"; DiagLogLevel22[DiagLogLevel22["DEBUG"] = 70] = "DEBUG"; DiagLogLevel22[DiagLogLevel22["VERBOSE"] = 80] = "VERBOSE"; DiagLogLevel22[DiagLogLevel22["ALL"] = 9999] = "ALL"; })(DiagLogLevel4 || (DiagLogLevel4 = {})); function createLogLevelDiagLogger4(maxLevel, logger) { if (maxLevel < DiagLogLevel4.NONE) { maxLevel = DiagLogLevel4.NONE; } else if (maxLevel > DiagLogLevel4.ALL) { maxLevel = DiagLogLevel4.ALL; } logger = logger || {}; function _filterFunc(funcName, theLevel) { var theFunc = logger[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { return theFunc.bind(logger); } return function() { }; } return { error: _filterFunc("error", DiagLogLevel4.ERROR), warn: _filterFunc("warn", DiagLogLevel4.WARN), info: _filterFunc("info", DiagLogLevel4.INFO), debug: _filterFunc("debug", DiagLogLevel4.DEBUG), verbose: _filterFunc("verbose", DiagLogLevel4.VERBOSE) }; } var __read24 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray24 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME6 = "diag"; var DiagAPI4 = ( /** @class */ (function() { function DiagAPI22() { function _logProxy(funcName) { return function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var logger = getGlobal4("diag"); if (!logger) return; return logger[funcName].apply(logger, __spreadArray24([], __read24(args), false)); }; } var self = this; var setLogger = function(logger, optionsOrLogLevel) { var _a162, _b92, _c; if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel4.INFO }; } if (logger === self) { var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self.error((_a162 = err.stack) !== null && _a162 !== void 0 ? _a162 : err.message); return false; } if (typeof optionsOrLogLevel === "number") { optionsOrLogLevel = { logLevel: optionsOrLogLevel }; } var oldLogger = getGlobal4("diag"); var newLogger = createLogLevelDiagLogger4((_b92 = optionsOrLogLevel.logLevel) !== null && _b92 !== void 0 ? _b92 : DiagLogLevel4.INFO, logger); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn("Current logger will be overwritten from " + stack); newLogger.warn("Current logger will overwrite one already registered from " + stack); } return registerGlobal4("diag", newLogger, self, true); }; self.setLogger = setLogger; self.disable = function() { unregisterGlobal4(API_NAME6, self); }; self.createComponentLogger = function(options) { return new DiagComponentLogger4(options); }; self.verbose = _logProxy("verbose"); self.debug = _logProxy("debug"); self.info = _logProxy("info"); self.warn = _logProxy("warn"); self.error = _logProxy("error"); } DiagAPI22.instance = function() { if (!this._instance) { this._instance = new DiagAPI22(); } return this._instance; }; return DiagAPI22; })() ); function createContextKey4(description) { return Symbol.for(description); } var BaseContext4 = ( /** @class */ /* @__PURE__ */ (function() { function BaseContext22(parentContext) { var self = this; self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); self.getValue = function(key) { return self._currentContext.get(key); }; self.setValue = function(key, value) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.set(key, value); return context2; }; self.deleteValue = function(key) { var context2 = new BaseContext22(self._currentContext); context2._currentContext.delete(key); return context2; }; } return BaseContext22; })() ); var ROOT_CONTEXT4 = new BaseContext4(); var __read34 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray34 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var NoopContextManager4 = ( /** @class */ (function() { function NoopContextManager22() { } NoopContextManager22.prototype.active = function() { return ROOT_CONTEXT4; }; NoopContextManager22.prototype.with = function(_context, fn, thisArg) { var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return fn.call.apply(fn, __spreadArray34([thisArg], __read34(args), false)); }; NoopContextManager22.prototype.bind = function(_context, target) { return target; }; NoopContextManager22.prototype.enable = function() { return this; }; NoopContextManager22.prototype.disable = function() { return this; }; return NoopContextManager22; })() ); var __read44 = function(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e2; try { while (!(r = i.next()).done) ar.push(r.value); } catch (error90) { e2 = { error: error90 }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e2) throw e2.error; } } return ar; }; var __spreadArray44 = function(to, from, pack) { if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var API_NAME24 = "context"; var NOOP_CONTEXT_MANAGER4 = new NoopContextManager4(); var ContextAPI4 = ( /** @class */ (function() { function ContextAPI22() { } ContextAPI22.getInstance = function() { if (!this._instance) { this._instance = new ContextAPI22(); } return this._instance; }; ContextAPI22.prototype.setGlobalContextManager = function(contextManager) { return registerGlobal4(API_NAME24, contextManager, DiagAPI4.instance()); }; ContextAPI22.prototype.active = function() { return this._getContextManager().active(); }; ContextAPI22.prototype.with = function(context2, fn, thisArg) { var _a162; var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return (_a162 = this._getContextManager()).with.apply(_a162, __spreadArray44([context2, fn, thisArg], __read44(args), false)); }; ContextAPI22.prototype.bind = function(context2, target) { return this._getContextManager().bind(context2, target); }; ContextAPI22.prototype._getContextManager = function() { return getGlobal4(API_NAME24) || NOOP_CONTEXT_MANAGER4; }; ContextAPI22.prototype.disable = function() { this._getContextManager().disable(); unregisterGlobal4(API_NAME24, DiagAPI4.instance()); }; return ContextAPI22; })() ); var TraceFlags4; (function(TraceFlags22) { TraceFlags22[TraceFlags22["NONE"] = 0] = "NONE"; TraceFlags22[TraceFlags22["SAMPLED"] = 1] = "SAMPLED"; })(TraceFlags4 || (TraceFlags4 = {})); var INVALID_SPANID4 = "0000000000000000"; var INVALID_TRACEID4 = "00000000000000000000000000000000"; var INVALID_SPAN_CONTEXT4 = { traceId: INVALID_TRACEID4, spanId: INVALID_SPANID4, traceFlags: TraceFlags4.NONE }; var NonRecordingSpan4 = ( /** @class */ (function() { function NonRecordingSpan22(_spanContext) { if (_spanContext === void 0) { _spanContext = INVALID_SPAN_CONTEXT4; } this._spanContext = _spanContext; } NonRecordingSpan22.prototype.spanContext = function() { return this._spanContext; }; NonRecordingSpan22.prototype.setAttribute = function(_key, _value) { return this; }; NonRecordingSpan22.prototype.setAttributes = function(_attributes) { return this; }; NonRecordingSpan22.prototype.addEvent = function(_name, _attributes) { return this; }; NonRecordingSpan22.prototype.addLink = function(_link) { return this; }; NonRecordingSpan22.prototype.addLinks = function(_links) { return this; }; NonRecordingSpan22.prototype.setStatus = function(_status) { return this; }; NonRecordingSpan22.prototype.updateName = function(_name) { return this; }; NonRecordingSpan22.prototype.end = function(_endTime) { }; NonRecordingSpan22.prototype.isRecording = function() { return false; }; NonRecordingSpan22.prototype.recordException = function(_exception, _time) { }; return NonRecordingSpan22; })() ); var SPAN_KEY4 = createContextKey4("OpenTelemetry Context Key SPAN"); function getSpan4(context2) { return context2.getValue(SPAN_KEY4) || void 0; } function getActiveSpan4() { return getSpan4(ContextAPI4.getInstance().active()); } function setSpan4(context2, span) { return context2.setValue(SPAN_KEY4, span); } function deleteSpan4(context2) { return context2.deleteValue(SPAN_KEY4); } function setSpanContext4(context2, spanContext) { return setSpan4(context2, new NonRecordingSpan4(spanContext)); } function getSpanContext4(context2) { var _a162; return (_a162 = getSpan4(context2)) === null || _a162 === void 0 ? void 0 : _a162.spanContext(); } var VALID_TRACEID_REGEX4 = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX4 = /^[0-9a-f]{16}$/i; function isValidTraceId4(traceId) { return VALID_TRACEID_REGEX4.test(traceId) && traceId !== INVALID_TRACEID4; } function isValidSpanId4(spanId) { return VALID_SPANID_REGEX4.test(spanId) && spanId !== INVALID_SPANID4; } function isSpanContextValid4(spanContext) { return isValidTraceId4(spanContext.traceId) && isValidSpanId4(spanContext.spanId); } function wrapSpanContext4(spanContext) { return new NonRecordingSpan4(spanContext); } var contextApi4 = ContextAPI4.getInstance(); var NoopTracer4 = ( /** @class */ (function() { function NoopTracer22() { } NoopTracer22.prototype.startSpan = function(name16, options, context2) { if (context2 === void 0) { context2 = contextApi4.active(); } var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan4(); } var parentFromContext = context2 && getSpanContext4(context2); if (isSpanContext4(parentFromContext) && isSpanContextValid4(parentFromContext)) { return new NonRecordingSpan4(parentFromContext); } else { return new NonRecordingSpan4(); } }; NoopTracer22.prototype.startActiveSpan = function(name16, arg2, arg3, arg4) { var opts; var ctx; var fn; if (arguments.length < 2) { return; } else if (arguments.length === 2) { fn = arg2; } else if (arguments.length === 3) { opts = arg2; fn = arg3; } else { opts = arg2; ctx = arg3; fn = arg4; } var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi4.active(); var span = this.startSpan(name16, opts, parentContext); var contextWithSpanSet = setSpan4(parentContext, span); return contextApi4.with(contextWithSpanSet, fn, void 0, span); }; return NoopTracer22; })() ); function isSpanContext4(spanContext) { return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; } var NOOP_TRACER4 = new NoopTracer4(); var ProxyTracer4 = ( /** @class */ (function() { function ProxyTracer22(_provider, name16, version3, options) { this._provider = _provider; this.name = name16; this.version = version3; this.options = options; } ProxyTracer22.prototype.startSpan = function(name16, options, context2) { return this._getTracer().startSpan(name16, options, context2); }; ProxyTracer22.prototype.startActiveSpan = function(_name, _options, _context, _fn) { var tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); }; ProxyTracer22.prototype._getTracer = function() { if (this._delegate) { return this._delegate; } var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER4; } this._delegate = tracer; return this._delegate; }; return ProxyTracer22; })() ); var NoopTracerProvider4 = ( /** @class */ (function() { function NoopTracerProvider22() { } NoopTracerProvider22.prototype.getTracer = function(_name, _version, _options) { return new NoopTracer4(); }; return NoopTracerProvider22; })() ); var NOOP_TRACER_PROVIDER4 = new NoopTracerProvider4(); var ProxyTracerProvider4 = ( /** @class */ (function() { function ProxyTracerProvider22() { } ProxyTracerProvider22.prototype.getTracer = function(name16, version3, options) { var _a162; return (_a162 = this.getDelegateTracer(name16, version3, options)) !== null && _a162 !== void 0 ? _a162 : new ProxyTracer4(this, name16, version3, options); }; ProxyTracerProvider22.prototype.getDelegate = function() { var _a162; return (_a162 = this._delegate) !== null && _a162 !== void 0 ? _a162 : NOOP_TRACER_PROVIDER4; }; ProxyTracerProvider22.prototype.setDelegate = function(delegate) { this._delegate = delegate; }; ProxyTracerProvider22.prototype.getDelegateTracer = function(name16, version3, options) { var _a162; return (_a162 = this._delegate) === null || _a162 === void 0 ? void 0 : _a162.getTracer(name16, version3, options); }; return ProxyTracerProvider22; })() ); var SpanStatusCode4; (function(SpanStatusCode22) { SpanStatusCode22[SpanStatusCode22["UNSET"] = 0] = "UNSET"; SpanStatusCode22[SpanStatusCode22["OK"] = 1] = "OK"; SpanStatusCode22[SpanStatusCode22["ERROR"] = 2] = "ERROR"; })(SpanStatusCode4 || (SpanStatusCode4 = {})); var API_NAME34 = "trace"; var TraceAPI4 = ( /** @class */ (function() { function TraceAPI22() { this._proxyTracerProvider = new ProxyTracerProvider4(); this.wrapSpanContext = wrapSpanContext4; this.isSpanContextValid = isSpanContextValid4; this.deleteSpan = deleteSpan4; this.getSpan = getSpan4; this.getActiveSpan = getActiveSpan4; this.getSpanContext = getSpanContext4; this.setSpan = setSpan4; this.setSpanContext = setSpanContext4; } TraceAPI22.getInstance = function() { if (!this._instance) { this._instance = new TraceAPI22(); } return this._instance; }; TraceAPI22.prototype.setGlobalTracerProvider = function(provider) { var success3 = registerGlobal4(API_NAME34, this._proxyTracerProvider, DiagAPI4.instance()); if (success3) { this._proxyTracerProvider.setDelegate(provider); } return success3; }; TraceAPI22.prototype.getTracerProvider = function() { return getGlobal4(API_NAME34) || this._proxyTracerProvider; }; TraceAPI22.prototype.getTracer = function(name16, version3) { return this.getTracerProvider().getTracer(name16, version3); }; TraceAPI22.prototype.disable = function() { unregisterGlobal4(API_NAME34, DiagAPI4.instance()); this._proxyTracerProvider = new ProxyTracerProvider4(); }; return TraceAPI22; })() ); TraceAPI4.getInstance(); var __defProp5 = Object.defineProperty; var __export5 = (target, all) => { for (var name16 in all) __defProp5(target, name16, { get: all[name16], enumerable: true }); }; var name6222 = "AI_NoObjectGeneratedError"; var marker6222 = `vercel.ai.error.${name6222}`; var symbol6222 = Symbol.for(marker6222); var _a6222; var NoObjectGeneratedError4 = class extends AISDKError4 { constructor({ message = "No object generated.", cause, text: text22, response, usage, finishReason }) { super({ name: name6222, message, cause }); this[_a6222] = true; this.text = text22; this.response = response; this.usage = usage; this.finishReason = finishReason; } static isInstance(error90) { return AISDKError4.hasMarker(error90, marker6222); } }; _a6222 = symbol6222; var dataContentSchema4 = z4.z.union([ z4.z.string(), z4.z.instanceof(Uint8Array), z4.z.instanceof(ArrayBuffer), z4.z.custom( // Buffer might not be available in some environments such as CloudFlare: (value) => { var _a162, _b92; return (_b92 = (_a162 = globalThis.Buffer) == null ? void 0 : _a162.isBuffer(value)) != null ? _b92 : false; }, { message: "Must be a Buffer" } ) ]); var jsonValueSchema4 = z4.z.lazy( () => z4.z.union([ z4.z.null(), z4.z.string(), z4.z.number(), z4.z.boolean(), z4.z.record(z4.z.string(), jsonValueSchema4), z4.z.array(jsonValueSchema4) ]) ); var providerMetadataSchema4 = z4.z.record( z4.z.string(), z4.z.record(z4.z.string(), jsonValueSchema4) ); var textPartSchema4 = z4.z.object({ type: z4.z.literal("text"), text: z4.z.string(), providerOptions: providerMetadataSchema4.optional() }); var imagePartSchema4 = z4.z.object({ type: z4.z.literal("image"), image: z4.z.union([dataContentSchema4, z4.z.instanceof(URL)]), mediaType: z4.z.string().optional(), providerOptions: providerMetadataSchema4.optional() }); var filePartSchema4 = z4.z.object({ type: z4.z.literal("file"), data: z4.z.union([dataContentSchema4, z4.z.instanceof(URL)]), filename: z4.z.string().optional(), mediaType: z4.z.string(), providerOptions: providerMetadataSchema4.optional() }); var reasoningPartSchema4 = z4.z.object({ type: z4.z.literal("reasoning"), text: z4.z.string(), providerOptions: providerMetadataSchema4.optional() }); var toolCallPartSchema4 = z4.z.object({ type: z4.z.literal("tool-call"), toolCallId: z4.z.string(), toolName: z4.z.string(), input: z4.z.unknown(), providerOptions: providerMetadataSchema4.optional(), providerExecuted: z4.z.boolean().optional() }); var outputSchema3 = z4.z.discriminatedUnion("type", [ z4.z.object({ type: z4.z.literal("text"), value: z4.z.string() }), z4.z.object({ type: z4.z.literal("json"), value: jsonValueSchema4 }), z4.z.object({ type: z4.z.literal("error-text"), value: z4.z.string() }), z4.z.object({ type: z4.z.literal("error-json"), value: jsonValueSchema4 }), z4.z.object({ type: z4.z.literal("content"), value: z4.z.array( z4.z.union([ z4.z.object({ type: z4.z.literal("text"), text: z4.z.string() }), z4.z.object({ type: z4.z.literal("media"), data: z4.z.string(), mediaType: z4.z.string() }) ]) ) }) ]); var toolResultPartSchema4 = z4.z.object({ type: z4.z.literal("tool-result"), toolCallId: z4.z.string(), toolName: z4.z.string(), output: outputSchema3, providerOptions: providerMetadataSchema4.optional() }); var systemModelMessageSchema3 = z4.z.object( { role: z4.z.literal("system"), content: z4.z.string(), providerOptions: providerMetadataSchema4.optional() } ); var userModelMessageSchema3 = z4.z.object({ role: z4.z.literal("user"), content: z4.z.union([ z4.z.string(), z4.z.array(z4.z.union([textPartSchema4, imagePartSchema4, filePartSchema4])) ]), providerOptions: providerMetadataSchema4.optional() }); var assistantModelMessageSchema3 = z4.z.object({ role: z4.z.literal("assistant"), content: z4.z.union([ z4.z.string(), z4.z.array( z4.z.union([ textPartSchema4, filePartSchema4, reasoningPartSchema4, toolCallPartSchema4, toolResultPartSchema4 ]) ) ]), providerOptions: providerMetadataSchema4.optional() }); var toolModelMessageSchema3 = z4.z.object({ role: z4.z.literal("tool"), content: z4.z.array(toolResultPartSchema4), providerOptions: providerMetadataSchema4.optional() }); z4.z.union([ systemModelMessageSchema3, userModelMessageSchema3, assistantModelMessageSchema3, toolModelMessageSchema3 ]); function stepCountIs(stepCount) { return ({ steps }) => steps.length === stepCount; } createIdGenerator4({ prefix: "aitxt", size: 24 }); function fixJson4(input) { const stack = ["ROOT"]; let lastValidIndex = -1; let literalStart = null; function processValueStart(char, i, swapState) { { switch (char) { case '"': { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_STRING"); break; } case "f": case "t": case "n": { lastValidIndex = i; literalStart = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_LITERAL"); break; } case "-": { stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_NUMBER"); break; } case "{": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_OBJECT_START"); break; } case "[": { lastValidIndex = i; stack.pop(); stack.push(swapState); stack.push("INSIDE_ARRAY_START"); break; } } } } function processAfterObjectValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_COMMA"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } } function processAfterArrayValue(char, i) { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } } } for (let i = 0; i < input.length; i++) { const char = input[i]; const currentState = stack[stack.length - 1]; switch (currentState) { case "ROOT": processValueStart(char, i, "FINISH"); break; case "INSIDE_OBJECT_START": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } case "}": { lastValidIndex = i; stack.pop(); break; } } break; } case "INSIDE_OBJECT_AFTER_COMMA": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_KEY"); break; } } break; } case "INSIDE_OBJECT_KEY": { switch (char) { case '"': { stack.pop(); stack.push("INSIDE_OBJECT_AFTER_KEY"); break; } } break; } case "INSIDE_OBJECT_AFTER_KEY": { switch (char) { case ":": { stack.pop(); stack.push("INSIDE_OBJECT_BEFORE_VALUE"); break; } } break; } case "INSIDE_OBJECT_BEFORE_VALUE": { processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE"); break; } case "INSIDE_OBJECT_AFTER_VALUE": { processAfterObjectValue(char, i); break; } case "INSIDE_STRING": { switch (char) { case '"': { stack.pop(); lastValidIndex = i; break; } case "\\": { stack.push("INSIDE_STRING_ESCAPE"); break; } default: { lastValidIndex = i; } } break; } case "INSIDE_ARRAY_START": { switch (char) { case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } } break; } case "INSIDE_ARRAY_AFTER_VALUE": { switch (char) { case ",": { stack.pop(); stack.push("INSIDE_ARRAY_AFTER_COMMA"); break; } case "]": { lastValidIndex = i; stack.pop(); break; } default: { lastValidIndex = i; break; } } break; } case "INSIDE_ARRAY_AFTER_COMMA": { processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE"); break; } case "INSIDE_STRING_ESCAPE": { stack.pop(); lastValidIndex = i; break; } case "INSIDE_NUMBER": { switch (char) { case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": { lastValidIndex = i; break; } case "e": case "E": case "-": case ".": { break; } case ",": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "}": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } break; } case "]": { stack.pop(); if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } break; } default: { stack.pop(); break; } } break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, i + 1); if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) { stack.pop(); if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") { processAfterObjectValue(char, i); } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") { processAfterArrayValue(char, i); } } else { lastValidIndex = i; } break; } } } let result = input.slice(0, lastValidIndex + 1); for (let i = stack.length - 1; i >= 0; i--) { const state = stack[i]; switch (state) { case "INSIDE_STRING": { result += '"'; break; } case "INSIDE_OBJECT_KEY": case "INSIDE_OBJECT_AFTER_KEY": case "INSIDE_OBJECT_AFTER_COMMA": case "INSIDE_OBJECT_START": case "INSIDE_OBJECT_BEFORE_VALUE": case "INSIDE_OBJECT_AFTER_VALUE": { result += "}"; break; } case "INSIDE_ARRAY_START": case "INSIDE_ARRAY_AFTER_COMMA": case "INSIDE_ARRAY_AFTER_VALUE": { result += "]"; break; } case "INSIDE_LITERAL": { const partialLiteral = input.substring(literalStart, input.length); if ("true".startsWith(partialLiteral)) { result += "true".slice(partialLiteral.length); } else if ("false".startsWith(partialLiteral)) { result += "false".slice(partialLiteral.length); } else if ("null".startsWith(partialLiteral)) { result += "null".slice(partialLiteral.length); } } } } return result; } async function parsePartialJson4(jsonText) { if (jsonText === void 0) { return { value: void 0, state: "undefined-input" }; } let result = await safeParseJSON4({ text: jsonText }); if (result.success) { return { value: result.value, state: "successful-parse" }; } result = await safeParseJSON4({ text: fixJson4(jsonText) }); if (result.success) { return { value: result.value, state: "repaired-parse" }; } return { value: void 0, state: "failed-parse" }; } createIdGenerator4({ prefix: "aitxt", size: 24 }); createIdGenerator4({ prefix: "aiobj", size: 24 }); createIdGenerator4({ prefix: "aiobj", size: 24 }); var output_exports4 = {}; __export5(output_exports4, { object: () => object6, text: () => text4 }); var text4 = () => ({ type: "text", responseFormat: { type: "text" }, async parsePartial({ text: text22 }) { return { partial: text22 }; }, async parseOutput({ text: text22 }) { return text22; } }); var object6 = ({ schema: inputSchema }) => { const schema = asSchema4(inputSchema); return { type: "object", responseFormat: { type: "json", schema: schema.jsonSchema }, async parsePartial({ text: text22 }) { const result = await parsePartialJson4(text22); switch (result.state) { case "failed-parse": case "undefined-input": return void 0; case "repaired-parse": case "successful-parse": return { // Note: currently no validation of partial results: partial: result.value }; default: { const _exhaustiveCheck = result.state; throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`); } } }, async parseOutput({ text: text22 }, context2) { const parseResult = await safeParseJSON4({ text: text22 }); if (!parseResult.success) { throw new NoObjectGeneratedError4({ message: "No object generated: could not parse the response.", cause: parseResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } const validationResult = await safeValidateTypes4({ value: parseResult.value, schema }); if (!validationResult.success) { throw new NoObjectGeneratedError4({ message: "No object generated: response did not match schema.", cause: validationResult.error, text: text22, response: context2.response, usage: context2.usage, finishReason: context2.finishReason }); } return validationResult.value; } }; }; var TaskSchema = zod.z.array( zod.z.object({ id: zod.z.string().describe("Unique task ID using kebab-case"), content: zod.z.string().describe("Specific, actionable task description"), status: zod.z.enum(["pending", "in_progress", "completed", "blocked"]).default("pending"), priority: zod.z.enum(["high", "medium", "low"]).describe("Task priority"), dependencies: zod.z.array(zod.z.string()).optional().describe("IDs of tasks this depends on"), notes: zod.z.string().describe("Detailed implementation notes and specifics") }) ); var QuestionSchema = zod.z.array( zod.z.object({ id: zod.z.string().describe("Unique question ID"), question: zod.z.string().describe("Clear, specific question for the user"), type: zod.z.enum(["choice", "text", "boolean"]).describe("Type of answer expected"), options: zod.z.array(zod.z.string()).optional().describe("Options for choice questions"), context: zod.z.string().optional().describe("Additional context or explanation") }) ); var PlanningIterationResultSchema = zod.z.object({ success: zod.z.boolean(), tasks: TaskSchema, questions: QuestionSchema, reasoning: zod.z.string(), planComplete: zod.z.boolean(), message: zod.z.string(), error: zod.z.string().optional(), allPreviousQuestions: zod.z.array(zod.z.any()).optional(), allPreviousAnswers: zod.z.record(zod.z.string(), zod.z.string()).optional() }); var taskPlanningPrompts = { planningAgent: { instructions: (context2) => `You are a Mastra workflow planning expert. Your task is to create a detailed, executable task plan. PLANNING RESPONSIBILITIES: 1. **Analyze Requirements**: Review the user's description and requirements thoroughly 2. **Identify Decision Points**: Find any choices that require user input (email providers, databases, APIs, etc.) 3. **Create Specific Tasks**: Generate concrete, actionable tasks with clear implementation notes 4. **Ask Clarifying Questions**: If any decisions are unclear, formulate specific questions for the user - do not ask about package managers - Assume the user is going to use zod for validation - You do not need to ask questions if you have none - NEVER ask questions that have already been answered before 5. **Incorporate Feedback**: Use any previous answers or feedback to refine the plan ${context2.storedQAPairs.length > 0 ? `PREVIOUS QUESTION-ANSWER PAIRS (${context2.storedQAPairs.length} total): ${context2.storedQAPairs.map( (pair, index) => `${index + 1}. Q: ${pair.question.question} A: ${pair.answer || "NOT ANSWERED YET"} Type: ${pair.question.type} Asked: ${pair.askedAt} ${pair.answer ? `Answered: ${pair.answeredAt}` : ""}` ).join("\n\n")} IMPORTANT: DO NOT ASK ANY QUESTIONS THAT HAVE ALREADY BEEN ASKED!` : ""} Based on the context and any user answers, create or refine the task plan.`, refinementPrompt: (context2) => `Refine the existing task plan based on all user answers collected so far. ANSWERED QUESTIONS AND RESPONSES: ${context2.storedQAPairs.filter((pair) => pair.answer).map( (pair, index) => `${index + 1}. Q: ${pair.question.question} A: ${pair.answer} Context: ${pair.question.context || "None"}` ).join("\n\n")} REQUIREMENTS: - Action: ${context2.action} - Workflow Name: ${context2.workflowName || "To be determined"} - Description: ${context2.description || "Not specified"} - Requirements: ${context2.requirements || "Not specified"} PROJECT CONTEXT: - Discovered Workflows: ${JSON.stringify(context2.discoveredWorkflows, null, 2)} - Project Structure: ${JSON.stringify(context2.projectStructure, null, 2)} - Research: ${JSON.stringify(context2.research, null, 2)} ${context2.hasTaskFeedback ? ` USER FEEDBACK ON PREVIOUS TASK LIST: ${context2.userAnswers?.taskFeedback} PLEASE INCORPORATE THIS FEEDBACK INTO THE REFINED TASK LIST.` : ""} Refine the task list and determine if any additional questions are needed.`, initialPrompt: (context2) => `Create an initial task plan for ${context2.action}ing a Mastra workflow. REQUIREMENTS: - Action: ${context2.action} - Workflow Name: ${context2.workflowName || "To be determined"} - Description: ${context2.description || "Not specified"} - Requirements: ${context2.requirements || "Not specified"} PROJECT CONTEXT: - Discovered Workflows: ${JSON.stringify(context2.discoveredWorkflows, null, 2)} - Project Structure: ${JSON.stringify(context2.projectStructure, null, 2)} - Research: ${JSON.stringify(context2.research, null, 2)} Create specific tasks and identify any questions that need user clarification.` }, taskApproval: { message: (questionsCount) => `Please answer ${questionsCount} question(s) to finalize the workflow plan:`, approvalMessage: (tasksCount) => `Please review and approve the ${tasksCount} task(s) for execution:` } }; var WorkflowBuilderInputSchema = zod.z.object({ workflowName: zod.z.string().optional().describe("Name of the workflow to create or edit"), action: zod.z.enum(["create", "edit"]).describe("Action to perform: create new or edit existing workflow"), description: zod.z.string().optional().describe("Description of what the workflow should do"), requirements: zod.z.string().optional().describe("Detailed requirements for the workflow"), projectPath: zod.z.string().optional().describe("Path to the Mastra project (defaults to current directory)") }); var DiscoveredWorkflowSchema = zod.z.object({ name: zod.z.string(), file: zod.z.string(), description: zod.z.string().optional(), inputSchema: zod.z.any().optional(), outputSchema: zod.z.any().optional(), steps: zod.z.array(zod.z.string()).optional() }); var WorkflowDiscoveryResultSchema = zod.z.object({ success: zod.z.boolean(), workflows: zod.z.array(DiscoveredWorkflowSchema), mastraIndexExists: zod.z.boolean(), message: zod.z.string(), error: zod.z.string().optional() }); var ProjectDiscoveryResultSchema = zod.z.object({ success: zod.z.boolean(), structure: zod.z.object({ hasWorkflowsDir: zod.z.boolean(), hasAgentsDir: zod.z.boolean(), hasToolsDir: zod.z.boolean(), hasMastraIndex: zod.z.boolean(), existingWorkflows: zod.z.array(zod.z.string()), existingAgents: zod.z.array(zod.z.string()), existingTools: zod.z.array(zod.z.string()) }), dependencies: zod.z.record(zod.z.string(), zod.z.string()), message: zod.z.string(), error: zod.z.string().optional() }); var WorkflowResearchResultSchema = zod.z.object({ success: zod.z.boolean(), documentation: zod.z.object({ workflowPatterns: zod.z.array(zod.z.string()), stepExamples: zod.z.array(zod.z.string()), bestPractices: zod.z.array(zod.z.string()) }), webResources: zod.z.array( zod.z.object({ title: zod.z.string(), url: zod.z.string(), snippet: zod.z.string(), relevance: zod.z.number() }) ), message: zod.z.string(), error: zod.z.string().optional() }); var TaskManagementResultSchema = zod.z.object({ success: zod.z.boolean(), tasks: TaskSchema, message: zod.z.string(), error: zod.z.string().optional() }); var TaskExecutionInputSchema = zod.z.object({ action: zod.z.enum(["create", "edit"]), workflowName: zod.z.string().optional(), description: zod.z.string().optional(), requirements: zod.z.string().optional(), tasks: TaskSchema, discoveredWorkflows: zod.z.array(zod.z.any()), projectStructure: zod.z.any(), research: zod.z.any(), projectPath: zod.z.string().optional() }); var TaskExecutionSuspendSchema = zod.z.object({ questions: QuestionSchema, currentProgress: zod.z.string(), completedTasks: zod.z.array(zod.z.string()), message: zod.z.string() }); var TaskExecutionResumeSchema = zod.z.object({ answers: zod.z.array( zod.z.object({ questionId: zod.z.string(), answer: zod.z.string() }) ) }); var TaskExecutionResultSchema = zod.z.object({ success: zod.z.boolean(), filesModified: zod.z.array(zod.z.string()), validationResults: zod.z.object({ passed: zod.z.boolean(), errors: zod.z.array(zod.z.string()), warnings: zod.z.array(zod.z.string()) }), completedTasks: zod.z.array(zod.z.string()), message: zod.z.string(), error: zod.z.string().optional() }); zod.z.object({ questions: QuestionSchema }); zod.z.object({ answers: zod.z.record(zod.z.string(), zod.z.string()), hasAnswers: zod.z.boolean() }); var WorkflowBuilderResultSchema = zod.z.object({ success: zod.z.boolean(), action: zod.z.enum(["create", "edit"]), workflowName: zod.z.string().optional(), workflowFile: zod.z.string().optional(), discovery: WorkflowDiscoveryResultSchema.optional(), projectStructure: ProjectDiscoveryResultSchema.optional(), research: WorkflowResearchResultSchema.optional(), planning: PlanningIterationResultSchema.optional(), taskManagement: TaskManagementResultSchema.optional(), execution: TaskExecutionResultSchema.optional(), needsUserInput: zod.z.boolean().optional(), questions: QuestionSchema.optional(), message: zod.z.string(), nextSteps: zod.z.array(zod.z.string()).optional(), error: zod.z.string().optional() }); var TaskExecutionIterationInputSchema = (taskLength) => zod.z.object({ status: zod.z.enum(["in_progress", "completed", "needs_clarification"]).describe('Status - only use "completed" when ALL remaining tasks are finished'), progress: zod.z.string().describe("Current progress description"), completedTasks: zod.z.array(zod.z.string()).describe("List of ALL completed task IDs (including previously completed ones)"), totalTasksRequired: zod.z.number().describe(`Total number of tasks that must be completed (should be ${taskLength})`), tasksRemaining: zod.z.array(zod.z.string()).describe("List of task IDs that still need to be completed"), filesModified: zod.z.array(zod.z.string()).describe("List of files that were created or modified - use these exact paths for validateCode tool"), questions: QuestionSchema.optional().describe("Questions for user if clarification is needed"), message: zod.z.string().describe("Summary of work completed or current status"), error: zod.z.string().optional().describe("Any errors encountered") }); var PlanningIterationInputSchema = zod.z.object({ action: zod.z.enum(["create", "edit"]), workflowName: zod.z.string().optional(), description: zod.z.string().optional(), requirements: zod.z.string().optional(), discoveredWorkflows: zod.z.array(DiscoveredWorkflowSchema), projectStructure: ProjectDiscoveryResultSchema, research: WorkflowResearchResultSchema, userAnswers: zod.z.record(zod.z.string(), zod.z.string()).optional() }); var PlanningIterationSuspendSchema = zod.z.object({ questions: QuestionSchema, message: zod.z.string(), currentPlan: zod.z.object({ tasks: TaskSchema, reasoning: zod.z.string() }) }); var PlanningIterationResumeSchema = zod.z.object({ answers: zod.z.record(zod.z.string(), zod.z.string()) }); var PlanningAgentOutputSchema = zod.z.object({ tasks: TaskSchema, questions: QuestionSchema.optional(), reasoning: zod.z.string().describe("Explanation of the plan and any questions"), planComplete: zod.z.boolean().describe("Whether the plan is ready for execution (no more questions)") }); var TaskApprovalOutputSchema = zod.z.object({ approved: zod.z.boolean(), tasks: TaskSchema, message: zod.z.string(), userFeedback: zod.z.string().optional() }); var TaskApprovalSuspendSchema = zod.z.object({ taskList: TaskSchema, summary: zod.z.string(), message: zod.z.string() }); var TaskApprovalResumeSchema = zod.z.object({ approved: zod.z.boolean(), modifications: zod.z.string().optional() }); var planningIterationStep = workflows.createStep({ id: "planning-iteration", description: "Create or refine task plan with user input", inputSchema: PlanningIterationInputSchema, outputSchema: PlanningIterationResultSchema, suspendSchema: PlanningIterationSuspendSchema, resumeSchema: PlanningIterationResumeSchema, execute: async ({ inputData, resumeData, suspend, requestContext }) => { const { action, workflowName, description, requirements, discoveredWorkflows, projectStructure, research, userAnswers } = inputData; console.info("Starting planning iteration..."); const qaKey = "workflow-builder-qa"; let storedQAPairs = requestContext.get(qaKey) || []; const newAnswers = { ...userAnswers || {}, ...resumeData?.answers || {} }; if (Object.keys(newAnswers).length > 0) { storedQAPairs = storedQAPairs.map((pair) => { const answerValue = newAnswers[pair.question.id]; if (answerValue) { return { ...pair, answer: String(answerValue) || null, answeredAt: (/* @__PURE__ */ new Date()).toISOString() }; } return pair; }); requestContext.set(qaKey, storedQAPairs); } try { const model = await resolveModel({ requestContext }); const planningAgent = new agent.Agent({ id: "workflow-planning-agent", model, instructions: taskPlanningPrompts.planningAgent.instructions({ storedQAPairs }), name: "Workflow Planning Agent" // tools: filteredMcpTools, }); const hasTaskFeedback = Boolean(userAnswers && userAnswers.taskFeedback); const planningPrompt = storedQAPairs.some((pair) => pair.answer) ? taskPlanningPrompts.planningAgent.refinementPrompt({ action, workflowName, description, requirements, discoveredWorkflows, projectStructure, research, storedQAPairs, hasTaskFeedback, userAnswers }) : taskPlanningPrompts.planningAgent.initialPrompt({ action, workflowName, description, requirements, discoveredWorkflows, projectStructure, research }); const result = await planningAgent.generate(planningPrompt, { structuredOutput: { schema: PlanningAgentOutputSchema } // maxSteps: 15, }); const planResult = await result.object; if (!planResult) { return { tasks: [], success: false, questions: [], reasoning: "Planning agent failed to generate a valid response", planComplete: false, message: "Planning failed" }; } if (planResult.questions && planResult.questions.length > 0 && !planResult.planComplete) { console.info(`Planning needs user clarification: ${planResult.questions.length} questions`); console.info(planResult.questions); const newQAPairs = planResult.questions.map((question) => ({ question, answer: null, askedAt: (/* @__PURE__ */ new Date()).toISOString(), answeredAt: null })); storedQAPairs = [...storedQAPairs, ...newQAPairs]; requestContext.set(qaKey, storedQAPairs); console.info( `Updated Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter((p) => p.answer).length} answered` ); return suspend({ questions: planResult.questions, message: taskPlanningPrompts.taskApproval.message(planResult.questions.length), currentPlan: { tasks: planResult.tasks, reasoning: planResult.reasoning } }); } console.info(`Planning complete with ${planResult.tasks.length} tasks`); requestContext.set(qaKey, storedQAPairs); console.info( `Final Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter((p) => p.answer).length} answered` ); return { tasks: planResult.tasks, success: true, questions: [], reasoning: planResult.reasoning, planComplete: true, message: `Successfully created ${planResult.tasks.length} tasks`, allPreviousQuestions: storedQAPairs.map((pair) => pair.question), allPreviousAnswers: Object.fromEntries( storedQAPairs.filter((pair) => pair.answer).map((pair) => [pair.question.id, pair.answer]) ) }; } catch (error90) { console.error("Planning iteration failed:", error90); return { tasks: [], success: false, questions: [], reasoning: `Planning failed: ${error90 instanceof Error ? error90.message : String(error90)}`, planComplete: false, message: "Planning iteration failed", error: error90 instanceof Error ? error90.message : String(error90), allPreviousQuestions: storedQAPairs.map((pair) => pair.question), allPreviousAnswers: Object.fromEntries( storedQAPairs.filter((pair) => pair.answer).map((pair) => [pair.question.id, pair.answer]) ) }; } } }); var taskApprovalStep = workflows.createStep({ id: "task-approval", description: "Get user approval for the final task list", inputSchema: PlanningIterationResultSchema, outputSchema: TaskApprovalOutputSchema, suspendSchema: TaskApprovalSuspendSchema, resumeSchema: TaskApprovalResumeSchema, execute: async ({ inputData, resumeData, suspend }) => { const { tasks } = inputData; if (!resumeData?.approved && resumeData?.approved !== false) { console.info(`Requesting user approval for ${tasks.length} tasks`); const summary = `Task List for Approval: ${tasks.length} tasks planned: ${tasks.map((task, i) => `${i + 1}. [${task.priority.toUpperCase()}] ${task.content}${task.dependencies?.length ? ` (depends on: ${task.dependencies.join(", ")})` : ""} Notes: ${task.notes || "None"}`).join("\n")}`; return suspend({ taskList: tasks, summary, message: taskPlanningPrompts.taskApproval.approvalMessage(tasks.length) }); } if (resumeData.approved) { console.info("Task list approved by user"); return { approved: true, tasks, message: "Task list approved, ready for execution" }; } else { console.info("Task list rejected by user"); return { approved: false, tasks, message: "Task list rejected", userFeedback: resumeData.modifications }; } } }); var planningAndApprovalWorkflow = workflows.createWorkflow({ id: "planning-and-approval", description: "Handle iterative planning with questions and task list approval", inputSchema: PlanningIterationInputSchema, outputSchema: TaskApprovalOutputSchema, steps: [planningIterationStep, taskApprovalStep] }).dountil(planningIterationStep, async ({ inputData }) => { console.info(`Sub-workflow planning check: planComplete=${inputData.planComplete}`); return inputData.planComplete === true; }).map(async ({ inputData }) => { return { tasks: inputData.tasks || [], success: inputData.success || false, questions: inputData.questions || [], reasoning: inputData.reasoning || "", planComplete: inputData.planComplete || false, message: inputData.message || "" }; }).then(taskApprovalStep).commit(); var workflowResearch = ` ## \u{1F50D} **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY** Based on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows: ### **\u{1F4CB} WORKFLOW FUNDAMENTALS** **Core Components:** - **\`createWorkflow()\`**: Main factory function that creates workflow instances - **\`createStep()\`**: Creates individual workflow steps with typed inputs/outputs - **\`.commit()\`**: Finalizes workflow definition (REQUIRED to make workflows executable) - **Zod schemas**: Used for strict input/output typing and validation **Basic Structure:** \`\`\`typescript import { createWorkflow, createStep } from "@mastra/core/workflows"; import { z } from "zod"; const workflow = createWorkflow({ id: "unique-workflow-id", // Required: kebab-case recommended description: "What this workflow does", // Optional but recommended inputSchema: z.object({...}), // Required: Defines workflow inputs outputSchema: z.object({...}) // Required: Defines final outputs }) .then(step1) // Chain steps sequentially .then(step2) .commit(); // CRITICAL: Makes workflow executable \`\`\` ### **\u{1F527} STEP CREATION PATTERNS** **Standard Step Definition:** \`\`\`typescript const myStep = createStep({ id: "step-id", // Required: unique identifier description: "Step description", // Recommended for clarity inputSchema: z.object({...}), // Required: input validation outputSchema: z.object({...}), // Required: output validation execute: async ({ inputData, mastra, getStepResult, getInitData }) => { // Step logic here return { /* matches outputSchema */ }; } }); \`\`\` **Execute Function Parameters:** - \`inputData\`: Validated input matching inputSchema - \`mastra\`: Access to Mastra instance (agents, tools, other workflows) - \`getStepResult(stepInstance)\`: Get results from previous steps - \`getInitData()\`: Access original workflow input data - \`requestContext\`: Runtime dependency injection context - \`runCount\`: Number of times this step has run (useful for retries) ### **\u{1F504} CONTROL FLOW METHODS** **Sequential Execution:** - \`.then(step)\`: Execute steps one after another - Data flows automatically if schemas match **Parallel Execution:** - \`.parallel([step1, step2])\`: Run steps simultaneously - All parallel steps complete before continuing **Conditional Logic:** - \`.branch([[condition, step], [condition, step]])\`: Execute different steps based on conditions - Conditions evaluated sequentially, matching steps run in parallel **Loops:** - \`.dountil(step, condition)\`: Repeat until condition becomes true - \`.dowhile(step, condition)\`: Repeat while condition is true - \`.foreach(step, {concurrency: N})\`: Execute step for each array item **Data Transformation:** - \`.map(({ inputData, getStepResult, getInitData }) => transformedData)\`: Transform data between steps ### **\u23F8\uFE0F SUSPEND & RESUME CAPABILITIES** **For Human-in-the-Loop Workflows:** \`\`\`typescript const userInputStep = createStep({ id: "user-input", suspendSchema: z.object({}), // Schema for suspension payload resumeSchema: z.object({ // Schema for resume data userResponse: z.string() }), execute: async ({ resumeData, suspend }) => { if (!resumeData?.userResponse) { await suspend({}); // Pause workflow return { response: "" }; } return { response: resumeData.userResponse }; } }); \`\`\` **Resume Workflow:** \`\`\`typescript const result = await run.start({ inputData: {...} }); if (result.status === "suspended") { await run.resume({ step: result.suspended[0], // Or specific step ID resumeData: { userResponse: "answer" } }); } \`\`\` ### **\u{1F6E0}\uFE0F INTEGRATING AGENTS & TOOLS** **Using Agents in Steps:** \`\`\`typescript // Method 1: Agent as step const agentStep = createStep(myAgent); // Method 2: Call agent in execute function const step = createStep({ execute: async ({ inputData }) => { const result = await myAgent.generate(prompt); return { output: result.text }; } }); \`\`\` **Using Tools in Steps:** \`\`\`typescript // Method 1: Tool as step const toolStep = createStep(myTool); // Method 2: Call tool in execute function const step = createStep({ execute: async ({ inputData, requestContext }) => { const result = await myTool.execute({ context: inputData, requestContext }); return result; } }); \`\`\` ### **\u{1F5C2}\uFE0F PROJECT ORGANIZATION PATTERNS** **MANDATORY Workflow Organization:** Each workflow MUST be organized in its own dedicated folder with separated concerns: \`\`\` src/mastra/workflows/ \u251C\u2500\u2500 my-workflow-name/ # Kebab-case folder name \u2502 \u251C\u2500\u2500 types.ts # All Zod schemas and TypeScript types \u2502 \u251C\u2500\u2500 steps.ts # All individual step definitions \u2502 \u251C\u2500\u2500 workflow.ts # Main workflow composition and export \u2502 \u2514\u2500\u2500 utils.ts # Helper functions (if needed) \u251C\u2500\u2500 another-workflow/ \u2502 \u251C\u2500\u2500 types.ts \u2502 \u251C\u2500\u2500 steps.ts \u2502 \u251C\u2500\u2500 workflow.ts \u2502 \u2514\u2500\u2500 utils.ts \u2514\u2500\u2500 index.ts # Export all workflows \`\`\` **CRITICAL File Organization Rules:** - **ALWAYS create a dedicated folder** for each workflow - **Folder names MUST be kebab-case** version of workflow name - **types.ts**: Define all input/output schemas, validation types, and interfaces - **steps.ts**: Create all individual step definitions using createStep() - **workflow.ts**: Compose steps into workflow using createWorkflow() and export the final workflow - **utils.ts**: Any helper functions, constants, or utilities (create only if needed) - **NEVER put everything in one file** - always separate concerns properly **Workflow Registration:** \`\`\`typescript // src/mastra/index.ts export const mastra = new Mastra({ workflows: { sendEmailWorkflow, // Use camelCase for keys dataProcessingWorkflow }, storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }), // Required for suspend/resume }); \`\`\` ### **\u{1F4E6} ESSENTIAL DEPENDENCIES** **Required Packages:** \`\`\`json { "dependencies": { "@mastra/core": "latest", "zod": "^3.25.67" } } \`\`\` **Additional Packages (as needed):** - \`@mastra/libsql\`: For workflow state persistence - \`@ai-sdk/openai\`: For AI model integration - \`ai\`: For AI SDK functionality ### **\u2705 WORKFLOW BEST PRACTICES** **Schema Design:** - Use descriptive property names in schemas - Make schemas as specific as possible (avoid \`z.any()\`) - Include validation for required business logic **Error Handling:** - Use \`try/catch\` blocks in step execute functions - Return meaningful error messages - Consider using \`bail()\` for early successful exits **Step Organization:** - Keep steps focused on single responsibilities - Use descriptive step IDs (kebab-case recommended) - Create reusable steps for common operations **Data Flow:** - Use \`.map()\` when schemas don't align between steps - Access previous step results with \`getStepResult(stepInstance)\` - Use \`getInitData()\` to access original workflow input ### **\u{1F680} EXECUTION PATTERNS** **Running Workflows:** \`\`\`typescript // Create and start run const run = await workflow.createRun(); const result = await run.start({ inputData: {...} }); // Stream execution for real-time monitoring const stream = await run.streamVNext({ inputData: {...} }); for await (const chunk of stream) { console.log(chunk); } // Watch for events run.watch((event) => console.log(event)); \`\`\` **Workflow Status Types:** - \`"success"\`: Completed successfully - \`"suspended"\`: Paused awaiting input - \`"failed"\`: Encountered error ### **\u{1F517} ADVANCED FEATURES** **Nested Workflows:** - Use workflows as steps: \`.then(otherWorkflow)\` - Enable complex workflow composition **Request Context:** - Pass shared data across all steps - Enable dependency injection patterns **Streaming & Events:** - Real-time workflow monitoring - Integration with external event systems **Cloning:** - \`cloneWorkflow(original, {id: "new-id"})\`: Reuse workflow structure - \`cloneStep(original, {id: "new-id"})\`: Reuse step logic This comprehensive research provides the foundation for creating robust, maintainable Mastra workflows with proper typing, error handling, and architectural patterns. `; var workflowBuilderPrompts = { researchAgent: { instructions: `You are a Mastra workflow research expert. Your task is to gather relevant information about creating Mastra workflows. RESEARCH OBJECTIVES: 1. **Core Concepts**: Understand how Mastra workflows work 2. **Best Practices**: Learn workflow patterns and conventions 3. **Code Examples**: Find relevant implementation examples 4. **Technical Details**: Understand schemas, steps, and configuration Use the available documentation and examples tools to gather comprehensive information about Mastra workflows.`, prompt: (context2) => `Research everything about Mastra workflows to help create or edit them effectively. PROJECT CONTEXT: - Project Structure: ${JSON.stringify(context2.projectStructure, null, 2)} - Dependencies: ${JSON.stringify(context2.dependencies, null, 2)} - Has Workflows Directory: ${context2.hasWorkflowsDir} Focus on: 1. How to create workflows using createWorkflow() 2. How to create and chain workflow steps 3. Best practices for workflow organization 4. Common workflow patterns and examples 5. Schema definitions and types 6. Error handling and debugging Use the docs and examples tools to gather comprehensive information.` }, executionAgent: { instructions: (context2) => `You are executing a workflow ${context2.action} task for: "${context2.workflowName}" CRITICAL WORKFLOW EXECUTION REQUIREMENTS: 1. **EXPLORE PROJECT STRUCTURE FIRST**: Use listDirectory and readFile tools to understand the existing project layout, folder structure, and conventions before creating any files 2. **FOLLOW PROJECT CONVENTIONS**: Look at existing workflows, agents, and file structures to understand where new files should be placed (typically src/mastra/workflows/, src/mastra/agents/, etc.) 3. **USE PRE-LOADED TASK LIST**: Your task list has been pre-populated in the taskManager tool. Use taskManager with action 'list' to see all tasks, and action 'update' to mark progress 4. **COMPLETE EVERY SINGLE TASK**: You MUST complete ALL ${context2.tasksLength} tasks that are already in the taskManager. Do not stop until every task is marked as 'completed' 5. **Follow Task Dependencies**: Execute tasks in the correct order, respecting dependencies 6. **Request User Input When Needed**: If you encounter choices (like email providers, databases, etc.) that require user decision, return questions for clarification 7. **STRICT WORKFLOW ORGANIZATION**: When creating or editing workflows, you MUST follow this exact structure MANDATORY WORKFLOW FOLDER STRUCTURE: When ${context2.action === "create" ? "creating a new workflow" : "editing a workflow"}, you MUST organize files as follows: \u{1F4C1} src/mastra/workflows/${context2.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, "-") || "new-workflow"}/ \u251C\u2500\u2500 \u{1F4C4} types.ts # All Zod schemas and TypeScript types \u251C\u2500\u2500 \u{1F4C4} steps.ts # All individual step definitions \u251C\u2500\u2500 \u{1F4C4} workflow.ts # Main workflow composition and export \u2514\u2500\u2500 \u{1F4C4} utils.ts # Helper functions (if needed) CRITICAL FILE ORGANIZATION RULES: - **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/ - **Folder name MUST be kebab-case** version of workflow name - **types.ts**: Define all input/output schemas, validation types, and interfaces - **steps.ts**: Create all individual step definitions using createStep() - **workflow.ts**: Compose steps into workflow using createWorkflow() and export the final workflow - **utils.ts**: Any helper functions, constants, or utilities (create only if needed) - **NEVER put everything in one file** - always separate concerns properly CRITICAL COMPLETION REQUIREMENTS: - ALWAYS explore the directory structure before creating files to understand where they should go - You MUST complete ALL ${context2.tasksLength} tasks before returning status='completed' - Use taskManager tool with action 'list' to see your current task list and action 'update' to mark tasks as 'in_progress' or 'completed' - If you need to make any decisions during implementation (choosing providers, configurations, etc.), return questions for user clarification - DO NOT make assumptions about file locations - explore first! - You cannot finish until ALL tasks in the taskManager are marked as 'completed' PROJECT CONTEXT: - Action: ${context2.action} - Workflow Name: ${context2.workflowName} - Project Path: ${context2.currentProjectPath} - Discovered Workflows: ${JSON.stringify(context2.discoveredWorkflows, null, 2)} - Project Structure: ${JSON.stringify(context2.projectStructure, null, 2)} AVAILABLE RESEARCH: ${JSON.stringify(context2.research, null, 2)} PRE-LOADED TASK LIST (${context2.tasksLength} tasks already in taskManager): ${context2.tasks.map((task) => `- ${task.id}: ${task.content} (Priority: ${task.priority})`).join("\n")} ${context2.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context2.resumeData.answers, null, 2)}` : ""} Start by exploring the project structure, then use 'taskManager' with action 'list' to see your pre-loaded tasks, and work through each task systematically.`, prompt: (context2) => context2.resumeData ? `Continue working on the task list. The user has provided answers to your questions: ${JSON.stringify(context2.resumeData.answers, null, 2)}. CRITICAL: You must complete ALL ${context2.tasks.length} tasks that are pre-loaded in the taskManager. Use the taskManager tool with action 'list' to check your progress and continue with the next tasks. Do not stop until every single task is marked as 'completed'.` : `Begin executing the pre-loaded task list to ${context2.action} the workflow "${context2.workflowName}". CRITICAL REQUIREMENTS: - Your ${context2.tasks.length} tasks have been PRE-LOADED into the taskManager tool - Start by exploring the project directory structure using listDirectory and readFile tools to understand: - Where workflows are typically stored (look for src/mastra/workflows/ or similar) - What the existing file structure looks like - How other workflows are organized and named - Where agent files are stored if needed - Then use taskManager with action 'list' to see your pre-loaded tasks - Use taskManager with action 'update' to mark tasks as 'in_progress' or 'completed' CRITICAL FILE ORGANIZATION RULES: - **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/ - **Folder name MUST be kebab-case** version of workflow name - **NEVER put everything in one file** - separate types, steps, and workflow composition - Follow the 4-file structure above for maximum maintainability and clarity - DO NOT return status='completed' until ALL ${context2.tasks.length} tasks are marked as 'completed' in the taskManager PRE-LOADED TASKS (${context2.tasks.length} total tasks in taskManager): ${context2.tasks.map((task, index) => `${index + 1}. [${task.id}] ${task.content}`).join("\n")} Use taskManager with action 'list' to see the current status of all tasks. You must complete every single one before finishing.`, iterationPrompt: (context2) => `Continue working on the remaining tasks. You have already completed these tasks: [${context2.completedTasks.map((t) => t.id).join(", ")}] REMAINING TASKS TO COMPLETE (${context2.pendingTasks.length} tasks): ${context2.pendingTasks.map((task, index) => `${index + 1}. [${task.id}] ${task.content}`).join("\n")} CRITICAL: You must complete ALL of these remaining ${context2.pendingTasks.length} tasks. Use taskManager with action 'list' to check current status and action 'update' to mark tasks as completed. ${context2.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context2.resumeData.answers, null, 2)}` : ""}` }, validation: { instructions: `CRITICAL VALIDATION INSTRUCTIONS: - When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter - The tool uses a hybrid validation approach: fast syntax checking \u2192 semantic type checking \u2192 ESLint - This is much faster than full project compilation and only shows errors from your specific files - Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] }) - ALWAYS validate after creating or modifying files to ensure they compile correctly` } }; var restrictedTaskManager = tools.createTool({ id: "task-manager", description: "View and update your pre-loaded task list. You can only mark tasks as in_progress or completed, not create new tasks.", inputSchema: zod.z.object({ action: zod.z.enum(["list", "update", "complete"]).describe("List tasks, update status, or mark complete - tasks are pre-loaded"), tasks: zod.z.array( zod.z.object({ id: zod.z.string().describe("Task ID - must match existing task"), content: zod.z.string().optional().describe("Task content (read-only)"), status: zod.z.enum(["pending", "in_progress", "completed", "blocked"]).describe("Task status"), priority: zod.z.enum(["high", "medium", "low"]).optional().describe("Task priority (read-only)"), dependencies: zod.z.array(zod.z.string()).optional().describe("Task dependencies (read-only)"), notes: zod.z.string().optional().describe("Additional notes or progress updates") }) ).optional().describe("Tasks to update (status and notes only)"), taskId: zod.z.string().optional().describe("Specific task ID for single task operations") }), outputSchema: zod.z.object({ success: zod.z.boolean(), tasks: zod.z.array( zod.z.object({ id: zod.z.string(), content: zod.z.string(), status: zod.z.string(), priority: zod.z.string(), dependencies: zod.z.array(zod.z.string()).optional(), notes: zod.z.string().optional(), createdAt: zod.z.string(), updatedAt: zod.z.string() }) ), message: zod.z.string() }), execute: async (input) => { const adaptedContext = { ...input, action: input.action, tasks: input.tasks?.map((task) => ({ ...task, priority: task.priority || "medium" })) }; return await AgentBuilderDefaults.manageTaskList(adaptedContext); } }); var workflowDiscoveryStep = workflows.createStep({ id: "workflow-discovery", description: "Discover existing workflows in the project", inputSchema: WorkflowBuilderInputSchema, outputSchema: WorkflowDiscoveryResultSchema, execute: async ({ inputData, requestContext: _requestContext }) => { console.info("Starting workflow discovery..."); const { projectPath = process.cwd() } = inputData; try { const workflowsPath = path.join(projectPath, "src/mastra/workflows"); if (!fs.existsSync(workflowsPath)) { console.info("No workflows directory found"); return { success: true, workflows: [], mastraIndexExists: fs.existsSync(path.join(projectPath, "src/mastra/index.ts")), message: "No existing workflows found in the project" }; } const workflowFiles = await promises.readdir(workflowsPath); const workflows = []; for (const fileName of workflowFiles) { if (fileName.endsWith(".ts") && !fileName.endsWith(".test.ts")) { const filePath = path.join(workflowsPath, fileName); try { const content = await promises.readFile(filePath, "utf-8"); const nameMatch = content.match(/createWorkflow\s*\(\s*{\s*id:\s*['"]([^'"]+)['"]/); const descMatch = content.match(/description:\s*['"]([^'"]*)['"]/); if (nameMatch && nameMatch[1]) { workflows.push({ name: nameMatch[1], file: filePath, description: descMatch?.[1] ?? "No description available" }); } } catch (error90) { console.warn(`Failed to read workflow file ${filePath}:`, error90); } } } console.info(`Discovered ${workflows.length} existing workflows`); return { success: true, workflows, mastraIndexExists: fs.existsSync(path.join(projectPath, "src/mastra/index.ts")), message: workflows.length > 0 ? `Found ${workflows.length} existing workflow(s): ${workflows.map((w) => w.name).join(", ")}` : "No existing workflows found in the project" }; } catch (error90) { console.error("Workflow discovery failed:", error90); return { success: false, workflows: [], mastraIndexExists: false, message: `Workflow discovery failed: ${error90 instanceof Error ? error90.message : String(error90)}`, error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var projectDiscoveryStep = workflows.createStep({ id: "project-discovery", description: "Analyze the project structure and setup", inputSchema: WorkflowDiscoveryResultSchema, outputSchema: ProjectDiscoveryResultSchema, execute: async ({ inputData: _inputData, requestContext: _requestContext }) => { console.info("Starting project discovery..."); try { const projectPath = process.cwd(); const projectStructure = { hasPackageJson: fs.existsSync(path.join(projectPath, "package.json")), hasMastraConfig: fs.existsSync(path.join(projectPath, "mastra.config.js")) || fs.existsSync(path.join(projectPath, "mastra.config.ts")), hasSrcDirectory: fs.existsSync(path.join(projectPath, "src")), hasMastraDirectory: fs.existsSync(path.join(projectPath, "src/mastra")), hasWorkflowsDirectory: fs.existsSync(path.join(projectPath, "src/mastra/workflows")), hasToolsDirectory: fs.existsSync(path.join(projectPath, "src/mastra/tools")), hasAgentsDirectory: fs.existsSync(path.join(projectPath, "src/mastra/agents")) }; let packageInfo = null; if (projectStructure.hasPackageJson) { try { const packageContent = await promises.readFile(path.join(projectPath, "package.json"), "utf-8"); packageInfo = JSON.parse(packageContent); } catch (error90) { console.warn("Failed to read package.json:", error90); } } console.info("Project discovery completed"); return { success: true, structure: { hasWorkflowsDir: projectStructure.hasWorkflowsDirectory, hasAgentsDir: projectStructure.hasAgentsDirectory, hasToolsDir: projectStructure.hasToolsDirectory, hasMastraIndex: fs.existsSync(path.join(projectPath, "src/mastra/index.ts")), existingWorkflows: [], existingAgents: [], existingTools: [] }, dependencies: packageInfo?.dependencies || {}, message: "Project discovery completed successfully" }; } catch (error90) { console.error("Project discovery failed:", error90); return { success: false, structure: { hasWorkflowsDir: false, hasAgentsDir: false, hasToolsDir: false, hasMastraIndex: false, existingWorkflows: [], existingAgents: [], existingTools: [] }, dependencies: {}, message: "Project discovery failed", error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var workflowResearchStep = workflows.createStep({ id: "workflow-research", description: "Research Mastra workflows and gather relevant documentation", inputSchema: ProjectDiscoveryResultSchema, outputSchema: WorkflowResearchResultSchema, execute: async ({ inputData, requestContext }) => { console.info("Starting workflow research..."); try { const model = await resolveModel({ requestContext }); const researchAgent = new agent.Agent({ id: "workflow-research-agent", model, instructions: workflowBuilderPrompts.researchAgent.instructions, name: "Workflow Research Agent" // tools: filteredMcpTools, }); const researchPrompt = workflowBuilderPrompts.researchAgent.prompt({ projectStructure: inputData.structure, dependencies: inputData.dependencies, hasWorkflowsDir: inputData.structure.hasWorkflowsDir }); const result = await researchAgent.generate(researchPrompt, { structuredOutput: { schema: WorkflowResearchResultSchema } // stopWhen: stepCountIs(10), }); const researchResult = await result.object; if (!researchResult) { return { success: false, documentation: { workflowPatterns: [], stepExamples: [], bestPractices: [] }, webResources: [], message: "Research agent failed to generate valid response", error: "Research agent failed to generate valid response" }; } console.info("Research completed successfully"); return { success: true, documentation: { workflowPatterns: researchResult.documentation.workflowPatterns, stepExamples: researchResult.documentation.stepExamples, bestPractices: researchResult.documentation.bestPractices }, webResources: researchResult.webResources, message: "Research completed successfully" }; } catch (error90) { console.error("Workflow research failed:", error90); return { success: false, documentation: { workflowPatterns: [], stepExamples: [], bestPractices: [] }, webResources: [], message: "Research failed", error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var taskExecutionStep = workflows.createStep({ id: "task-execution", description: "Execute the approved task list to create or edit the workflow", inputSchema: TaskExecutionInputSchema, outputSchema: TaskExecutionResultSchema, suspendSchema: TaskExecutionSuspendSchema, resumeSchema: TaskExecutionResumeSchema, execute: async ({ inputData, resumeData, suspend, requestContext }) => { const { action, workflowName, tasks, discoveredWorkflows, projectStructure, research, projectPath } = inputData; console.info(`Starting task execution for ${action}ing workflow: ${workflowName}`); console.info(`Executing ${tasks.length} tasks using AgentBuilder stream...`); try { const model = await resolveModel({ requestContext }); const currentProjectPath = projectPath || process.cwd(); console.info("Pre-populating taskManager with planned tasks..."); const taskManagerContext = { action: "create", tasks: tasks.map((task) => ({ id: task.id, content: task.content, status: "pending", priority: task.priority, dependencies: task.dependencies, notes: task.notes })) }; const taskManagerResult = await AgentBuilderDefaults.manageTaskList(taskManagerContext); console.info(`Task manager initialized with ${taskManagerResult.tasks.length} tasks`); if (!taskManagerResult.success) { throw new Error(`Failed to initialize task manager: ${taskManagerResult.message}`); } const executionAgent = new AgentBuilder({ projectPath: currentProjectPath, model, tools: { "task-manager": restrictedTaskManager }, instructions: `${workflowBuilderPrompts.executionAgent.instructions({ action, workflowName, tasksLength: tasks.length, currentProjectPath, discoveredWorkflows, projectStructure, research, tasks, resumeData })} ${workflowBuilderPrompts.validation.instructions}` }); const executionPrompt = workflowBuilderPrompts.executionAgent.prompt({ action, workflowName, tasks, resumeData }); const originalInstructions = await executionAgent.getInstructions({ requestContext }); const enhancedOptions = { stopWhen: stepCountIs(100), temperature: 0.3, instructions: originalInstructions }; let finalResult = null; let allTasksCompleted = false; let iterationCount = 0; const maxIterations = 5; const expectedTaskIds = tasks.map((task) => task.id); while (!allTasksCompleted && iterationCount < maxIterations) { iterationCount++; const currentTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: "list" }); const completedTasks = currentTaskStatus.tasks.filter((task) => task.status === "completed"); const pendingTasks = currentTaskStatus.tasks.filter((task) => task.status !== "completed"); console.info(` === EXECUTION ITERATION ${iterationCount} ===`); console.info(`Completed tasks: ${completedTasks.length}/${expectedTaskIds.length}`); console.info(`Remaining tasks: ${pendingTasks.map((t) => t.id).join(", ")}`); allTasksCompleted = pendingTasks.length === 0; if (allTasksCompleted) { console.info("All tasks completed! Breaking execution loop."); break; } const iterationPrompt = iterationCount === 1 ? executionPrompt : `${workflowBuilderPrompts.executionAgent.iterationPrompt({ completedTasks, pendingTasks, workflowName, resumeData })} ${workflowBuilderPrompts.validation.instructions}`; const stream = await executionAgent.stream(iterationPrompt, { structuredOutput: { schema: TaskExecutionIterationInputSchema(tasks.length), model }, ...enhancedOptions }); let finalMessage = ""; for await (const chunk of stream.fullStream) { if (chunk.type === "text-delta") { finalMessage += chunk.payload.text; } if (chunk.type === "step-finish") { console.info(finalMessage); finalMessage = ""; } if (chunk.type === "tool-result") { console.info(JSON.stringify(chunk, null, 2)); } if (chunk.type === "finish") { console.info(chunk); } } await stream.consumeStream(); finalResult = await stream.object; console.info(`Iteration ${iterationCount} result:`, { finalResult }); if (!finalResult) { throw new Error(`No result received from agent execution on iteration ${iterationCount}`); } const postIterationTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: "list" }); const postCompletedTasks = postIterationTaskStatus.tasks.filter((task) => task.status === "completed"); const postPendingTasks = postIterationTaskStatus.tasks.filter((task) => task.status !== "completed"); allTasksCompleted = postPendingTasks.length === 0; console.info( `After iteration ${iterationCount}: ${postCompletedTasks.length}/${expectedTaskIds.length} tasks completed in taskManager` ); if (finalResult.status === "needs_clarification" && finalResult.questions && finalResult.questions.length > 0) { console.info( `Agent needs clarification on iteration ${iterationCount}: ${finalResult.questions.length} questions` ); break; } if (finalResult.status === "completed" && !allTasksCompleted) { console.info( `Agent claimed completion but taskManager shows pending tasks: ${postPendingTasks.map((t) => t.id).join(", ")}` ); } } if (iterationCount >= maxIterations && !allTasksCompleted) { finalResult.error = `Maximum iterations (${maxIterations}) reached but not all tasks completed`; finalResult.status = "in_progress"; } if (!finalResult) { throw new Error("No result received from agent execution"); } if (finalResult.status === "needs_clarification" && finalResult.questions && finalResult.questions.length > 0) { console.info(`Agent needs clarification: ${finalResult.questions.length} questions`); console.info("finalResult", JSON.stringify(finalResult, null, 2)); return suspend({ questions: finalResult.questions, currentProgress: finalResult.progress, completedTasks: finalResult.completedTasks || [], message: finalResult.message }); } const finalTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: "list" }); const finalCompletedTasks = finalTaskStatus.tasks.filter((task) => task.status === "completed"); const finalPendingTasks = finalTaskStatus.tasks.filter((task) => task.status !== "completed"); const tasksCompleted = finalCompletedTasks.length; const tasksExpected = expectedTaskIds.length; const finalAllTasksCompleted = finalPendingTasks.length === 0; const success3 = finalAllTasksCompleted && !finalResult.error; const message = success3 ? `Successfully completed workflow ${action} - all ${tasksExpected} tasks completed after ${iterationCount} iteration(s): ${finalResult.message}` : `Workflow execution finished with issues after ${iterationCount} iteration(s): ${finalResult.message}. Completed: ${tasksCompleted}/${tasksExpected} tasks`; console.info(message); const missingTasks = finalPendingTasks.map((task) => task.id); const validationErrors = []; if (finalResult.error) { validationErrors.push(finalResult.error); } if (!finalAllTasksCompleted) { validationErrors.push( `Incomplete tasks: ${missingTasks.join(", ")} (${tasksCompleted}/${tasksExpected} completed)` ); } return { success: success3, completedTasks: finalCompletedTasks.map((task) => task.id), filesModified: finalResult.filesModified || [], validationResults: { passed: success3, errors: validationErrors, warnings: finalAllTasksCompleted ? [] : [`Missing ${missingTasks.length} tasks: ${missingTasks.join(", ")}`] }, message, error: finalResult.error }; } catch (error90) { console.error("Task execution failed:", error90); return { success: false, completedTasks: [], filesModified: [], validationResults: { passed: false, errors: [`Task execution failed: ${error90 instanceof Error ? error90.message : String(error90)}`], warnings: [] }, message: `Task execution failed: ${error90 instanceof Error ? error90.message : String(error90)}`, error: error90 instanceof Error ? error90.message : String(error90) }; } } }); var workflowBuilderWorkflow = workflows.createWorkflow({ id: "workflow-builder", description: "Create or edit Mastra workflows using AI-powered assistance with iterative planning", inputSchema: WorkflowBuilderInputSchema, outputSchema: WorkflowBuilderResultSchema, steps: [ workflowDiscoveryStep, projectDiscoveryStep, workflowResearchStep, planningAndApprovalWorkflow, taskExecutionStep ] }).then(workflowDiscoveryStep).then(projectDiscoveryStep).then(workflowResearchStep).map(async ({ getStepResult, getInitData }) => { const initData = getInitData(); const discoveryResult = getStepResult(workflowDiscoveryStep); const projectResult = getStepResult(projectDiscoveryStep); return { action: initData.action, workflowName: initData.workflowName, description: initData.description, requirements: initData.requirements, discoveredWorkflows: discoveryResult.workflows, projectStructure: projectResult, // research: researchResult, research: workflowResearch, userAnswers: void 0 }; }).dountil(planningAndApprovalWorkflow, async ({ inputData }) => { console.info(`Sub-workflow check: approved=${inputData.approved}`); return inputData.approved === true; }).map(async ({ getStepResult, getInitData }) => { const initData = getInitData(); const discoveryResult = getStepResult(workflowDiscoveryStep); const projectResult = getStepResult(projectDiscoveryStep); const subWorkflowResult = getStepResult(planningAndApprovalWorkflow); return { action: initData.action, workflowName: initData.workflowName, description: initData.description, requirements: initData.requirements, tasks: subWorkflowResult.tasks, discoveredWorkflows: discoveryResult.workflows, projectStructure: projectResult, // research: researchResult, research: workflowResearch, projectPath: initData.projectPath || process.cwd() }; }).then(taskExecutionStep).commit(); var agentBuilderWorkflows = { "merge-template": agentBuilderTemplateWorkflow, "workflow-builder": workflowBuilderWorkflow }; exports.AgentBuilder = AgentBuilder; exports.AgentBuilderDefaults = AgentBuilderDefaults; exports.agentBuilderTemplateWorkflow = agentBuilderTemplateWorkflow; exports.agentBuilderWorkflows = agentBuilderWorkflows; exports.mergeTemplateBySlug = mergeTemplateBySlug; exports.planningAndApprovalWorkflow = planningAndApprovalWorkflow; exports.workflowBuilderWorkflow = workflowBuilderWorkflow; //# sourceMappingURL=dist-V3SVSSXI.cjs.map //# sourceMappingURL=dist-V3SVSSXI.cjs.map