@21st-extension/toolbar
Version:
21st.dev toolbar SDK for AI Agent interaction.
1,286 lines • 233 kB
JavaScript
import { l as l$1, K as K$1, u as u$1, x as x$2, _ as _$1, k as k$2, H as H$1, b as b$1, J as J$1, E as E$1, G as G$1 } from "./jsx-runtime-BI3iOU20.js";
var t, r$1, u, i, o = 0, f = [], c = l$1, e = c.__b, a = c.__r, v = c.diffed, l = c.__c, m = c.unmount, s = c.__;
function p(n, t2) {
c.__h && c.__h(r$1, n, o || t2), o = 0;
var u2 = r$1.__H || (r$1.__H = { __: [], __h: [] });
return n >= u2.__.length && u2.__.push({}), u2.__[n];
}
function d(n) {
return o = 1, h(D$1, n);
}
function h(n, u2, i2) {
var o2 = p(t++, 2);
if (o2.t = n, !o2.__c && (o2.__ = [i2 ? i2(u2) : D$1(void 0, u2), function(n2) {
var t2 = o2.__N ? o2.__N[0] : o2.__[0], r2 = o2.t(t2, n2);
t2 !== r2 && (o2.__N = [r2, o2.__[1]], o2.__c.setState({}));
}], o2.__c = r$1, !r$1.__f)) {
var f2 = function(n2, t2, r2) {
if (!o2.__c.__H) return !0;
var u3 = o2.__c.__H.__.filter(function(n3) {
return !!n3.__c;
});
if (u3.every(function(n3) {
return !n3.__N;
})) return !c2 || c2.call(this, n2, t2, r2);
var i3 = o2.__c.props !== n2;
return u3.forEach(function(n3) {
if (n3.__N) {
var t3 = n3.__[0];
n3.__ = n3.__N, n3.__N = void 0, t3 !== n3.__[0] && (i3 = !0);
}
}), c2 && c2.call(this, n2, t2, r2) || i3;
};
r$1.__f = !0;
var c2 = r$1.shouldComponentUpdate, e2 = r$1.componentWillUpdate;
r$1.componentWillUpdate = function(n2, t2, r2) {
if (this.__e) {
var u3 = c2;
c2 = void 0, f2(n2, t2, r2), c2 = u3;
}
e2 && e2.call(this, n2, t2, r2);
}, r$1.shouldComponentUpdate = f2;
}
return o2.__N || o2.__;
}
function y(n, u2) {
var i2 = p(t++, 3);
!c.__s && C$1(i2.__H, u2) && (i2.__ = n, i2.u = u2, r$1.__H.__h.push(i2));
}
function _(n, u2) {
var i2 = p(t++, 4);
!c.__s && C$1(i2.__H, u2) && (i2.__ = n, i2.u = u2, r$1.__h.push(i2));
}
function A$1(n) {
return o = 5, T$1(function() {
return { current: n };
}, []);
}
function F$1(n, t2, r2) {
o = 6, _(function() {
if (typeof n == "function") {
var r3 = n(t2());
return function() {
n(null), r3 && typeof r3 == "function" && r3();
};
}
if (n) return n.current = t2(), function() {
return n.current = null;
};
}, r2 == null ? r2 : r2.concat(n));
}
function T$1(n, r2) {
var u2 = p(t++, 7);
return C$1(u2.__H, r2) && (u2.__ = n(), u2.__H = r2, u2.__h = n), u2.__;
}
function q$1(n, t2) {
return o = 8, T$1(function() {
return n;
}, t2);
}
function x$1(n) {
var u2 = r$1.context[n.__c], i2 = p(t++, 9);
return i2.c = n, u2 ? (i2.__ == null && (i2.__ = !0, u2.sub(r$1)), u2.props.value) : n.__;
}
function P$1(n, t2) {
c.useDebugValue && c.useDebugValue(t2 ? t2(n) : n);
}
function b(n) {
var u2 = p(t++, 10), i2 = d();
return u2.__ = n, r$1.componentDidCatch || (r$1.componentDidCatch = function(n2, t2) {
u2.__ && u2.__(n2, t2), i2[1](n2);
}), [i2[0], function() {
i2[1](void 0);
}];
}
function g$1() {
var n = p(t++, 11);
if (!n.__) {
for (var u2 = r$1.__v; u2 !== null && !u2.__m && u2.__ !== null; ) u2 = u2.__;
var i2 = u2.__m || (u2.__m = [0, 0]);
n.__ = "P" + i2[0] + "-" + i2[1]++;
}
return n.__;
}
function j$1() {
for (var n; n = f.shift(); ) if (n.__P && n.__H) try {
n.__H.__h.forEach(z$1), n.__H.__h.forEach(B$1), n.__H.__h = [];
} catch (t2) {
n.__H.__h = [], c.__e(t2, n.__v);
}
}
c.__b = function(n) {
r$1 = null, e && e(n);
}, c.__ = function(n, t2) {
n && t2.__k && t2.__k.__m && (n.__m = t2.__k.__m), s && s(n, t2);
}, c.__r = function(n) {
a && a(n), t = 0;
var i2 = (r$1 = n.__c).__H;
i2 && (u === r$1 ? (i2.__h = [], r$1.__h = [], i2.__.forEach(function(n2) {
n2.__N && (n2.__ = n2.__N), n2.u = n2.__N = void 0;
})) : (i2.__h.forEach(z$1), i2.__h.forEach(B$1), i2.__h = [], t = 0)), u = r$1;
}, c.diffed = function(n) {
v && v(n);
var t2 = n.__c;
t2 && t2.__H && (t2.__H.__h.length && (f.push(t2) !== 1 && i === c.requestAnimationFrame || ((i = c.requestAnimationFrame) || w$1)(j$1)), t2.__H.__.forEach(function(n2) {
n2.u && (n2.__H = n2.u), n2.u = void 0;
})), u = r$1 = null;
}, c.__c = function(n, t2) {
t2.some(function(n2) {
try {
n2.__h.forEach(z$1), n2.__h = n2.__h.filter(function(n3) {
return !n3.__ || B$1(n3);
});
} catch (r2) {
t2.some(function(n3) {
n3.__h && (n3.__h = []);
}), t2 = [], c.__e(r2, n2.__v);
}
}), l && l(n, t2);
}, c.unmount = function(n) {
m && m(n);
var t2, r2 = n.__c;
r2 && r2.__H && (r2.__H.__.forEach(function(n2) {
try {
z$1(n2);
} catch (n3) {
t2 = n3;
}
}), r2.__H = void 0, t2 && c.__e(t2, r2.__v));
};
var k$1 = typeof requestAnimationFrame == "function";
function w$1(n) {
var t2, r2 = function() {
clearTimeout(u2), k$1 && cancelAnimationFrame(t2), setTimeout(n);
}, u2 = setTimeout(r2, 35);
k$1 && (t2 = requestAnimationFrame(r2));
}
function z$1(n) {
var t2 = r$1, u2 = n.__c;
typeof u2 == "function" && (n.__c = void 0, u2()), r$1 = t2;
}
function B$1(n) {
var t2 = r$1;
n.__c = n.__(), r$1 = t2;
}
function C$1(n, t2) {
return !n || n.length !== t2.length || t2.some(function(t3, r2) {
return t3 !== n[r2];
});
}
function D$1(n, t2) {
return typeof t2 == "function" ? t2(n) : t2;
}
const ConfigContext = K$1({
config: void 0
});
function ConfigProvider({
children,
config
}) {
const value = T$1(() => ({
config
}), [config]);
return /* @__PURE__ */ u$1(ConfigContext.Provider, { value, children });
}
function useConfig() {
return x$1(ConfigContext);
}
var generateId$1 = (length = 16) => Math.random().toString(36).substring(2, length + 2), DEFAULT_OPTIONS = {
maxReconnectAttempts: 5,
reconnectDelay: 1e3,
requestTimeout: 3e4
// Extended timeout for longer operations
}, WebSocketRpcBridge = class {
constructor(options = {}) {
this.ws = null, this.pendingRequests = /* @__PURE__ */ new Map(), this.reconnectAttempts = 0, this.methods = {}, this.isIntentionalClose = !1, this.options = { ...DEFAULT_OPTIONS, ...options };
}
/**
* Register RPC method handlers
* @param methodHandlers Object containing method handlers
*/
register(methodHandlers) {
Object.entries(methodHandlers).forEach(([methodName, handler]) => {
this.methods[methodName] = { handler };
});
}
/**
* Generic method to call a remote procedure with support for streaming updates
* @param method Method name to call
* @param payload Request payload
* @param onUpdate Optional callback for progress updates
* @returns Promise resolving with the response
*/
callMethod(method, payload, onUpdate) {
if (!this.ws)
throw new Error("WebSocket is not connected");
const id = generateId$1(), requestMessage = {
id,
messageType: "request",
method,
payload
};
return new Promise((resolve, reject) => {
var _a;
const timeout = setTimeout(() => {
this.pendingRequests.delete(id), reject(new Error(`Request timed out: ${method}`));
}, this.options.requestTimeout);
this.pendingRequests.set(id, { resolve, reject, timeout, onUpdate }), (_a = this.ws) == null || _a.send(JSON.stringify(requestMessage));
});
}
/**
* Sets up WebSocket event handlers
* @param ws WebSocket instance
*/
setupWebSocketHandlers(ws) {
ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data);
this.handleMessage(message);
} catch (error) {
console.error("Error handling WebSocket message:", error);
}
}, ws.onclose = () => {
this.handleDisconnect();
}, ws.onerror = (event) => {
console.error("WebSocket error:", event);
};
}
/**
* Handles incoming WebSocket messages
* @param message The message to handle
*/
handleMessage(message) {
const { messageType, id } = message;
switch (messageType) {
case "request":
this.handleRequest(message);
break;
case "response":
this.handleResponse(id, message.payload);
break;
case "update":
this.handleUpdate(id, message.payload);
break;
case "error":
this.handleError(id, message.error.message);
break;
default:
console.warn(`Unknown message type: ${messageType}`);
}
}
/**
* Handle incoming requests by invoking the registered method
* @param message Request message
*/
async handleRequest(message) {
const { id, method, payload } = message;
if (!method) {
this.sendError(id, "Method name is required");
return;
}
const methodDef = this.methods[method];
if (!methodDef) {
this.sendError(id, `Method not found: ${method}`);
return;
}
try {
const sendUpdate = (update) => {
this.sendUpdate(id, method, update);
}, result = await methodDef.handler(payload, sendUpdate);
this.sendResponse(id, method, result);
} catch (error) {
this.sendError(
id,
error instanceof Error ? error.message : String(error)
);
}
}
/**
* Handle response messages by resolving the pending request
* @param id Request ID
* @param payload Response payload
*/
handleResponse(id, payload) {
const pendingRequest = this.pendingRequests.get(id);
if (!pendingRequest) {
console.warn(`Received response for unknown request ID: ${id}`);
return;
}
clearTimeout(pendingRequest.timeout), this.pendingRequests.delete(id), pendingRequest.resolve(payload);
}
/**
* Handle update messages by calling the update callback
* @param id Request ID
* @param payload Update payload
*/
handleUpdate(id, payload) {
const pendingRequest = this.pendingRequests.get(id);
if (!pendingRequest || !pendingRequest.onUpdate) {
console.warn(`Received update for unknown request ID: ${id}`);
return;
}
pendingRequest.onUpdate(payload);
}
/**
* Handle error messages by rejecting the pending request
* @param id Request ID
* @param error Error message
*/
handleError(id, error) {
const pendingRequest = this.pendingRequests.get(id);
if (!pendingRequest) {
console.warn(`Received error for unknown request ID: ${id}`);
return;
}
clearTimeout(pendingRequest.timeout), this.pendingRequests.delete(id), pendingRequest.reject(new Error(error));
}
/**
* Send a response message
* @param id Request ID
* @param method Method name
* @param payload Response payload
*/
sendResponse(id, method, payload) {
if (!this.ws)
throw new Error("WebSocket is not connected");
const responseMessage = {
id,
messageType: "response",
method,
payload
};
this.ws.send(JSON.stringify(responseMessage));
}
/**
* Send an update message for streaming
* @param id Request ID
* @param method Method name
* @param payload Update payload
*/
sendUpdate(id, method, payload) {
if (!this.ws)
throw new Error("WebSocket is not connected");
const updateMessage = {
id,
messageType: "update",
method,
payload
};
this.ws.send(JSON.stringify(updateMessage));
}
/**
* Send an error message
* @param id Request ID
* @param errorMessage Error message
*/
sendError(id, errorMessage) {
if (!this.ws)
throw new Error("WebSocket is not connected");
const errorResponse = {
id,
messageType: "error",
error: {
message: errorMessage
}
};
this.ws.send(JSON.stringify(errorResponse));
}
/**
* Handle disconnection by attempting to reconnect
*/
handleDisconnect() {
if (this.isIntentionalClose) {
console.log(
"WebSocket closed intentionally, not attempting to reconnect"
), this.clearPendingRequests(new Error("Connection closed by user"));
return;
}
this.reconnectAttempts < this.options.maxReconnectAttempts ? (this.reconnectAttempts++, console.log(
`Attempting to reconnect (${this.reconnectAttempts}/${this.options.maxReconnectAttempts})...`
), setTimeout(
() => this.reconnect(),
this.options.reconnectDelay * this.reconnectAttempts
)) : (console.error("Max reconnection attempts reached"), this.clearPendingRequests(new Error("Connection closed")));
}
/**
* Clear all pending requests with an error
* @param error Error to reject with
*/
clearPendingRequests(error) {
this.pendingRequests.forEach(({ reject }) => {
reject(error);
}), this.pendingRequests.clear();
}
/**
* Close the WebSocket connection
* @returns Promise that resolves when the connection is closed
*/
async close() {
this.isIntentionalClose = !0, this.ws && (this.ws.close(), this.ws = null), this.clearPendingRequests(new Error("Connection closed by user"));
}
};
function validateWithZod(schema, data, context, silent = !1) {
const result = schema.safeParse(data);
if (!result.success) {
const error = new Error(
`Validation failed for ${context}: ${result.error.message}`
);
if (silent)
return console.error(error), data;
throw error;
}
return result.data;
}
var ZodTypedBridge = class {
constructor(bridge, contract2) {
this.bridge = bridge, this.contract = contract2, this.call = new Proxy({}, {
get: (target, prop) => (request, options) => this.callMethod(prop, request, options)
});
}
async callMethod(method, request, options) {
const methodContract = this.contract.consumes[method];
if (!methodContract)
throw new Error(`Method ${String(method)} not found in contract`);
const validatedRequest = validateWithZod(
methodContract.request,
request,
`request for method ${String(method)}`
), onUpdate = options != null && options.onUpdate && methodContract.update ? (update) => {
var _a;
if (methodContract.update)
try {
const validatedUpdate = validateWithZod(
methodContract.update,
update,
`update for method ${String(method)}`,
!0
// silently log validation errors
);
(_a = options.onUpdate) == null || _a.call(options, validatedUpdate);
} catch (error) {
console.error("Update validation failed:", error);
}
} : void 0, response = await this.bridge.callMethod(
method,
validatedRequest,
onUpdate
);
return validateWithZod(
methodContract.response,
response,
`response for method ${String(method)}`
);
}
register(implementations) {
const wrappedImplementations = {};
for (const [method, implementation] of Object.entries(implementations)) {
const methodContract = this.contract.serves[method];
if (!methodContract)
throw new Error(`Method ${method} not found in contract`);
wrappedImplementations[method] = async (request, sendUpdate) => {
const validatedRequest = validateWithZod(
methodContract.request,
request,
`request for method ${method}`
), wrappedSendUpdate = methodContract.update && sendUpdate ? (update) => {
if (methodContract.update)
try {
const validatedUpdate = validateWithZod(
methodContract.update,
update,
`update for method ${method}`,
!0
// silently log validation errors
);
sendUpdate(validatedUpdate);
} catch (error) {
console.error("Update validation failed:", error);
}
} : void 0, response = await implementation(validatedRequest, {
sendUpdate: wrappedSendUpdate
});
return validateWithZod(
methodContract.response,
response,
`response for method ${method}`
);
};
}
this.bridge.register(wrappedImplementations);
}
async close() {
await this.bridge.close();
}
}, ClientBridge = class extends WebSocketRpcBridge {
constructor(url, options) {
super(options), this.reconnectTimer = null, this.url = url;
}
call(method, payload, onUpdate) {
return this.callMethod(method, payload, onUpdate);
}
reconnect() {
this.reconnectTimer && clearTimeout(this.reconnectTimer), this.reconnectTimer = setTimeout(async () => {
try {
await this.connect();
} catch {
this.reconnect();
}
}, this.options.reconnectDelay);
}
connect() {
return new Promise((resolve, reject) => {
try {
const ws = new window.WebSocket(this.url);
ws.onopen = () => {
this.ws = ws, this.setupWebSocketHandlers(ws), resolve();
}, ws.onerror = () => {
reject(new Error("Failed to connect to WebSocket server"));
};
} catch (error) {
reject(error);
}
});
}
}, ZodClient = class extends ZodTypedBridge {
constructor(url, contract2, options) {
super(new ClientBridge(url, options), {
serves: contract2.client || {},
consumes: contract2.server || {}
});
}
connect() {
return this.bridge.connect();
}
};
function createSRPCClientBridge(url, contract2, options) {
return new ZodClient(url, contract2, options);
}
var util;
(function(util2) {
util2.assertEqual = (_2) => {
};
function assertIs(_arg) {
}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever, util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items)
obj[item] = item;
return obj;
}, util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] != "number"), filtered = {};
for (const k2 of validKeys)
filtered[k2] = obj[k2];
return util2.objectValues(filtered);
}, util2.objectValues = (obj) => util2.objectKeys(obj).map(function(e2) {
return obj[e2];
}), util2.objectKeys = typeof Object.keys == "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object)
Object.prototype.hasOwnProperty.call(object, key) && keys.push(key);
return keys;
}, util2.find = (arr, checker) => {
for (const item of arr)
if (checker(item))
return item;
}, util2.isInteger = typeof Number.isInteger == "function" ? (val) => Number.isInteger(val) : (val) => typeof val == "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val == "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues, util2.jsonStringifyReplacer = (_2, value) => typeof value == "bigint" ? value.toString() : value;
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => ({
...first,
...second
// second overwrites first
});
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]), getParsedType = (data) => {
switch (typeof data) {
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":
return Array.isArray(data) ? ZodParsedType.array : data === null ? ZodParsedType.null : data.then && typeof data.then == "function" && data.catch && typeof data.catch == "function" ? ZodParsedType.promise : typeof Map < "u" && data instanceof Map ? ZodParsedType.map : typeof Set < "u" && data instanceof Set ? ZodParsedType.set : typeof Date < "u" && data instanceof Date ? ZodParsedType.date : ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
}, 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"
]);
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;
Object.setPrototypeOf ? Object.setPrototypeOf(this, actualProto) : this.__proto__ = actualProto, this.name = "ZodError", this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
}, fieldErrors = { _errors: [] }, processError = (error) => {
for (const issue of error.issues)
if (issue.code === "invalid_union")
issue.unionErrors.map(processError);
else if (issue.code === "invalid_return_type")
processError(issue.returnTypeError);
else if (issue.code === "invalid_arguments")
processError(issue.argumentsError);
else if (issue.path.length === 0)
fieldErrors._errors.push(mapper(issue));
else {
let curr = fieldErrors, i2 = 0;
for (; i2 < issue.path.length; ) {
const el = issue.path[i2];
i2 === issue.path.length - 1 ? (curr[el] = curr[el] || { _errors: [] }, curr[el]._errors.push(mapper(issue))) : curr[el] = curr[el] || { _errors: [] }, curr = curr[el], i2++;
}
}
};
return processError(this), 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 = (issue) => issue.message) {
const fieldErrors = {}, 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) => new ZodError(issues);
const errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
issue.received === ZodParsedType.undefined ? message = "Required" : message = `Expected ${issue.expected}, received ${issue.received}`;
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = "Invalid input";
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = "Invalid function arguments";
break;
case ZodIssueCode.invalid_return_type:
message = "Invalid function return type";
break;
case ZodIssueCode.invalid_date:
message = "Invalid date";
break;
case ZodIssueCode.invalid_string:
typeof issue.validation == "object" ? "includes" in issue.validation ? (message = `Invalid input: must include "${issue.validation.includes}"`, typeof issue.validation.position == "number" && (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)) : "startsWith" in issue.validation ? message = `Invalid input: must start with "${issue.validation.startsWith}"` : "endsWith" in issue.validation ? message = `Invalid input: must end with "${issue.validation.endsWith}"` : util.assertNever(issue.validation) : issue.validation !== "regex" ? message = `Invalid ${issue.validation}` : message = "Invalid";
break;
case ZodIssueCode.too_small:
issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} ${issue.minimum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} ${issue.minimum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : issue.type === "bigint" ? message = `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(issue.minimum))}` : message = "Invalid input";
break;
case ZodIssueCode.too_big:
issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} ${issue.maximum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} ${issue.maximum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "bigint" ? message = `BigInt must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(issue.maximum))}` : message = "Invalid input";
break;
case ZodIssueCode.custom:
message = "Invalid input";
break;
case ZodIssueCode.invalid_intersection_types:
message = "Intersection results could not be merged";
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError, util.assertNever(issue);
}
return { message };
};
let overrideErrorMap = errorMap;
function getErrorMap() {
return overrideErrorMap;
}
const makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params, fullPath = [...path, ...issueData.path || []], fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0)
return {
...issueData,
path: fullPath,
message: issueData.message
};
let errorMessage = "";
const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
for (const map of maps)
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap(), issue = 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 === errorMap ? void 0 : errorMap
// then global default map
].filter((x2) => !!x2)
});
ctx.common.issues.push(issue);
}
class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
this.value === "valid" && (this.value = "dirty");
}
abort() {
this.value !== "aborted" && (this.value = "aborted");
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s2 of results) {
if (s2.status === "aborted")
return INVALID;
s2.status === "dirty" && status.dirty(), arrayValue.push(s2.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key, 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" || value.status === "aborted")
return INVALID;
key.status === "dirty" && status.dirty(), value.status === "dirty" && status.dirty(), key.value !== "__proto__" && (typeof value.value < "u" || pair.alwaysSet) && (finalObject[key.value] = value.value);
}
return { status: status.value, value: finalObject };
}
}
const INVALID = Object.freeze({
status: "aborted"
}), DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x2) => x2.status === "aborted", isDirty = (x2) => x2.status === "dirty", isValid = (x2) => x2.status === "valid", isAsync = (x2) => typeof Promise < "u" && x2 instanceof Promise;
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message == "string" ? { message } : message || {}, errorUtil2.toString = (message) => typeof message == "string" ? message : message == null ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
class ParseInputLazyPath {
constructor(parent, value, path, key) {
this._cachedPath = [], this.parent = parent, this.data = value, this._path = path, this._key = key;
}
get path() {
return this._cachedPath.length || (Array.isArray(this._key) ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath;
}
}
const handleResult = (ctx, result) => {
if (isValid(result))
return { success: !0, data: result.value };
if (!ctx.common.issues.length)
throw new Error("Validation failed but no issues detected.");
return {
success: !1,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
return this._error = error, this._error;
}
};
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error))
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
return errorMap2 ? { errorMap: errorMap2, description } : { errorMap: (iss, ctx) => {
const { message } = params;
return iss.code === "invalid_enum_value" ? { message: message ?? ctx.defaultError } : typeof ctx.data > "u" ? { message: message ?? required_error ?? ctx.defaultError } : iss.code !== "invalid_type" ? { message: ctx.defaultError } : { message: message ?? invalid_type_error ?? ctx.defaultError };
}, description };
}
class ZodType {
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 == null ? void 0 : params.async) ?? !1,
contextualErrorMap: params == null ? void 0 : params.errorMap
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
}, result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
"~validate"(data) {
var _a, _b;
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) {
(_b = (_a = err == null ? void 0 : err.message) == null ? void 0 : _a.toLowerCase()) != null && _b.includes("encountered") && (this["~standard"].async = !0), ctx.common = {
issues: [],
async: !0
};
}
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 == null ? void 0 : params.errorMap,
async: !0
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
}, maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }), result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => typeof message == "string" || typeof message > "u" ? { message } : typeof message == "function" ? message(val) : message;
return this._refinement((val, ctx) => {
const result = check(val), setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
return typeof Promise < "u" && result instanceof Promise ? result.then((data) => data ? !0 : (setError(), !1)) : result ? !0 : (setError(), !1);
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => check(val) ? !0 : (ctx.addIssue(typeof refinementData == "function" ? refinementData(val, ctx) : refinementData), !1));
}
_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(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
const defaultValueFunc = typeof def == "function" ? def : () => def;
return new 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;
}
}
const cuidRegex = /^c[^\s-]{8,}$/i, cuid2Regex = /^[0-9a-z]+$/, ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i, 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, nanoidRegex = /^[a-z0-9_-]{21}$/i, jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/, 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)?)??$/, emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i, _emojiRegex = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
let emojiRegex;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, 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])$/, 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]))$/, 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])$/, base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, 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])))", dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = "[0-5]\\d";
args.precision ? secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}` : 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 = [];
return opts.push(args.local ? "Z?" : "Z"), args.offset && opts.push("([+-]\\d{2}:?\\d{2})"), regex = `${regex}(${opts.join("|")})`, new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
return !!((version === "v4" || !version) && ipv4Regex.test(ip) || (version === "v6" || !version) && ipv6Regex.test(ip));
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return !1;
try {
const [header] = jwt.split(".");
if (!header)
return !1;
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="), decoded = JSON.parse(atob(base64));
return !(typeof decoded != "object" || decoded === null || "typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT" || !decoded.alg || alg && decoded.alg !== alg);
} catch {
return !1;
}
}
function isValidCidr(ip, version) {
return !!((version === "v4" || !version) && ipv4CidrRegex.test(ip) || (version === "v6" || !version) && ipv6CidrRegex.test(ip));
}
class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce && (input.data = String(input.data)), this._getType(input) !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
}), INVALID;
}
const status = new ParseStatus();
let ctx;
for (const check of this._def.checks)
if (check.kind === "min")
input.data.length < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: !0,
exact: !1,
message: check.message
}), status.dirty());
else if (check.kind === "max")
input.data.length > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: !0,
exact: !1,
message: check.message
}), status.dirty());
else if (check.kind === "length") {
const tooBig = input.data.length > check.value, tooSmall = input.data.length < check.value;
(tooBig || tooSmall) && (ctx = this._getOrReturnCtx(input, ctx), tooBig ? addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: !0,
exact: !0,
message: check.message
}) : tooSmall && addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: !0,
exact: !0,
message: check.message
}), status.dirty());
} else if (check.kind === "email")
emailRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "emoji")
emojiRegex || (emojiRegex = new RegExp(_emojiRegex, "u")), emojiRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "uuid")
uuidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "nanoid")
nanoidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "cuid")
cuidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "cuid2")
cuid2Regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "ulid")
ulidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "url")
try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty();
}
else check.kind === "regex" ? (check.regex.lastIndex = 0, check.regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty())) : check.kind === "trim" ? input.data = input.data.trim() : check.kind === "includes" ? input.data.includes(check.value, check.position) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
}), status.dirty()) : check.kind === "toLowerCase" ? input.data = input.data.toLowerCase() : check.kind === "toUpperCase" ? input.data = input.data.toUpperCase() : check.kind === "startsWith" ? input.data.startsWith(check.value) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
}), status.dirty()) : check.kind === "endsWith" ? input.data.endsWith(check.value) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
}), status.dirty()) : check.kind === "datetime" ? datetimeRegex(check).test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
}), status.dirty()) : check.kind === "date" ? dateRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.