opencoder
Version:
1,583 lines (1,576 loc) • 595 kB
JavaScript
import { __commonJS, __esm, __export, __require, __toCommonJS, __toESM } from "./assets/chunk-BlwiYZwt.js";
import { ZodFirstPartyTypeKind, ZodIssueCode, z } from "./assets/react-CmaS1f3l.js";
import { AISDKError, dedent_default, import_jsx_runtime } from "./assets/jsx-runtime-DieFuC91.js";
import { experimental_createMCPClient, jsonSchema, tool } from "ai";
import { spawn } from "child_process";
//#region node_modules/ai/mcp-stdio/dist/index.mjs
var ClientOrServerImplementationSchema = z.object({
name: z.string(),
version: z.string()
}).passthrough();
var BaseParamsSchema = z.object({ _meta: z.optional(z.object({}).passthrough()) }).passthrough();
var ResultSchema = BaseParamsSchema;
var RequestSchema = z.object({
method: z.string(),
params: z.optional(BaseParamsSchema)
});
var ServerCapabilitiesSchema = z.object({
experimental: z.optional(z.object({}).passthrough()),
logging: z.optional(z.object({}).passthrough()),
prompts: z.optional(z.object({ listChanged: z.optional(z.boolean()) }).passthrough()),
resources: z.optional(z.object({
subscribe: z.optional(z.boolean()),
listChanged: z.optional(z.boolean())
}).passthrough()),
tools: z.optional(z.object({ listChanged: z.optional(z.boolean()) }).passthrough())
}).passthrough();
var InitializeResultSchema = ResultSchema.extend({
protocolVersion: z.string(),
capabilities: ServerCapabilitiesSchema,
serverInfo: ClientOrServerImplementationSchema,
instructions: z.optional(z.string())
});
var PaginatedResultSchema = ResultSchema.extend({ nextCursor: z.optional(z.string()) });
var ToolSchema = z.object({
name: z.string(),
description: z.optional(z.string()),
inputSchema: z.object({
type: z.literal("object"),
properties: z.optional(z.object({}).passthrough())
}).passthrough()
}).passthrough();
var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: z.array(ToolSchema) });
var TextContentSchema = z.object({
type: z.literal("text"),
text: z.string()
}).passthrough();
var ImageContentSchema = z.object({
type: z.literal("image"),
data: z.string().base64(),
mimeType: z.string()
}).passthrough();
var ResourceContentsSchema = z.object({
uri: z.string(),
mimeType: z.optional(z.string())
}).passthrough();
var TextResourceContentsSchema = ResourceContentsSchema.extend({ text: z.string() });
var BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: z.string().base64() });
var EmbeddedResourceSchema = z.object({
type: z.literal("resource"),
resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
}).passthrough();
var CallToolResultSchema = ResultSchema.extend({
content: z.array(z.union([
TextContentSchema,
ImageContentSchema,
EmbeddedResourceSchema
])),
isError: z.boolean().default(false).optional()
}).or(ResultSchema.extend({ toolResult: z.unknown() }));
var JSONRPC_VERSION = "2.0";
var JSONRPCRequestSchema = z.object({
jsonrpc: z.literal(JSONRPC_VERSION),
id: z.union([z.string(), z.number().int()])
}).merge(RequestSchema).strict();
var JSONRPCResponseSchema = z.object({
jsonrpc: z.literal(JSONRPC_VERSION),
id: z.union([z.string(), z.number().int()]),
result: ResultSchema
}).strict();
var JSONRPCErrorSchema = z.object({
jsonrpc: z.literal(JSONRPC_VERSION),
id: z.union([z.string(), z.number().int()]),
error: z.object({
code: z.number().int(),
message: z.string(),
data: z.optional(z.unknown())
})
}).strict();
var JSONRPCNotificationSchema = z.object({ jsonrpc: z.literal(JSONRPC_VERSION) }).merge(z.object({
method: z.string(),
params: z.optional(BaseParamsSchema)
})).strict();
var JSONRPCMessageSchema = z.union([
JSONRPCRequestSchema,
JSONRPCNotificationSchema,
JSONRPCResponseSchema,
JSONRPCErrorSchema
]);
var name$1 = "AI_MCPClientError";
var marker = `vercel.ai.error.${name$1}`;
var symbol = Symbol.for(marker);
var _a$3;
var MCPClientError = class extends AISDKError {
constructor({ name: name2 = "MCPClientError", message, cause }) {
super({
name: name2,
message,
cause
});
this[_a$3] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker);
}
};
_a$3 = symbol;
function getEnvironment(customEnv) {
const DEFAULT_INHERITED_ENV_VARS = globalThis.process.platform === "win32" ? [
"APPDATA",
"HOMEDRIVE",
"HOMEPATH",
"LOCALAPPDATA",
"PATH",
"PROCESSOR_ARCHITECTURE",
"SYSTEMDRIVE",
"SYSTEMROOT",
"TEMP",
"USERNAME",
"USERPROFILE"
] : [
"HOME",
"LOGNAME",
"PATH",
"SHELL",
"TERM",
"USER"
];
const env = customEnv ? { ...customEnv } : {};
for (const key$1 of DEFAULT_INHERITED_ENV_VARS) {
const value = globalThis.process.env[key$1];
if (value === void 0) continue;
if (value.startsWith("()")) continue;
env[key$1] = value;
}
return env;
}
async function createChildProcess(config, signal) {
var _a2, _b;
return spawn(config.command, (_a2 = config.args) != null ? _a2 : [], {
env: getEnvironment(config.env),
stdio: [
"pipe",
"pipe",
(_b = config.stderr) != null ? _b : "inherit"
],
shell: false,
signal,
windowsHide: globalThis.process.platform === "win32" && isElectron(),
cwd: config.cwd
});
}
function isElectron() {
return "type" in globalThis.process;
}
var StdioMCPTransport = class {
constructor(server) {
this.abortController = new AbortController();
this.readBuffer = new ReadBuffer();
this.serverParams = server;
}
async start() {
if (this.process) throw new MCPClientError({ message: "StdioMCPTransport already started." });
return new Promise(async (resolve, reject) => {
var _a2, _b, _c, _d;
try {
const process$1 = await createChildProcess(this.serverParams, this.abortController.signal);
this.process = process$1;
this.process.on("error", (error) => {
var _a3, _b2;
if (error.name === "AbortError") {
(_a3 = this.onclose) == null ? void 0 : _a3.call(this);
return;
}
reject(error);
(_b2 = this.onerror) == null ? void 0 : _b2.call(this, error);
});
this.process.on("spawn", () => {
resolve();
});
this.process.on("close", (_code) => {
var _a3;
this.process = void 0;
(_a3 = this.onclose) == null ? void 0 : _a3.call(this);
});
(_a2 = this.process.stdin) == null ? void 0 : _a2.on("error", (error) => {
var _a3;
(_a3 = this.onerror) == null ? void 0 : _a3.call(this, error);
});
(_b = this.process.stdout) == null ? void 0 : _b.on("data", (chunk) => {
this.readBuffer.append(chunk);
this.processReadBuffer();
});
(_c = this.process.stdout) == null ? void 0 : _c.on("error", (error) => {
var _a3;
(_a3 = this.onerror) == null ? void 0 : _a3.call(this, error);
});
} catch (error) {
reject(error);
(_d = this.onerror) == null ? void 0 : _d.call(this, error);
}
});
}
processReadBuffer() {
var _a2, _b;
while (true) try {
const message = this.readBuffer.readMessage();
if (message === null) break;
(_a2 = this.onmessage) == null ? void 0 : _a2.call(this, message);
} catch (error) {
(_b = this.onerror) == null ? void 0 : _b.call(this, error);
}
}
async close() {
this.abortController.abort();
this.process = void 0;
this.readBuffer.clear();
}
send(message) {
return new Promise((resolve) => {
var _a2;
if (!((_a2 = this.process) == null ? void 0 : _a2.stdin)) throw new MCPClientError({ message: "StdioClientTransport not connected" });
const json = serializeMessage(message);
if (this.process.stdin.write(json)) resolve();
else this.process.stdin.once("drain", resolve);
});
}
};
var ReadBuffer = class {
append(chunk) {
this.buffer = this.buffer ? Buffer.concat([this.buffer, chunk]) : chunk;
}
readMessage() {
if (!this.buffer) return null;
const index = this.buffer.indexOf("\n");
if (index === -1) return null;
const line = this.buffer.toString("utf8", 0, index);
this.buffer = this.buffer.subarray(index + 1);
return deserializeMessage(line);
}
clear() {
this.buffer = void 0;
}
};
function serializeMessage(message) {
return JSON.stringify(message) + "\n";
}
function deserializeMessage(line) {
return JSONRPCMessageSchema.parse(JSON.parse(line));
}
//#endregion
//#region node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js
var JSONRepairError = class extends Error {
constructor(message, position) {
super("".concat(message, " at position ").concat(position));
this.position = position;
}
};
//#endregion
//#region node_modules/jsonrepair/lib/esm/utils/stringUtils.js
const codeSpace = 32;
const codeNewline = 10;
const codeTab = 9;
const codeReturn = 13;
const codeNonBreakingSpace = 160;
const codeEnQuad = 8192;
const codeHairSpace = 8202;
const codeNarrowNoBreakSpace = 8239;
const codeMediumMathematicalSpace = 8287;
const codeIdeographicSpace = 12288;
function isHex(char) {
return /^[0-9A-Fa-f]$/.test(char);
}
function isDigit(char) {
return char >= "0" && char <= "9";
}
function isValidStringCharacter(char) {
return char >= " ";
}
function isDelimiter(char) {
return ",:[]/{}()\n+".includes(char);
}
function isFunctionNameCharStart(char) {
return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$";
}
function isFunctionNameChar(char) {
return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$" || char >= "0" && char <= "9";
}
const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\/\/$/;
const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;
function isUnquotedStringDelimiter(char) {
return ",[]/{}\n+".includes(char);
}
function isStartOfValue(char) {
return isQuote(char) || regexStartOfValue.test(char);
}
const regexStartOfValue = /^[[{\w-]$/;
function isControlCharacter(char) {
return char === "\n" || char === "\r" || char === " " || char === "\b" || char === "\f";
}
function isWhitespace(text, index) {
const code = text.charCodeAt(index);
return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;
}
function isWhitespaceExceptNewline(text, index) {
const code = text.charCodeAt(index);
return code === codeSpace || code === codeTab || code === codeReturn;
}
function isSpecialWhitespace(text, index) {
const code = text.charCodeAt(index);
return code === codeNonBreakingSpace || code >= codeEnQuad && code <= codeHairSpace || code === codeNarrowNoBreakSpace || code === codeMediumMathematicalSpace || code === codeIdeographicSpace;
}
function isQuote(char) {
return isDoubleQuoteLike(char) || isSingleQuoteLike(char);
}
function isDoubleQuoteLike(char) {
return char === "\"" || char === "“" || char === "”";
}
function isDoubleQuote(char) {
return char === "\"";
}
function isSingleQuoteLike(char) {
return char === "'" || char === "‘" || char === "’" || char === "`" || char === "´";
}
function isSingleQuote(char) {
return char === "'";
}
function stripLastOccurrence(text, textToStrip) {
let stripRemainingText = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
const index = text.lastIndexOf(textToStrip);
return index !== -1 ? text.substring(0, index) + (stripRemainingText ? "" : text.substring(index + 1)) : text;
}
function insertBeforeLastWhitespace(text, textToInsert) {
let index = text.length;
if (!isWhitespace(text, index - 1)) return text + textToInsert;
while (isWhitespace(text, index - 1)) index--;
return text.substring(0, index) + textToInsert + text.substring(index);
}
function removeAtIndex(text, start, count) {
return text.substring(0, start) + text.substring(start + count);
}
function endsWithCommaOrNewline(text) {
return /[,\n][ \t\r]*$/.test(text);
}
//#endregion
//#region node_modules/jsonrepair/lib/esm/regular/jsonrepair.js
const controlCharacters = {
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t"
};
const escapeCharacters = {
"\"": "\"",
"\\": "\\",
"/": "/",
b: "\b",
f: "\f",
n: "\n",
r: "\r",
t: " "
};
function jsonrepair(text) {
let i$3 = 0;
let output = "";
parseMarkdownCodeBlock();
const processed = parseValue();
if (!processed) throwUnexpectedEnd();
parseMarkdownCodeBlock();
const processedComma = parseCharacter(",");
if (processedComma) parseWhitespaceAndSkipComments();
if (isStartOfValue(text[i$3]) && endsWithCommaOrNewline(output)) {
if (!processedComma) output = insertBeforeLastWhitespace(output, ",");
parseNewlineDelimitedJSON();
} else if (processedComma) output = stripLastOccurrence(output, ",");
while (text[i$3] === "}" || text[i$3] === "]") {
i$3++;
parseWhitespaceAndSkipComments();
}
if (i$3 >= text.length) return output;
throwUnexpectedCharacter();
function parseValue() {
parseWhitespaceAndSkipComments();
const processed$1 = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex();
parseWhitespaceAndSkipComments();
return processed$1;
}
function parseWhitespaceAndSkipComments() {
let skipNewline = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
const start = i$3;
let changed = parseWhitespace(skipNewline);
do {
changed = parseComment();
if (changed) changed = parseWhitespace(skipNewline);
} while (changed);
return i$3 > start;
}
function parseWhitespace(skipNewline) {
const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline;
let whitespace = "";
while (true) if (_isWhiteSpace(text, i$3)) {
whitespace += text[i$3];
i$3++;
} else if (isSpecialWhitespace(text, i$3)) {
whitespace += " ";
i$3++;
} else break;
if (whitespace.length > 0) {
output += whitespace;
return true;
}
return false;
}
function parseComment() {
if (text[i$3] === "/" && text[i$3 + 1] === "*") {
while (i$3 < text.length && !atEndOfBlockComment(text, i$3)) i$3++;
i$3 += 2;
return true;
}
if (text[i$3] === "/" && text[i$3 + 1] === "/") {
while (i$3 < text.length && text[i$3] !== "\n") i$3++;
return true;
}
return false;
}
function parseMarkdownCodeBlock() {
if (text.slice(i$3, i$3 + 3) === "```") {
i$3 += 3;
if (isFunctionNameCharStart(text[i$3])) while (i$3 < text.length && isFunctionNameChar(text[i$3])) i$3++;
parseWhitespaceAndSkipComments();
return true;
}
return false;
}
function parseCharacter(char) {
if (text[i$3] === char) {
output += text[i$3];
i$3++;
return true;
}
return false;
}
function skipCharacter(char) {
if (text[i$3] === char) {
i$3++;
return true;
}
return false;
}
function skipEscapeCharacter() {
return skipCharacter("\\");
}
/**
* Skip ellipsis like "[1,2,3,...]" or "[1,2,3,...,9]" or "[...,7,8,9]"
* or a similar construct in objects.
*/
function skipEllipsis() {
parseWhitespaceAndSkipComments();
if (text[i$3] === "." && text[i$3 + 1] === "." && text[i$3 + 2] === ".") {
i$3 += 3;
parseWhitespaceAndSkipComments();
skipCharacter(",");
return true;
}
return false;
}
/**
* Parse an object like '{"key": "value"}'
*/
function parseObject() {
if (text[i$3] === "{") {
output += "{";
i$3++;
parseWhitespaceAndSkipComments();
if (skipCharacter(",")) parseWhitespaceAndSkipComments();
let initial = true;
while (i$3 < text.length && text[i$3] !== "}") {
let processedComma$1;
if (!initial) {
processedComma$1 = parseCharacter(",");
if (!processedComma$1) output = insertBeforeLastWhitespace(output, ",");
parseWhitespaceAndSkipComments();
} else {
processedComma$1 = true;
initial = false;
}
skipEllipsis();
const processedKey = parseString() || parseUnquotedString(true);
if (!processedKey) {
if (text[i$3] === "}" || text[i$3] === "{" || text[i$3] === "]" || text[i$3] === "[" || text[i$3] === void 0) output = stripLastOccurrence(output, ",");
else throwObjectKeyExpected();
break;
}
parseWhitespaceAndSkipComments();
const processedColon = parseCharacter(":");
const truncatedText = i$3 >= text.length;
if (!processedColon) if (isStartOfValue(text[i$3]) || truncatedText) output = insertBeforeLastWhitespace(output, ":");
else throwColonExpected();
const processedValue = parseValue();
if (!processedValue) if (processedColon || truncatedText) output += "null";
else throwColonExpected();
}
if (text[i$3] === "}") {
output += "}";
i$3++;
} else output = insertBeforeLastWhitespace(output, "}");
return true;
}
return false;
}
/**
* Parse an array like '["item1", "item2", ...]'
*/
function parseArray() {
if (text[i$3] === "[") {
output += "[";
i$3++;
parseWhitespaceAndSkipComments();
if (skipCharacter(",")) parseWhitespaceAndSkipComments();
let initial = true;
while (i$3 < text.length && text[i$3] !== "]") {
if (!initial) {
const processedComma$1 = parseCharacter(",");
if (!processedComma$1) output = insertBeforeLastWhitespace(output, ",");
} else initial = false;
skipEllipsis();
const processedValue = parseValue();
if (!processedValue) {
output = stripLastOccurrence(output, ",");
break;
}
}
if (text[i$3] === "]") {
output += "]";
i$3++;
} else output = insertBeforeLastWhitespace(output, "]");
return true;
}
return false;
}
/**
* Parse and repair Newline Delimited JSON (NDJSON):
* multiple JSON objects separated by a newline character
*/
function parseNewlineDelimitedJSON() {
let initial = true;
let processedValue = true;
while (processedValue) {
if (!initial) {
const processedComma$1 = parseCharacter(",");
if (!processedComma$1) output = insertBeforeLastWhitespace(output, ",");
} else initial = false;
processedValue = parseValue();
}
if (!processedValue) output = stripLastOccurrence(output, ",");
output = "[\n".concat(output, "\n]");
}
/**
* Parse a string enclosed by double quotes "...". Can contain escaped quotes
* Repair strings enclosed in single quotes or special quotes
* Repair an escaped string
*
* The function can run in two stages:
* - First, it assumes the string has a valid end quote
* - If it turns out that the string does not have a valid end quote followed
* by a delimiter (which should be the case), the function runs again in a
* more conservative way, stopping the string at the first next delimiter
* and fixing the string by inserting a quote there, or stopping at a
* stop index detected in the first iteration.
*/
function parseString() {
let stopAtDelimiter = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
let stopAtIndex = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : -1;
let skipEscapeChars = text[i$3] === "\\";
if (skipEscapeChars) {
i$3++;
skipEscapeChars = true;
}
if (isQuote(text[i$3])) {
const isEndQuote = isDoubleQuote(text[i$3]) ? isDoubleQuote : isSingleQuote(text[i$3]) ? isSingleQuote : isSingleQuoteLike(text[i$3]) ? isSingleQuoteLike : isDoubleQuoteLike;
const iBefore = i$3;
const oBefore = output.length;
let str = "\"";
i$3++;
while (true) {
if (i$3 >= text.length) {
const iPrev = prevNonWhitespaceIndex(i$3 - 1);
if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {
i$3 = iBefore;
output = output.substring(0, oBefore);
return parseString(true);
}
str = insertBeforeLastWhitespace(str, "\"");
output += str;
return true;
} else if (i$3 === stopAtIndex) {
str = insertBeforeLastWhitespace(str, "\"");
output += str;
return true;
} else if (isEndQuote(text[i$3])) {
const iQuote = i$3;
const oQuote = str.length;
str += "\"";
i$3++;
output += str;
parseWhitespaceAndSkipComments(false);
if (stopAtDelimiter || i$3 >= text.length || isDelimiter(text[i$3]) || isQuote(text[i$3]) || isDigit(text[i$3])) {
parseConcatenatedString();
return true;
}
const iPrevChar = prevNonWhitespaceIndex(iQuote - 1);
const prevChar = text.charAt(iPrevChar);
if (prevChar === ",") {
i$3 = iBefore;
output = output.substring(0, oBefore);
return parseString(false, iPrevChar);
}
if (isDelimiter(prevChar)) {
i$3 = iBefore;
output = output.substring(0, oBefore);
return parseString(true);
}
output = output.substring(0, oBefore);
i$3 = iQuote + 1;
str = "".concat(str.substring(0, oQuote), "\\").concat(str.substring(oQuote));
} else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i$3])) {
if (text[i$3 - 1] === ":" && regexUrlStart.test(text.substring(iBefore + 1, i$3 + 2))) while (i$3 < text.length && regexUrlChar.test(text[i$3])) {
str += text[i$3];
i$3++;
}
str = insertBeforeLastWhitespace(str, "\"");
output += str;
parseConcatenatedString();
return true;
} else if (text[i$3] === "\\") {
const char = text.charAt(i$3 + 1);
const escapeChar = escapeCharacters[char];
if (escapeChar !== void 0) {
str += text.slice(i$3, i$3 + 2);
i$3 += 2;
} else if (char === "u") {
let j = 2;
while (j < 6 && isHex(text[i$3 + j])) j++;
if (j === 6) {
str += text.slice(i$3, i$3 + 6);
i$3 += 6;
} else if (i$3 + j >= text.length) i$3 = text.length;
else throwInvalidUnicodeCharacter();
} else {
str += char;
i$3 += 2;
}
} else {
const char = text.charAt(i$3);
if (char === "\"" && text[i$3 - 1] !== "\\") {
str += "\\".concat(char);
i$3++;
} else if (isControlCharacter(char)) {
str += controlCharacters[char];
i$3++;
} else {
if (!isValidStringCharacter(char)) throwInvalidCharacter(char);
str += char;
i$3++;
}
}
if (skipEscapeChars) skipEscapeCharacter();
}
}
return false;
}
/**
* Repair concatenated strings like "hello" + "world", change this into "helloworld"
*/
function parseConcatenatedString() {
let processed$1 = false;
parseWhitespaceAndSkipComments();
while (text[i$3] === "+") {
processed$1 = true;
i$3++;
parseWhitespaceAndSkipComments();
output = stripLastOccurrence(output, "\"", true);
const start = output.length;
const parsedStr = parseString();
if (parsedStr) output = removeAtIndex(output, start, 1);
else output = insertBeforeLastWhitespace(output, "\"");
}
return processed$1;
}
/**
* Parse a number like 2.4 or 2.4e6
*/
function parseNumber() {
const start = i$3;
if (text[i$3] === "-") {
i$3++;
if (atEndOfNumber()) {
repairNumberEndingWithNumericSymbol(start);
return true;
}
if (!isDigit(text[i$3])) {
i$3 = start;
return false;
}
}
while (isDigit(text[i$3])) i$3++;
if (text[i$3] === ".") {
i$3++;
if (atEndOfNumber()) {
repairNumberEndingWithNumericSymbol(start);
return true;
}
if (!isDigit(text[i$3])) {
i$3 = start;
return false;
}
while (isDigit(text[i$3])) i$3++;
}
if (text[i$3] === "e" || text[i$3] === "E") {
i$3++;
if (text[i$3] === "-" || text[i$3] === "+") i$3++;
if (atEndOfNumber()) {
repairNumberEndingWithNumericSymbol(start);
return true;
}
if (!isDigit(text[i$3])) {
i$3 = start;
return false;
}
while (isDigit(text[i$3])) i$3++;
}
if (!atEndOfNumber()) {
i$3 = start;
return false;
}
if (i$3 > start) {
const num = text.slice(start, i$3);
const hasInvalidLeadingZero = /^0\d/.test(num);
output += hasInvalidLeadingZero ? "\"".concat(num, "\"") : num;
return true;
}
return false;
}
/**
* Parse keywords true, false, null
* Repair Python keywords True, False, None
*/
function parseKeywords() {
return parseKeyword("true", "true") || parseKeyword("false", "false") || parseKeyword("null", "null") || parseKeyword("True", "true") || parseKeyword("False", "false") || parseKeyword("None", "null");
}
function parseKeyword(name$2, value) {
if (text.slice(i$3, i$3 + name$2.length) === name$2) {
output += value;
i$3 += name$2.length;
return true;
}
return false;
}
/**
* Repair an unquoted string by adding quotes around it
* Repair a MongoDB function call like NumberLong("2")
* Repair a JSONP function call like callback({...});
*/
function parseUnquotedString(isKey) {
const start = i$3;
if (isFunctionNameCharStart(text[i$3])) {
while (i$3 < text.length && isFunctionNameChar(text[i$3])) i$3++;
let j = i$3;
while (isWhitespace(text, j)) j++;
if (text[j] === "(") {
i$3 = j + 1;
parseValue();
if (text[i$3] === ")") {
i$3++;
if (text[i$3] === ";") i$3++;
}
return true;
}
}
while (i$3 < text.length && !isUnquotedStringDelimiter(text[i$3]) && !isQuote(text[i$3]) && (!isKey || text[i$3] !== ":")) i$3++;
if (text[i$3 - 1] === ":" && regexUrlStart.test(text.substring(start, i$3 + 2))) while (i$3 < text.length && regexUrlChar.test(text[i$3])) i$3++;
if (i$3 > start) {
while (isWhitespace(text, i$3 - 1) && i$3 > 0) i$3--;
const symbol$1 = text.slice(start, i$3);
output += symbol$1 === "undefined" ? "null" : JSON.stringify(symbol$1);
if (text[i$3] === "\"") i$3++;
return true;
}
}
function parseRegex() {
if (text[i$3] === "/") {
const start = i$3;
i$3++;
while (i$3 < text.length && (text[i$3] !== "/" || text[i$3 - 1] === "\\")) i$3++;
i$3++;
output += "\"".concat(text.substring(start, i$3), "\"");
return true;
}
}
function prevNonWhitespaceIndex(start) {
let prev = start;
while (prev > 0 && isWhitespace(text, prev)) prev--;
return prev;
}
function atEndOfNumber() {
return i$3 >= text.length || isDelimiter(text[i$3]) || isWhitespace(text, i$3);
}
function repairNumberEndingWithNumericSymbol(start) {
output += "".concat(text.slice(start, i$3), "0");
}
function throwInvalidCharacter(char) {
throw new JSONRepairError("Invalid character ".concat(JSON.stringify(char)), i$3);
}
function throwUnexpectedCharacter() {
throw new JSONRepairError("Unexpected character ".concat(JSON.stringify(text[i$3])), i$3);
}
function throwUnexpectedEnd() {
throw new JSONRepairError("Unexpected end of json string", text.length);
}
function throwObjectKeyExpected() {
throw new JSONRepairError("Object key expected", i$3);
}
function throwColonExpected() {
throw new JSONRepairError("Colon expected", i$3);
}
function throwInvalidUnicodeCharacter() {
const chars = text.slice(i$3, i$3 + 6);
throw new JSONRepairError("Invalid unicode character \"".concat(chars, "\""), i$3);
}
}
function atEndOfBlockComment(text, i$3) {
return text[i$3] === "*" && text[i$3 + 1] === "/";
}
//#endregion
//#region node_modules/zod-validation-error/dist/index.mjs
function isZodErrorLike(err) {
return err instanceof Error && err.name === "ZodError" && "issues" in err && Array.isArray(err.issues);
}
var ValidationError = class extends Error {
name;
details;
constructor(message, options) {
super(message, options);
this.name = "ZodValidationError";
this.details = getIssuesFromErrorOptions(options);
}
toString() {
return this.message;
}
};
function getIssuesFromErrorOptions(options) {
if (options) {
const cause = options.cause;
if (isZodErrorLike(cause)) return cause.issues;
}
return [];
}
function isNonEmptyArray(value) {
return value.length !== 0;
}
var identifierRegex = /[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
function joinPath(path) {
if (path.length === 1) return path[0].toString();
return path.reduce((acc, item) => {
if (typeof item === "number") return acc + "[" + item.toString() + "]";
if (item.includes("\"")) return acc + "[\"" + escapeQuotes(item) + "\"]";
if (!identifierRegex.test(item)) return acc + "[\"" + item + "\"]";
const separator = acc.length === 0 ? "" : ".";
return acc + separator + item;
}, "");
}
function escapeQuotes(str) {
return str.replace(/"/g, "\\\"");
}
var ISSUE_SEPARATOR = "; ";
var MAX_ISSUES_IN_MESSAGE = 99;
var PREFIX = "Validation error";
var PREFIX_SEPARATOR = ": ";
var UNION_SEPARATOR = ", or ";
function createMessageBuilder(props = {}) {
const { issueSeparator = ISSUE_SEPARATOR, unionSeparator = UNION_SEPARATOR, prefixSeparator = PREFIX_SEPARATOR, prefix = PREFIX, includePath = true, maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE } = props;
return (issues) => {
const message = issues.slice(0, maxIssuesInMessage).map((issue) => getMessageFromZodIssue({
issue,
issueSeparator,
unionSeparator,
includePath
})).join(issueSeparator);
return prefixMessage(message, prefix, prefixSeparator);
};
}
function getMessageFromZodIssue(props) {
const { issue, issueSeparator, unionSeparator, includePath } = props;
if (issue.code === ZodIssueCode.invalid_union) return issue.unionErrors.reduce((acc, zodError) => {
const newIssues = zodError.issues.map((issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
})).join(issueSeparator);
if (!acc.includes(newIssues)) acc.push(newIssues);
return acc;
}, []).join(unionSeparator);
if (issue.code === ZodIssueCode.invalid_arguments) return [issue.message, ...issue.argumentsError.issues.map((issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
}))].join(issueSeparator);
if (issue.code === ZodIssueCode.invalid_return_type) return [issue.message, ...issue.returnTypeError.issues.map((issue2) => getMessageFromZodIssue({
issue: issue2,
issueSeparator,
unionSeparator,
includePath
}))].join(issueSeparator);
if (includePath && isNonEmptyArray(issue.path)) {
if (issue.path.length === 1) {
const identifier = issue.path[0];
if (typeof identifier === "number") return `${issue.message} at index ${identifier}`;
}
return `${issue.message} at "${joinPath(issue.path)}"`;
}
return issue.message;
}
function prefixMessage(message, prefix, prefixSeparator) {
if (prefix !== null) {
if (message.length > 0) return [prefix, message].join(prefixSeparator);
return prefix;
}
if (message.length > 0) return message;
return PREFIX;
}
function fromZodError(zodError, options = {}) {
if (!isZodErrorLike(zodError)) throw new TypeError(`Invalid zodError param; expected instance of ZodError. Did you mean to use the "${fromError.name}" method instead?`);
return fromZodErrorWithoutRuntimeCheck(zodError, options);
}
function fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {
const zodIssues = zodError.errors;
let message;
if (isNonEmptyArray(zodIssues)) {
const messageBuilder = createMessageBuilderFromOptions2(options);
message = messageBuilder(zodIssues);
} else message = zodError.message;
return new ValidationError(message, { cause: zodError });
}
function createMessageBuilderFromOptions2(options) {
if ("messageBuilder" in options) return options.messageBuilder;
return createMessageBuilder(options);
}
var toValidationError = (options = {}) => (err) => {
if (isZodErrorLike(err)) return fromZodErrorWithoutRuntimeCheck(err, options);
if (err instanceof Error) return new ValidationError(err.message, { cause: err });
return new ValidationError("Unknown error");
};
function fromError(err, options = {}) {
return toValidationError(options)(err);
}
//#endregion
//#region node_modules/delay/index.js
const createAbortError = () => {
const error = new Error("Delay aborted");
error.name = "AbortError";
return error;
};
const clearMethods = new WeakMap();
function createDelay({ clearTimeout: defaultClear, setTimeout: defaultSet } = {}) {
return (milliseconds, { value, signal } = {}) => {
if (signal?.aborted) return Promise.reject(createAbortError());
let timeoutId;
let settle;
let rejectFunction;
const clear = defaultClear ?? clearTimeout;
const signalListener = () => {
clear(timeoutId);
rejectFunction(createAbortError());
};
const cleanup = () => {
if (signal) signal.removeEventListener("abort", signalListener);
};
const delayPromise = new Promise((resolve, reject) => {
settle = () => {
cleanup();
resolve(value);
};
rejectFunction = reject;
timeoutId = (defaultSet ?? setTimeout)(settle, milliseconds);
});
if (signal) signal.addEventListener("abort", signalListener, { once: true });
clearMethods.set(delayPromise, () => {
clear(timeoutId);
timeoutId = null;
settle();
});
return delayPromise;
};
}
const delay$1 = createDelay();
//#endregion
//#region node_modules/openai-zod-to-json-schema/dist/index.js
var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions$4 = {
name: void 0,
$refStrategy: "root",
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
nullableStrategy: "from-target",
removeAdditionalStrategy: "passthrough",
definitionPath: "definitions",
target: "jsonSchema7",
strictUnions: false,
errorMessages: false,
markdownDescription: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions = (options) => {
return typeof options === "string" ? {
...defaultOptions$4,
basePath: ["#"],
definitions: {},
name: options
} : {
...defaultOptions$4,
basePath: ["#"],
definitions: {},
...options
};
};
var zodDef = (zodSchema) => {
return "_def" in zodSchema ? zodSchema._def : zodSchema;
};
function isEmptyObj(obj) {
if (!obj) return true;
for (const _k in obj) return false;
return true;
}
var getRefs = (options) => {
const _options = getDefaultOptions(options);
const currentPath = _options.name !== void 0 ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return {
..._options,
currentPath,
propertyPath: void 0,
seenRefs: /* @__PURE__ */ new Set(),
seen: new Map(Object.entries(_options.definitions).map(([name$2, def]) => [zodDef(def), {
def: zodDef(def),
path: [
..._options.basePath,
_options.definitionPath,
name$2
],
jsonSchema: void 0
}]))
};
};
function addErrorMessage(res, key$1, errorMessage, refs) {
if (!refs?.errorMessages) return;
if (errorMessage) res.errorMessage = {
...res.errorMessage,
[key$1]: errorMessage
};
}
function setResponseValueAndErrors(res, key$1, value, errorMessage, refs) {
res[key$1] = value;
addErrorMessage(res, key$1, errorMessage, refs);
}
function parseAnyDef() {
return {};
}
function parseArrayDef(def, refs) {
const res = { type: "array" };
if (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 check of def.checks) switch (check.kind) {
case "min":
if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
else {
if (!check.inclusive) res.exclusiveMinimum = true;
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
break;
case "max":
if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
else {
if (!check.inclusive) res.exclusiveMaximum = true;
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
break;
case "multipleOf":
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
break;
}
return res;
}
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$3) => 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 check of def.checks) switch (check.kind) {
case "min":
setResponseValueAndErrors(
res,
"minimum",
check.value,
// This is in milliseconds
check.message,
refs
);
break;
case "max":
setResponseValueAndErrors(
res,
"maximum",
check.value,
// This is in milliseconds
check.message,
refs
);
break;
}
return res;
};
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
function parseEffectsDef(_def, refs, forceResolution) {
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs, forceResolution) : {};
}
function parseEnumDef(def) {
return {
type: "string",
enum: [...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 parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
if (refs.target === "openApi3") return {
type: parsedType === "bigint" ? "integer" : parsedType,
enum: [def.value]
};
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
var emojiRegex;
var zodPatterns = {
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
emoji: () => {
if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
return emojiRegex;
},
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}$/,
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
ipv6: /^(([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})))$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/
};
function parseStringDef(def, refs) {
const res = { type: "string" };
function processPattern(value) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(value) : value;
}
if (def.checks) for (const check of def.checks) switch (check.kind) {
case "min":
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
break;
case "max":
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat(res, "idn-email", check.message, refs);
break;
case "pattern:zod":
addPattern(res, zodPatterns.email, check.message, refs);
break;
}
break;
case "url":
addFormat(res, "uri", check.message, refs);
break;
case "uuid":
addFormat(res, "uuid", check.message, refs);
break;
case "regex":
addPattern(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern(res, zodPatterns.cuid, check.message, refs);
break;
case "cuid2":
addPattern(res, zodPatterns.cuid2, check.message, refs);
break;
case "startsWith":
addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);
break;
case "endsWith":
addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);
break;
case "datetime":
addFormat(res, "date-time", check.message, refs);
break;
case "date":
addFormat(res, "date", check.message, refs);
break;
case "time":
addFormat(res, "time", check.message, refs);
break;
case "duration":
addFormat(res, "duration", check.message, refs);
break;
case "length":
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
break;
case "includes": {
addPattern(res, RegExp(processPattern(check.value)), check.message, refs);
break;
}
case "ip": {
if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs);
if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs);
break;
}
case "emoji":
addPattern(res, zodPatterns.emoji, check.message, refs);
break;
case "ulid": {
addPattern(res, zodPatterns.ulid, check.message, refs);
break;
}
case "base64": {
switch (refs.base64Strategy) {
case "format:binary": {
addFormat(res, "binary", check.message, refs);
break;
}
case "contentEncoding:base64": {
setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
break;
}
case "pattern:zod": {
addPattern(res, zodPatterns.base64, check.message, refs);
break;
}
}
break;
}
case "nanoid": addPattern(res, zodPatterns.nanoid, check.message, refs);
case "toLowerCase":
case "toUpperCase":
case "trim": break;
default: /* @__PURE__ */ ((_) => {})(check);
}
return res;
}
var escapeNonAlphaNumeric = (value) => Array.from(value).map((c) => /[a-zA-Z0-9]/.test(c) ? c : `\\${c}`).join("");
var 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);
};
var addPattern = (schema, regex$1, 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: processRegExp(regex$1, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else setResponseValueAndErrors(schema, "pattern", processRegExp(regex$1, refs), message, refs);
};
var processRegExp = (regexOrFunction, refs) => {
const regex$1 = typeof regexOrFunction === "function" ? regexOrFunction() : regexOrFunction;
if (!refs.applyRegexFlags || !regex$1.flags) return regex$1.source;
const flags = {
i: regex$1.flags.includes("i"),
m: regex$1.flags.includes("m"),
s: regex$1.flags.includes("s")
};
const source = flags.i ? regex$1.source.toLowerCase() : regex$1.source;
let pattern = "";
let isEscaped$1 = false;
let inCharGroup = false;
let inCharRange = false;
for (let i$3 = 0; i$3 < source.length; i$3++) {
if (isEscaped$1) {
pattern += source[i$3];
isEscaped$1 = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i$3].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i$3];
pattern += `${source[i$3 - 2]}-${source[i$3]}`.toUpperCase();
inCharRange = false;
} else if (source[i$3 + 1] === "-" && source[i$3 + 2]?.match(/[a-z]/)) {
pattern += source[i$3];
inCharRange = true;
} else pattern += `${source[i$3]}${source[i$3].toUpperCase()}`;
continue;
}
} else if (source[i$3].match(/[a-z]/)) {
pattern += `[${source[i$3]}${source[i$3].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i$3] === "^") {
pattern += `(^|(?<=[\r
]))`;
continue;
} else if (source[i$3] === "$") {
pattern += `($|(?=[\r
]))`;
continue;
}
}
if (flags.s && source[i$3] === ".") {
pattern += inCharGroup ? `${source[i$3]}\r
` : `[${source[i$3]}\r
]`;
continue;
}
pattern += source[i$3];
if (source[i$3] === "\\") isEscaped$1 = true;
else if (inCharGroup && source[i$3] === "]") inCharGroup = false;
else if (!inCharGroup && source[i$3] === "[") inCharGroup = true;
}
try {
const regexTest = new RegExp(pattern);
} catch {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex$1.source;
}
return pattern;
};
function parseRecordDef(def, refs) {
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$1) => ({
...acc,
[key$1]: parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"properties",
key$1
]
}) ?? {}
}), {}),
additionalProperties: false
};
const schema = {
type: "object",
additionalProperties: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
}) ?? {}
};
if (refs.target === "openApi3") return schema;
if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key$1, value]) => key$1 === "type" ? acc : {
...acc,
[key$1]: value
}, {});
return {
...schema,
propertyNames: keyType
};
} else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {
...schema,
propertyNames: { enum: def.keyType._def.values }
};
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"
]
}) || {};
const values = parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"1"
]
}) || {};
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [keys, values],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef(def) {
const object = def.values;
const actualKeys = Object.keys(def.values).filter((key$1) => {
return typeof object[object[key$1]] !== "number";
});
const actualValues = actualKeys.map((key$1) => object[key$1]);
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() {
return { not: {} };
}
function parseNullDef(refs) {
return refs.target === "openApi3" ? {
enum: ["null"],
nullable: true
} : { type: "null" };
}
var primitiveMappings = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer"