@compass-labs/sdk
Version:
Package structured tools for AI agents using compass API.
6,313 lines • 218 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// node_modules/@zodios/core/lib/index.mjs
import ee, { AxiosError } from "axios";
// node_modules/zod/lib/index.mjs
var util;
(function(util2) {
util2.assertEqual = (val) => val;
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((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (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;
}
return void 0;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "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 = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return __spreadValues(__spreadValues({}, first), second);
};
})(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 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 json = JSON.stringify(obj, null, 2);
return json.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(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof _ZodError)) {
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 = {};
const formErrors = [];
for (const sub of this.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 };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.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:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var overrideErrorMap = errorMap;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = __spreadProps(__spreadValues({}, issueData), {
path: fullPath
});
if (issueData.message !== void 0) {
return __spreadProps(__spreadValues({}, issueData), {
path: fullPath,
message: issueData.message
});
}
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return __spreadProps(__spreadValues({}, issueData), {
path: fullPath,
message: errorMessage
});
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const 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((x) => !!x)
});
ctx.common.issues.push(issue);
}
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 mergeObjectAsync(status, pairs) {
return __async(this, null, function* () {
const syncPairs = [];
for (const pair of pairs) {
const key = yield pair.key;
const value = yield 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;
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache;
var _ZodNativeEnum_cache;
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 (this._key instanceof Array) {
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 error = new ZodError(ctx.common.issues);
this._error = error;
return 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.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
var _a, _b;
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : 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) {
var _a;
const ctx = {
common: {
issues: [],
async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
},
path: (params === null || params === void 0 ? void 0 : 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) {
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) {
if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.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
});
}
parseAsync(data, params) {
return __async(this, null, function* () {
const result = yield this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
});
}
safeParseAsync(data, params) {
return __async(this, null, function* () {
const ctx = {
common: {
issues: [],
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
async: true
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = yield isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult);
return handleResult(ctx, result);
});
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue(__spreadValues({
code: ZodIssueCode.custom
}, getIssueProperties(val)));
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
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(__spreadProps(__spreadValues({}, processCreateParams(this._def)), {
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
}));
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault(__spreadProps(__spreadValues({}, processCreateParams(this._def)), {
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
}));
}
brand() {
return new ZodBranded(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this
}, processCreateParams(this._def)));
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch(__spreadProps(__spreadValues({}, processCreateParams(this._def)), {
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
}));
}
describe(description) {
const This = this.constructor;
return new This(__spreadProps(__spreadValues({}, 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 regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
if (args.precision) {
regex = `${regex}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
regex = `${regex}(\\.\\d+)?`;
}
return regex;
}
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, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return false;
try {
const [header] = jwt.split(".");
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null)
return false;
if (!decoded.typ || !decoded.alg)
return false;
if (alg && decoded.alg !== alg)
return false;
return true;
} catch (_a) {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
return true;
}
return false;
}
var ZodString = class _ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== 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 check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch (_a) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), __spreadValues({
validation,
code: ZodIssueCode.invalid_string
}, errorUtil.errToObj(message)));
}
_addCheck(check) {
return new _ZodString(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
email(message) {
return this._addCheck(__spreadValues({ kind: "email" }, errorUtil.errToObj(message)));
}
url(message) {
return this._addCheck(__spreadValues({ kind: "url" }, errorUtil.errToObj(message)));
}
emoji(message) {
return this._addCheck(__spreadValues({ kind: "emoji" }, errorUtil.errToObj(message)));
}
uuid(message) {
return this._addCheck(__spreadValues({ kind: "uuid" }, errorUtil.errToObj(message)));
}
nanoid(message) {
return this._addCheck(__spreadValues({ kind: "nanoid" }, errorUtil.errToObj(message)));
}
cuid(message) {
return this._addCheck(__spreadValues({ kind: "cuid" }, errorUtil.errToObj(message)));
}
cuid2(message) {
return this._addCheck(__spreadValues({ kind: "cuid2" }, errorUtil.errToObj(message)));
}
ulid(message) {
return this._addCheck(__spreadValues({ kind: "ulid" }, errorUtil.errToObj(message)));
}
base64(message) {
return this._addCheck(__spreadValues({ kind: "base64" }, errorUtil.errToObj(message)));
}
base64url(message) {
return this._addCheck(__spreadValues({
kind: "base64url"
}, errorUtil.errToObj(message)));
}
jwt(options) {
return this._addCheck(__spreadValues({ kind: "jwt" }, errorUtil.errToObj(options)));
}
ip(options) {
return this._addCheck(__spreadValues({ kind: "ip" }, errorUtil.errToObj(options)));
}
cidr(options) {
return this._addCheck(__spreadValues({ kind: "cidr" }, errorUtil.errToObj(options)));
}
datetime(options) {
var _a, _b;
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck(__spreadValues({
kind: "datetime",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false
}, errorUtil.errToObj(options === null || options === void 0 ? void 0 : 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(__spreadValues({
kind: "time",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision
}, errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)));
}
duration(message) {
return this._addCheck(__spreadValues({ kind: "duration" }, errorUtil.errToObj(message)));
}
regex(regex, message) {
return this._addCheck(__spreadValues({
kind: "regex",
regex
}, errorUtil.errToObj(message)));
}
includes(value, options) {
return this._addCheck(__spreadValues({
kind: "includes",
value,
position: options === null || options === void 0 ? void 0 : options.position
}, errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)));
}
startsWith(value, message) {
return this._addCheck(__spreadValues({
kind: "startsWith",
value
}, errorUtil.errToObj(message)));
}
endsWith(value, message) {
return this._addCheck(__spreadValues({
kind: "endsWith",
value
}, errorUtil.errToObj(message)));
}
min(minLength, message) {
return this._addCheck(__spreadValues({
kind: "min",
value: minLength
}, errorUtil.errToObj(message)));
}
max(maxLength, message) {
return this._addCheck(__spreadValues({
kind: "max",
value: maxLength
}, errorUtil.errToObj(message)));
}
length(len, message) {
return this._addCheck(__spreadValues({
kind: "length",
value: len
}, errorUtil.errToObj(message)));
}
/**
* Equivalent to `.min(1)`
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new _ZodString(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, { kind: "trim" }]
}));
}
toLowerCase() {
return new _ZodString(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, { kind: "toLowerCase" }]
}));
}
toUpperCase() {
return new _ZodString(__spreadProps(__spreadValues({}, 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) => {
var _a;
return new ZodString(__spreadValues({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : 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 = parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / Math.pow(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 parsedType = this._getType(input);
if (parsedType !== 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 check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodNumber(__spreadProps(__spreadValues({}, this._def), {
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
}));
}
_addCheck(check) {
return new _ZodNumber(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
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, 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(__spreadValues({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params === null || params === void 0 ? void 0 : 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 (_a) {
return this._getInvalidInput(input);
}
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
return this._getInvalidInput(input);
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodBigInt(__spreadProps(__spreadValues({}, this._def), {
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
}));
}
_addCheck(check) {
return new _ZodBigInt(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
var _a;
return new ZodBigInt(__spreadValues({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false
}, processCreateParams(params)));
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false
}, processCreateParams(params)));
};
var ZodDate = class _ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (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 check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new _ZodDate(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate(__spreadValues({
checks: [],
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate
}, processCreateParams(params)));
};
var ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodSymbol
}, processCreateParams(params)));
};
var ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodUndefined
}, processCreateParams(params)));
};
var ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull(__spreadValues({
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(__spreadValues({
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(__spreadValues({
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(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodNever
}, processCreateParams(params)));
};
var ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid(__spreadValues({
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(__spreadProps(__spreadValues({}, this._def), {
minLength: { value: minLength, message: errorUtil.toString(message) }
}));
}
max(maxLength, message) {
return new _ZodArray(__spreadProps(__spreadValues({}, this._def), {
maxLength: { value: maxLength, message: errorUtil.toString(message) }
}));
}
length(len, message) {
return new _ZodArray(__spreadProps(__spreadValues({}, this._def), {
exactLength: { value: len, message: errorUtil.toString(message) }
}));
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray(__spreadValues({
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(__spreadProps(__spreadValues({}, schema._def), {
shape: () => newShape
}));
} else if (schema instanceof ZodArray) {
return new ZodArray(__spreadProps(__spreadValues({}, 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);
return this._cached = { shape, keys };
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== 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(this, null, function* () {
const syncPairs = [];
for (const pair of pairs) {
const key = yield pair.key;
const value = yield pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
})).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new _ZodObject(__spreadValues(__spreadProps(__spreadValues({}, this._def), {
unknownKeys: "strict"
}), message !== void 0 ? {
errorMap: (issue, ctx) => {
var _a, _b, _c, _d;
const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
};
return {
message: defaultError
};
}
} : {}));
}
strip() {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
unknownKeys: "strip"
}));
}
passthrough() {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
unknownKeys: "passthrough"
}));
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => __spreadValues(__spreadValues({}, 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: () => __spreadValues(__spreadValues({}, this._def.shape()), merging._def.shape()),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
catchall: index
}));
}
pick(mask) {
const shape = {};
util.objectKeys(mask).forEach((key) => {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
});
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => shape
}));
}
omit(mask) {
const shape = {};
util.objectKeys(this.shape).forEach((key) => {
if (!mask[key]) {
shape[key] = this.shape[key];
}
});
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => shape
}));
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
});
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => newShape
}));
}
required(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
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(__spreadProps(__spreadValues({}, this._def), {
shape: () => newShape
}));
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject(__spreadValues({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject
}, processCreateParams(params)));
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject(__spreadValues({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject
}, processCreateParams(params)));
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject(__spreadValues({
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((option) => __async(this, null, function* () {
const childCtx = __spreadProps(__spreadValues({}, ctx), {
common: __spreadProps(__spreadValues({}, ctx.common), {
issues: []
}),
parent: null
});
return {
result: yield 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 = __spreadProps(__spreadValues({}, ctx), {
common: __spreadProps(__spreadValues({}, 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(__spreadValues({
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(__spreadValues({
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 = __spreadValues(__spreadValues({}, 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(__spreadValues({
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(__spreadProps(__spreadValues({}, this._def), {
rest
}));
}
};
ZodTuple.create = (schemas2, params) => {
if (!Array.isArray(schemas2)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple(__spreadValues({
items: schemas2,
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(__spreadValues({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord
}, processCreateParams(third)));
}
return new _ZodRecord(__spreadValues({
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(this, null, function* () {
for (const pair of pairs) {
const key = yield pair.key;
const value = yield 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(__spreadValues({
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(__spreadProps(__spreadValues({}, this._def), {
minSize: { value: minSize, message: errorUtil.toString(message) }
}));
}
max(maxSize, message) {
return new _ZodSet(__spreadProps(__spreadValues({}, 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(__spreadValues({
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, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(function(...args) {
return __async(this, null, function* () {
const error = new ZodError([]);
const parsedArgs = yield me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = yield Reflect.apply(fn, this, parsedArgs);
const parsedReturns = yield me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
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(__spreadProps(__spreadValues({}, this._def), {
args: ZodTuple.create(items).rest(ZodUnknown.create())
}));
}
returns(returnType) {
return new _ZodFunction(__spreadProps(__spreadValues({}, 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(__spreadValues({
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 lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy(__spreadValues({
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(__spreadValues({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral
}, processCreateParams(params)));
};
function createZodEnum(values, params) {
return new ZodEnum(__spreadValues({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum
}, processCreateParams(params)));
}
var ZodEnum = class _ZodEnum extends ZodType {
constructor() {
super(...arguments);
_ZodEnum_cache.set(this, void 0);
}
_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 (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
}
if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").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, __spreadValues(__spreadValues({}, this._def), newDef));
}
exclude(values, newDef = this._def) {
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), __spreadValues(__spreadValues({}, this._def), newDef));
}
};
_ZodEnum_cache = /* @__PURE__ */ new WeakMap();
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
constructor() {
super(...arguments);
_ZodNativeEnum_cache.set(this, void 0);
}
_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 (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
}
if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").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_cache = /* @__PURE__ */ new WeakMap();
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum(__spreadValues({
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(__spreadValues({
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((processed2) => __async(this, null, function* () {
if (status.value === "aborted")
return INVALID;
const result = yield 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 base;
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 base;
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(__spreadValues({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect
}, processCreateParams(params)));
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects(__spreadValues({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects
}, processCreateParams(params)));
};
var ZodOptional = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(void 0);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional
}, processCreateParams(params)));
};
var ZodNullable = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable(__spreadValues({
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(__spreadValues({
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 = __spreadProps(__spreadValues({}, ctx), {
common: __spreadProps(__spreadValues({}, ctx.common), {
issues: []
})
});
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: __spreadValues({}, 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(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch
}, processCreateParams(params)));
};
var ZodNaN = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => {
return new ZodNaN(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodNaN
}, processCreateParams(params)));
};
var BRAND = 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(this, null, function* () {
const inResult = yield 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(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly
}, processCreateParams(params)));
};
function custom(check, params = {}, fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
var _a, _b;
if (!check(data)) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
const p2 = typeof p === "string" ? { message: p } : p;
ctx.addIssue(__spreadProps(__spreadValues({ code: "custom" }, p2), { fatal: _fatal }));
}
});
return ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["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(__spreadProps(__spreadValues({}, arg), { coerce: true })),
number: (arg) => ZodNumber.create(__spreadProps(__spreadValues({}, arg), { coerce: true })),
boolean: (arg) => ZodBoolean.create(__spreadProps(__spreadValues({}, arg), {
coerce: true
})),
bigint: (arg) => ZodBigInt.create(__spreadProps(__spreadValues({}, arg), { coerce: true })),
date: (arg) => ZodDate.create(__spreadProps(__spreadValues({}, arg), { coerce: true }))
};
var NEVER = INVALID;
var z = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap,
getErrorMap,
makeIssue,
EMPTY_PATH,
addIssueToContext,
ParseStatus,
INVALID,
DIRTY,
OK,
isAborted,
isDirty,
isValid,
isAsync,
get util() {
return util;
},
get objectUtil() {
return objectUtil;
},
ZodParsedType,
getParsedType,
ZodType,
datetimeRegex,
ZodString,
ZodNumber,
ZodBigInt,
ZodBoolean,
ZodDate,
ZodSymbol,
ZodUndefined,
ZodNull,
ZodAny,
ZodUnknown,
ZodNever,
ZodVoid,
ZodArray,
ZodObject,
ZodUnion,
ZodDiscriminatedUnion,
ZodIntersection,
ZodTuple,
ZodRecord,
ZodMap,
ZodSet,
ZodFunction,
ZodLazy,
ZodLiteral,
ZodEnum,
ZodNativeEnum,
ZodPromise,
ZodEffects,
ZodTransformer: ZodEffects,
ZodOptional,
ZodNullable,
ZodDefault,
ZodCatch,
ZodNaN,
BRAND,
ZodBranded,
ZodPipeline,
ZodReadonly,
custom,
Schema: ZodType,
ZodSchema: ZodType,
late,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind;
},
coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
"enum": enumType,
"function": functionType,
"instanceof": instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
"null": nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean,
onumber,
optional: optionalType,
ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
"undefined": undefinedType,
union: unionType,
unknown: unknownType,
"void": voidType,
NEVER,
ZodIssueCode,
quotelessJson,
ZodError
});
// node_modules/@zodios/core/lib/index.mjs
function D(o, e) {
let t = __spreadValues({}, o);
for (let i of e) delete t[i];
return t;
}
var M = /:([a-zA-Z_][a-zA-Z0-9_]*)/g;
function $(o) {
let e = o.url, t = o.params;
return t && (e = e.replace(M, (i, n) => n in t ? `${t[n]}` : i)), e;
}
function P(o, e, t) {
return o.find((i) => i.method === e && i.path === t);
}
function C(o) {
let e = new FormData();
for (let t in o) e.append(t, o[t]);
return { data: e };
}
var u = class extends Error {
constructor(t, i, n, s) {
super(t);
this.config = i;
this.data = n;
this.cause = s;
}
};
var H = { name: "form-data", request: (o, e) => __async(void 0, null, function* () {
if (typeof e.data != "object" || Array.isArray(e.data)) throw new u("Zodios: multipart/form-data body must be an object", e);
let t = C(e.data);
return __spreadProps(__spreadValues({}, e), { data: t.data, headers: __spreadValues(__spreadValues({}, e.headers), t.headers) });
}) };
function R() {
return H;
}
var F = { name: "form-url", request: (o, e) => __async(void 0, null, function* () {
if (typeof e.data != "object" || Array.isArray(e.data)) throw new u("Zodios: application/x-www-form-urlencoded body must be an object", e);
return __spreadProps(__spreadValues({}, e), { data: new URLSearchParams(e.data).toString(), headers: __spreadProps(__spreadValues({}, e.headers), { "Content-Type": "application/x-www-form-urlencoded" }) });
}) };
function T() {
return F;
}
function Z(o, e) {
return { request: (t, i) => __async(this, null, function* () {
return __spreadProps(__spreadValues({}, i), { headers: __spreadProps(__spreadValues({}, i.headers), { [o]: e }) });
}) };
}
function S(o) {
return [true, "response", "all"].includes(o);
}
function I(o) {
return [true, "request", "all"].includes(o);
}
function w({ validate: o, transform: e, sendDefaults: t }) {
return { name: "zod-validation", request: I(o) ? (i, n) => __async(this, null, function* () {
let s = P(i, n.method, n.url);
if (!s) throw new Error(`No endpoint found for ${n.method} ${n.url}`);
let { parameters: d } = s;
if (!d) return n;
let p = __spreadProps(__spreadValues({}, n), { queries: __spreadValues({}, n.queries), headers: __spreadValues({}, n.headers), params: __spreadValues({}, n.params) }), f = { Query: (r) => {
var a;
return (a = p.queries) == null ? void 0 : a[r];
}, Body: (r) => p.data, Header: (r) => {
var a;
return (a = p.headers) == null ? void 0 : a[r];
}, Path: (r) => {
var a;
return (a = p.params) == null ? void 0 : a[r];
} }, c = { Query: (r, a) => p.queries[r] = a, Body: (r, a) => p.data = a, Header: (r, a) => p.headers[r] = a, Path: (r, a) => p.params[r] = a }, m = I(e);
for (let r of d) {
let { name: a, schema: j, type: x } = r, A = f[x](a);
if (t || A !== void 0) {
let E = yield j.safeParseAsync(A);
if (!E.success) throw new u(`Zodios: Invalid ${x} parameter '${a}'`, n, A, E.error);
m && c[x](a, E.data);
}
}
return p;
}) : void 0, response: S(o) ? (i, n, s) => __async(this, null, function* () {
var p, f, c, m;
let d = P(i, n.method, n.url);
if (!d) throw new Error(`No endpoint found for ${n.method} ${n.url}`);
if (((f = (p = s.headers) == null ? void 0 : p["content-type"]) == null ? void 0 : f.includes("application/json")) || ((m = (c = s.headers) == null ? void 0 : c["content-type"]) == null ? void 0 : m.includes("application/vnd.api+json"))) {
let r = yield d.response.safeParseAsync(s.data);
if (!r.success) throw new u(`Zodios: Invalid response from endpoint '${d.method} ${d.path}'
status: ${s.status} ${s.statusText}
cause:
${r.error.message}
received:
${JSON.stringify(s.data, null, 2)}`, n, s.data, r.error);
S(e) && (s.data = r.data);
}
return s;
}) : void 0 };
}
var y = class {
constructor(e, t) {
this.plugins = [];
this.key = `${e}-${t}`;
}
indexOf(e) {
return this.plugins.findIndex((t) => (t == null ? void 0 : t.name) === e);
}
use(e) {
if (e.name) {
let t = this.indexOf(e.name);
if (t !== -1) return this.plugins[t] = e, { key: this.key, value: t };
}
return this.plugins.push(e), { key: this.key, value: this.plugins.length - 1 };
}
eject(e) {
if (typeof e == "string") {
let t = this.indexOf(e);
if (t === -1) throw new Error(`Plugin with name '${e}' not found`);
this.plugins[t] = void 0;
} else {
if (e.key !== this.key) throw new Error(`Plugin with key '${e.key}' is not registered for endpoint '${this.key}'`);
this.plugins[e.value] = void 0;
}
}
interceptRequest(e, t) {
return __async(this, null, function* () {
let i = t;
for (let n of this.plugins) n != null && n.request && (i = yield n.request(e, i));
return i;
});
}
interceptResponse(e, t, i) {
return __async(this, null, function* () {
let n = i;
for (let s = this.plugins.length - 1; s >= 0; s--) {
let d = this.plugins[s];
d && (n = n.then(d != null && d.response ? (p) => d.response(e, t, p) : void 0, d != null && d.error ? (p) => d.error(e, t, p) : void 0));
}
return n;
});
}
count() {
return this.plugins.reduce((e, t) => t ? e + 1 : e, 0);
}
};
function l(o) {
let e = /* @__PURE__ */ new Set();
for (let i of o) {
let n = `${i.method} ${i.path}`;
if (e.has(n)) throw new Error(`Zodios: Duplicate path '${n}'`);
e.add(n);
}
let t = /* @__PURE__ */ new Set();
for (let i of o) if (i.alias) {
if (t.has(i.alias)) throw new Error(`Zodios: Duplicate alias '${i.alias}'`);
t.add(i.alias);
}
for (let i of o) if (i.parameters && i.parameters.filter((s) => s.type === "Body").length > 1) throw new Error(`Zodios: Multiple body parameters in endpoint '${i.path}'`);
}
function z2(o) {
return l(o), o;
}
var B = class {
constructor(e, t, i) {
this.endpointPlugins = /* @__PURE__ */ new Map();
let n;
if (!e) throw Array.isArray(t) ? new Error("Zodios: missing base url") : new Error("Zodios: missing api description");
let s;
if (typeof e == "string" && Array.isArray(t)) s = e, this.api = t, n = i || {};
else if (Array.isArray(e) && !Array.isArray(t)) this.api = e, n = t || {};
else throw new Error("Zodios: api must be an array");
l(this.api), this.options = __spreadValues({ validate: true, transform: true, sendDefaults: false }, n), this.options.axiosInstance ? this.axiosInstance = this.options.axiosInstance : this.axiosInstance = ee.create(__spreadValues({}, this.options.axiosConfig)), s && (this.axiosInstance.defaults.baseURL = s), this.injectAliasEndpoints(), this.initPlugins(), [true, "all", "request", "response"].includes(this.options.validate) && this.use(w(this.options));
}
initPlugins() {
this.endpointPlugins.set("any-any", new y("any", "any")), this.api.forEach((e) => {
let t = new y(e.method, e.path);
switch (e.requestFormat) {
case "binary":
t.use(Z("Content-Type", "application/octet-stream"));
break;
case "form-data":
t.use(R());
break;
case "form-url":
t.use(T());
break;
case "text":
t.use(Z("Content-Type", "text/plain"));
break;
}
this.endpointPlugins.set(`${e.method}-${e.path}`, t);
});
}
getAnyEndpointPlugins() {
return this.endpointPlugins.get("any-any");
}
findAliasEndpointPlugins(e) {
let t = this.api.find((i) => i.alias === e);
if (t) return this.endpointPlugins.get(`${t.method}-${t.path}`);
}
findEnpointPlugins(e, t) {
return this.endpointPlugins.get(`${e}-${t}`);
}
get baseURL() {
return this.axiosInstance.defaults.baseURL;
}
get axios() {
return this.axiosInstance;
}
use(...e) {
if (typeof e[0] == "object") return this.getAnyEndpointPlugins().use(e[0]);
if (typeof e[0] == "string" && typeof e[1] == "object") {
let t = this.findAliasEndpointPlugins(e[0]);
if (!t) throw new Error(`Zodios: no alias '${e[0]}' found to register plugin`);
return t.use(e[1]);
} else if (typeof e[0] == "string" && typeof e[1] == "string" && typeof e[2] == "object") {
let t = this.findEnpointPlugins(e[0], e[1]);
if (!t) throw new Error(`Zodios: no endpoint '${e[0]} ${e[1]}' found to register plugin`);
return t.use(e[2]);
}
throw new Error("Zodios: invalid plugin registration");
}
eject(e) {
var t;
if (typeof e == "string") {
this.getAnyEndpointPlugins().eject(e);
return;
}
(t = this.endpointPlugins.get(e.key)) == null || t.eject(e);
}
injectAliasEndpoints() {
this.api.forEach((e) => {
e.alias && (["post", "put", "patch", "delete"].includes(e.method) ? this[e.alias] = (t, i) => this.request(__spreadProps(__spreadValues({}, i), { method: e.method, url: e.path, data: t })) : this[e.alias] = (t) => this.request(__spreadProps(__spreadValues({}, t), { method: e.method, url: e.path })));
});
}
request(e) {
return __async(this, null, function* () {
let t = e, i = this.getAnyEndpointPlugins(), n = this.findEnpointPlugins(t.method, t.url);
t = yield i.interceptRequest(this.api, t), n && (t = yield n.interceptRequest(this.api, t));
let s = this.axiosInstance.request(__spreadProps(__spreadValues({}, D(t, ["params", "queries"])), { url: $(t), params: t.queries }));
return n && (s = n.interceptResponse(this.api, t, s)), s = i.interceptResponse(this.api, t, s), (yield s).data;
});
}
get(_0) {
return __async(this, arguments, function* (e, ...[t]) {
return this.request(__spreadProps(__spreadValues({}, t), { method: "get", url: e }));
});
}
post(_0, _1) {
return __async(this, arguments, function* (e, t, ...[i]) {
return this.request(__spreadProps(__spreadValues({}, i), { method: "post", url: e, data: t }));
});
}
put(_0, _1) {
return __async(this, arguments, function* (e, t, ...[i]) {
return this.request(__spreadProps(__spreadValues({}, i), { method: "put", url: e, data: t }));
});
}
patch(_0, _1) {
return __async(this, arguments, function* (e, t, ...[i]) {
return this.request(__spreadProps(__spreadValues({}, i), { method: "patch", url: e, data: t }));
});
}
delete(_0, _1) {
return __async(this, arguments, function* (e, t, ...[i]) {
return this.request(__spreadProps(__spreadValues({}, i), { method: "delete", url: e, data: t }));
});
}
};
var te = B;
// src/client.ts
var Chain = z.enum(["base:mainnet", "ethereum:mainnet", "arbitrum:mainnet"]);
var Token = z.enum([
"1INCH",
"AAVE",
"BAL",
"cbBTC",
"cbETH",
"CRV",
"crvUSD",
"DAI",
"ENS",
"ETHx",
"FRAX",
"FXS",
"GHO",
"KNC",
"LDO",
"LINK",
"LUSD",
"MKR",
"osETH",
"PYUSD",
"rETH",
"RPL",
"rsETH",
"sDAI",
"SNX",
"STG",
"sUSDe",
"tBTC",
"UNI",
"USDC",
"USDe",
"USDS",
"USDT",
"WBTC",
"weETH",
"WETH",
"wstETH",
"ARB",
"EURS",
"MAI",
"USDCe",
"AERO",
"EUR",
"VIRTUAL"
]);
var AaveSupplyRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
asset: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
amount: z.union([z.number(), z.string()]).describe("The amount of the asset to supply"),
on_behalf_of: z.union([z.string(), z.null()]).describe(
"The address on behalf of whom the supply is made. Defaults to the transaction sender."
).optional()
}).passthrough();
var UnsignedTransaction = z.object({
chainId: z.number().int().describe("The chain id of the transaction"),
data: z.string().describe("The data of the transaction"),
from: z.string().describe("The sender of the transaction"),
gas: z.number().int().describe("The gas of the transaction"),
to: z.string().describe("The recipient of the transaction"),
value: z.number().int().describe("The value of the transaction"),
nonce: z.number().int().describe("The nonce of the address"),
maxFeePerGas: z.number().int().describe("The max fee per gas of the transaction"),
maxPriorityFeePerGas: z.number().int().describe("The max priority fee per gas of the transaction")
}).passthrough();
var ValidationError = z.object({
loc: z.array(z.union([z.string(), z.number()])),
msg: z.string(),
type: z.string()
}).passthrough();
var HTTPValidationError = z.object({ detail: z.array(ValidationError) }).partial().passthrough();
var InterestRateMode = z.union([z.literal(1), z.literal(2)]);
var AaveBorrowRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
asset: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
amount: z.union([z.number(), z.string()]).describe("The amount of the asset to borrow"),
interest_rate_mode: InterestRateMode.describe(`On AAVE there are 2 different interest modes.
A stable (but typically higher rate), or a variable rate.`),
on_behalf_of: z.union([z.string(), z.null()]).describe("The address on behalf of whom the supply is made").optional()
}).passthrough();
var AaveRepayRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
asset: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
amount: z.union([z.number(), z.string()]).describe("The amount of the asset to repay"),
interest_rate_mode: InterestRateMode.describe(`On AAVE there are 2 different interest modes.
A stable (but typically higher rate), or a variable rate.`),
on_behalf_of: z.union([z.string(), z.null()]).describe("The address on behalf of whom the supply is made").optional()
}).passthrough();
var AaveWithdrawRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
asset: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
amount: z.union([z.number(), z.string()]).describe("The amount of the asset to withdraw"),
recipient: z.string().describe("The address of the recipient of the withdrawn funds.")
}).passthrough();
var AaveGetAssetPriceRequest = z.object({
chain: Chain.describe("The chain to use."),
asset: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`)
}).passthrough();
var AaveAssetPriceResponse = z.object({ price: z.string().describe("The price of the asset in USD.") }).passthrough();
var AaveGetLiquidityChangeRequest = z.object({
chain: Chain.describe("The chain to use."),
start_block: z.number().int().describe("The starting block."),
end_block: z.union([z.number(), z.null()]).describe("The ending block. If nothing provided defaults to latest").optional(),
asset: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`)
}).passthrough();
var AaveLiquidityChangeResponse = z.object({
liquidity_change: z.string().describe(
"The change in the liqudiity index between the two times, expressed as a percentage."
),
start_time: z.string().datetime({ offset: true }).describe("Dateime of starting block"),
end_time: z.string().datetime({ offset: true }).describe("Dateime of ending block")
}).passthrough();
var AaveGetUserPositionSummaryRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The user to get the position summary of. Values are in USD.")
}).passthrough();
var AaveUserPositionSummaryResponse = z.object({
maximum_loan_to_value_ratio: z.string().describe("The loan to value ratio of a user."),
health_factor: z.string().describe(`The health factor of a user. If this is above 1 it is safe; below 1 and the
user is in risk of liquidation. This number might be very high (which would mean the user is
safe!)`),
total_collateral: z.string().describe("The total collateral (in USD) of a user."),
total_debt: z.string().describe("The total debt (in USD) of a user."),
available_borrows: z.string().describe("The available borrows (in USD) of a user."),
liquidation_threshold: z.string().describe(`The liquidation threshold of a user. A user might exceed this due to changing
asset values.`)
}).passthrough();
var AaveGetUserPositionPerTokenRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The user to fetch the token-specific position of."),
asset: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`)
}).passthrough();
var AaveUserPositionPerTokenResponse = z.object({
token_balance: z.string().describe(
"The balance of AAVE aTokens (interest-bearing representations of your deposits)."
),
stable_debt: z.string().describe("The amount of the user's debt with a fixed interest rate."),
variable_debt: z.string().describe("The amount of the user's debt with a variable interest rate."),
principal_stable_debt: z.string().describe(`The amount of the user's debt that was part of the initial principal of all
loans with a stable interest rate.`),
principal_variable_debt: z.string().describe(`The amount of the user's debt that was part of the initial principal of all
loans with a variable interest rate. This is the value stored by AAVE, which may be slightly
inaccurate, but reflects what AAVE believes you initially paid.`),
stable_borrow_rate: z.string().describe(`The current average annualised interest rate for all your stable loans in
this pool.`),
stable_borrow_rate_for_new_loans: z.string().describe("The annualised interest rate you would pay on a new stable loan."),
variable_borrow_rate: z.string().describe(`The current annualised interest rate for variable rate loans in this pool.
(This applies to both current and new loans.)`),
liquidity_rate: z.string().describe("The annualised interest rate for deposited supplies.")
}).passthrough();
var AerodromeAddLiquidityRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_a: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_b: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
stable: z.boolean().describe(
"If true, try to provide liquidity on a stable pool with a bonding curve of K=x^3y+y^3x. If false, try to provide liquidity on a volatile pool with a bonding curve of K=xy"
),
amount_a_desired: z.union([z.number(), z.string()]).describe("The amount of token A you want to provide"),
amount_b_desired: z.union([z.number(), z.string()]).describe("The amount of token B you want to provide"),
amount_a_min: z.union([z.number(), z.string()]).describe("The minimal amount of token A you are willing to provide"),
amount_b_min: z.union([z.number(), z.string()]).describe("The minimal amount of token B you are willing to provide"),
to: z.union([z.string(), z.null()]).describe("The receiver of the LP tokens from this trade, default to sender").optional(),
deadline: z.union([z.number(), z.null()]).describe("The deadline for this transaction in seconds since epoch")
}).passthrough();
var AerodromeAddLiquidityEthRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
stable: z.boolean().describe(
"If true, try to provide liquidity on a stable pool with a bonding curve of K=x^3y+y^3x. If false, try to provide liquidity on a volatile pool with a bonding curve of K=xy"
),
amount_token_desired: z.union([z.number(), z.string()]).describe("The amount of token you want to provide"),
amount_eth_desired: z.union([z.number(), z.string()]).describe("The amount of WETH you want to provide"),
amount_token_min: z.union([z.number(), z.string()]).describe("The minimal amount of token you are willing to provide"),
amount_eth_min: z.union([z.number(), z.string()]).describe("The minimal amount of WETH you are willing to provide"),
to: z.union([z.string(), z.null()]).describe("The receiver of the LP tokens from this trade, default to sender").optional(),
deadline: z.union([z.number(), z.null()]).describe("The deadline for this transaction in seconds since epoch")
}).passthrough();
var AerodromeRemoveLiquidityRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_a: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_b: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
stable: z.boolean().describe(
"If true, try to remove liquidity from a stable pool with a bonding curve of K=x^3y+y^3x. If false, try to remove liquidity from a volatile pool with a bonding curve of K=xy"
),
liquidity: z.union([z.number(), z.string()]).describe("The amount of liquidity you want to remove"),
amount_a_min: z.union([z.number(), z.string()]).describe("The minimal amount of token A you are willing to receive"),
amount_b_min: z.union([z.number(), z.string()]).describe("The minimal amount of token B you are willing to receive"),
to: z.union([z.string(), z.null()]).describe("The receiver of the tokens from this liquidity removal, default to sender").optional(),
deadline: z.union([z.number(), z.null()]).describe("The deadline for this transaction in seconds since epoch")
}).passthrough();
var AerodromeRemoveLiquidityEthRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
stable: z.boolean().describe(
"If true, try to remove liquidity from a stable pool with a bonding curve of K=x^3y+y^3x. If false, try to remove liquidity from a volatile pool with a bonding curve of K=xy"
),
liquidity: z.union([z.number(), z.string()]).describe("The amount of liquidity you want to remove"),
amount_token_min: z.union([z.number(), z.string()]).describe("The minimal amount of token you are willing to receive"),
amount_eth_min: z.union([z.number(), z.string()]).describe("The minimal amount of WETH you are willing to receive"),
to: z.union([z.string(), z.null()]).describe("The receiver of the tokens from this liquidity removal, default to sender").optional(),
deadline: z.union([z.number(), z.null()]).describe("The deadline for this transaction in seconds since epoch")
}).passthrough();
var AerodromeSwapTokensRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
amount_in: z.union([z.number(), z.string()]).describe("The amount of tokens you will give to aerodrome_basic for this trade"),
amount_out_min: z.union([z.number(), z.string()]).describe(`The minimal amount of token you are willing to receive (will revert if the
swap gives you less)`),
stable: z.boolean().describe(`If true, try to trade on a stable pool with a bonding curve of K=x^3y+y^3x.
If false, try to trade on a volatile pool with a bonding curve of K=xy`),
to: z.union([z.string(), z.null()]).describe("The receiver of the funds from this trade, default to sender").optional()
}).passthrough();
var AerodromeSwapEthForTokenRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
amount_in: z.union([z.number(), z.string()]).describe("The amount of ETH you will give to aerodrome_basic for this trade"),
amount_out_min: z.union([z.number(), z.string()]).describe(
"The minimal amount of token you are willing to receive (will revert if the swap gives you less)"
),
stable: z.boolean().describe(
"If true, try to trade on a stable pool with a bonding curve of K=x^3y+y^3x. If false, try to trade on a volatile pool with a bonding curve of K=xy"
),
to: z.union([z.string(), z.null()]).describe("The receiver of the funds from this trade, default to sender").optional()
}).passthrough();
var AerodromeSwapTokenForEthRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
amount_in: z.union([z.number(), z.string()]).describe("The amount of tokens you will give to aerodrome_basic for this trade"),
amount_out_min: z.union([z.number(), z.string()]).describe(
"The minimal amount of ETH you are willing to receive (will revert if the swap gives you less)"
),
stable: z.boolean().describe(
"If true, try to trade on a stable pool with a bonding curve of K=x^3y+y^3x. If false, try to trade on a volatile pool with a bonding curve of K=xy"
),
to: z.union([z.string(), z.null()]).describe("The receiver of the funds from this trade, default to sender").optional()
}).passthrough();
var AerodromeSlipstreamSellExactlyRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
tick_spacing: z.number().int().gte(1).describe("The tick spacing of the pool"),
amount_in: z.union([z.number(), z.string()]).describe("The amount of the token to swap from"),
amount_out_minimum: z.union([z.number(), z.string()]).describe("The minimum amount of the token to swap to, defaults to 0").optional().default("0")
}).passthrough();
var AerodromeSlipstreamBuyExactlyRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
tick_spacing: z.number().int().gte(1).describe("The tick spacing of the pool"),
amount_out: z.union([z.number(), z.string()]).describe("The amount of the token to swap to"),
amount_in_maximum: z.union([z.number(), z.string()]).describe("The maximum amount of the token to swap from")
}).passthrough();
var AerodromeSlipstreamMintLiquidityProvisionRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token0: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token1: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
tick_spacing: z.number().int().gte(1).describe("The tick spacing of the pool"),
tick_lower: z.number().int().describe("The lower tick of the range to mint the position in"),
tick_upper: z.number().int().describe("The upper tick of the range to mint the position in"),
amount0_desired: z.union([z.number(), z.string()]).describe("The desired amount of the first token to deposit"),
amount1_desired: z.union([z.number(), z.string()]).describe("The desired amount of the second token to deposit"),
amount0_min: z.union([z.number(), z.string()]).describe("The minimum amount of the first token to deposit"),
amount1_min: z.union([z.number(), z.string()]).describe("The minimum amount of the second token to deposit"),
recipient: z.union([z.string(), z.null()]).describe("The address that will receive the LP tokens").optional()
}).passthrough();
var AerodromeSlipstreamIncreaseLiquidityProvisionRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_id: z.number().int().describe("Token ID of the NFT representing the liquidity provisioned position."),
amount0_desired: z.union([z.number(), z.string()]).describe("The desired amount of the first token to deposit"),
amount1_desired: z.union([z.number(), z.string()]).describe("The desired amount of the second token to deposit"),
amount0_min: z.union([z.number(), z.string()]).describe("The minimum amount of the first token to deposit"),
amount1_min: z.union([z.number(), z.string()]).describe("The minimum amount of the second token to deposit")
}).passthrough();
var AerodromeSlipstreamWithdrawLiquidityProvisionRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_id: z.number().int().describe("Token ID of the NFT representing the liquidity provisioned position."),
percentage_for_withdrawal: z.union([z.number(), z.string()]).describe("How much liquidity to take out in percentage.")
}).passthrough();
var AerodromeSlipstreamGetLiquidityProvisionPositionsRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The address of the user to check the balance of")
}).passthrough();
var AerodromePosition = z.object({
nonce: z.number().int(),
operator: z.string(),
token0: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token1: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
tick_spacing: z.number().int(),
tick_lower: z.number().int(),
tick_upper: z.number().int(),
liquidity: z.number().int(),
fee_growth_inside0_last_x128: z.number().int(),
fee_growth_inside1_last_x128: z.number().int(),
tokens_owed0: z.number().int(),
tokens_owed1: z.number().int(),
token_id: z.number().int()
}).passthrough();
var AerodromeLPPositionsResponse = z.object({
positions: z.record(AerodromePosition).describe(`Liquidity provision positions belonging to a particular user. The key is a
tuple of the token0, token1, tick_spacing, tick_lower, and tick_upper of the position.`)
}).passthrough();
var AerodromeSlipstreamGetPoolPriceRequest = z.object({
chain: Chain.describe("The chain to use."),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
tick_spacing: z.number().int().gte(1).describe("The tick spacing of the pool")
}).passthrough();
var AerodromeSlipstreamPoolPriceResponse = z.object({
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
price: z.string().describe(`The price of the pool. This is expressed as an instantaneous amount of how
many token0 you need to buy 1 token1. In any swap this will not change during the trade; use
the quote endpoint to get a better idea of how much you will pay!`),
tick: z.number().int().describe(`The current tick in the pool. This is a number that represents the price of
the pool according to the aerodrome_slipstream v3 concentrated liquidity concept.`)
}).passthrough();
var PortfolioRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The address of the user.")
}).passthrough();
var TokenBalance = z.object({
amount: z.string().describe("Amount of tokens a particular address holds"),
decimals: z.number().int().describe("Number of decimals of the token"),
token_symbol: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_address: z.string().describe("Address of the token"),
price: z.string().describe("Price of the token in USD"),
token_value_in_usd: z.string().describe("Value of the token balance in USD")
}).passthrough();
var Portfolio = z.object({
total_value_in_usd: z.string().describe("Total value of the portfolio in USD"),
token_balances: z.array(TokenBalance).describe("List of token balances in the portfolio")
}).passthrough();
var VisualizePortfolioRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The address of the user.")
}).passthrough();
var Image = z.object({ image: z.string().describe("Base64 encoded SVG image") }).passthrough();
var PriceRequest = z.object({
chain: Chain.describe("The chain to use."),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`)
}).passthrough();
var PriceResponse = z.object({
token_price_in_usd: z.string().describe("Price of the token in USD")
}).passthrough();
var TokensRequest = z.object({ chain: Chain.describe("The chain to use.") }).passthrough();
var TokenInfo = z.object({
tokens: z.array(Token).describe("List of supported tokens for a given chain")
}).passthrough();
var GetErc20BalanceRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The user to get the ERC20 balance of."),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`)
}).passthrough();
var BalanceInfoResponse = z.object({
amount: z.string().describe("Amount of tokens a particular address holds"),
decimals: z.number().int().describe("Number of decimals of the token"),
token_symbol: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_address: z.string().describe("Address of the token")
}).passthrough();
var ContractName = z.enum([
"AaveV3Pool",
"AaveV3Oracle",
"AaveV3ProtocolDataProvider",
"AerodromeBasicFactory",
"AerodromeSlipstreamFactory",
"AerodromeBasicRouter",
"AerodromeSlipstreamRouter",
"AerodromeBasicPool",
"AerodromeSlipstreamNonfungiblePositionManager",
"UniswapV3Router",
"UniswapV3Factory",
"UniswapV3NFTPositionManager",
"UniswapV3Quoter",
"ChainlinkEACAggregatorProxy"
]);
var GetErc20AllowanceRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The user to get the ERC20 allowance of."),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
contract_name: ContractName.describe(`Select the protocol.
E.g. for increasing ERC-20 allowance.`)
}).passthrough();
var AllowanceInfoResponse = z.object({
amount: z.string().describe("Amount of tokens allowed to be spent by spender"),
decimals: z.number().int().describe("Number of decimals of the token"),
token_symbol: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_address: z.string().describe("Address of the token"),
contract_address: z.string().describe("Address of the contract")
}).passthrough();
var GetEnsDetailsRequest = z.object({
chain: Chain.describe("The chain to use."),
ens_name: z.string().describe("The ENS address of the user.")
}).passthrough();
var EnsNameInfoResponse = z.object({
wallet_address: z.string().describe("The wallet address of the user"),
registrant: z.string().describe("The registrant of the ENS")
}).passthrough();
var WrapEthRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
amount: z.union([z.number(), z.string()]).describe("The amount of ETH to wrap.")
}).passthrough();
var UnwrapWethRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
amount: z.union([z.number(), z.string()]).describe("The amount of WETH to unwrap.")
}).passthrough();
var TransferERC20Request = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
amount: z.union([z.number(), z.string()]).describe("Amount of token to transfer"),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
to: z.string().describe("The recipient of the tokens.")
}).passthrough();
var TransferEthRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
amount: z.union([z.number(), z.string()]).describe("Amount of ETH to transfer"),
to: z.string().describe("The recipient of the ETH.")
}).passthrough();
var IncreaseAllowanceRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
contract_name: ContractName.describe(`Select the protocol.
E.g. for increasing ERC-20 allowance.`),
amount: z.union([z.number(), z.string()]).describe("The amount of tokens to increase the allowance by.")
}).passthrough();
var IncreaseAllowanceAnyRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_address: z.string().describe("The address of the ERC20 token for which the allowance is increased."),
contract_name: ContractName.describe(`Select the protocol.
E.g. for increasing ERC-20 allowance.`),
amount: z.union([z.number(), z.string()]).describe("The amount of tokens to increase the allowance by.")
}).passthrough();
var FeeEnum = z.enum(["0.01", "0.05", "0.3", "1.0"]);
var UniswapBuyExactlyRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
fee: FeeEnum.describe(`The transaction fee of a Uniswap pool in bips.
Uniswap supports 4 different fee levels.`),
amount_out: z.union([z.number(), z.string()]).describe("The amount of the token to swap to"),
amount_in_maximum: z.union([z.number(), z.string()]).describe("The maximum amount of the token to swap from"),
wrap_eth: z.boolean().describe("Whether to wrap ETH to WETH, only use when swapping WETH into something").optional().default(false)
}).passthrough();
var UniswapSellExactlyRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
fee: FeeEnum.describe(`The transaction fee of a Uniswap pool in bips.
Uniswap supports 4 different fee levels.`),
amount_in: z.union([z.number(), z.string()]).describe("The amount of the token to swap from"),
amount_out_minimum: z.union([z.number(), z.string()]).describe("The minimum amount of the token to swap to, defaults to 0").optional().default("0"),
wrap_eth: z.boolean().describe("Whether to wrap ETH to WETH, only use when swapping WETH into something").optional().default(false)
}).passthrough();
var UniswapIncreaseLiquidityProvisionRequest = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_id: z.number().int().describe("Token ID of the NFT representing the liquidity provisioned position."),
amount0_desired: z.union([z.number(), z.string()]).describe("The desired amount of the first token to deposit"),
amount1_desired: z.union([z.number(), z.string()]).describe("The desired amount of the second token to deposit"),
amount0_min: z.union([z.number(), z.string()]).describe("The minimum amount of the first token to deposit"),
amount1_min: z.union([z.number(), z.string()]).describe("The minimum amount of the second token to deposit")
}).passthrough();
var UniswapMintLiquidityProvision = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token0: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token1: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
fee: FeeEnum.describe(`The transaction fee of a Uniswap pool in bips.
Uniswap supports 4 different fee levels.`),
tick_lower: z.number().int().gte(-887272).lte(887272).describe("The lower tick of the range to mint the position in"),
tick_upper: z.number().int().gte(-887272).lte(887272).describe("The upper tick of the range to mint the position in"),
amount0_desired: z.union([z.number(), z.string()]).describe("The desired amount of the first token to deposit"),
amount1_desired: z.union([z.number(), z.string()]).describe("The desired amount of the second token to deposit"),
amount0_min: z.union([z.number(), z.string()]).describe("The minimum amount of the first token to deposit"),
amount1_min: z.union([z.number(), z.string()]).describe("The minimum amount of the second token to deposit"),
recipient: z.union([z.string(), z.null()]).describe("The address that will receive the LP tokens").optional()
}).passthrough();
var UniswapWithdrawLiquidityProvision = z.object({
chain: Chain.describe("The chain to use."),
sender: z.string().describe("The address of the transaction sender"),
token_id: z.number().int().describe("Token ID of the NFT representing the liquidity provisioned position."),
percentage_for_withdrawal: z.union([z.number(), z.string()]).describe("How much liquidity to take out in percentage.")
}).passthrough();
var UniswapGetBuyQuoteRequest = z.object({
chain: Chain.describe("The chain to use."),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
fee: FeeEnum.describe(`The transaction fee of a Uniswap pool in bips.
Uniswap supports 4 different fee levels.`),
amount_out: z.union([z.number(), z.string()]).describe("The amount of the token to swap to")
}).passthrough();
var UniswapBuyQuoteInfoResponse = z.object({
amount_in: z.string().describe("The amount of token_in you would need to give to the pool."),
price_after: z.string().describe(
"The price of the pool after this trade would happen. (How much token0 you need to buy 1 token1.)"
)
}).passthrough();
var UniswapGetSellQuoteRequest = z.object({
chain: Chain.describe("The chain to use."),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
fee: FeeEnum.describe(`The transaction fee of a Uniswap pool in bips.
Uniswap supports 4 different fee levels.`),
amount_in: z.union([z.number(), z.string()]).describe("The amount of the token to swap from")
}).passthrough();
var UniswapSellQuoteInfoResponse = z.object({
amount_out: z.string().describe("The amount of token_out you would receive from the pool."),
price_after: z.string().describe(
"The price of the pool after this trade would happen. (How much token0 you need to buy 1 token1.)"
)
}).passthrough();
var UniswapGetPoolPriceRequest = z.object({
chain: Chain.describe("The chain to use."),
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
fee: FeeEnum.describe(`The transaction fee of a Uniswap pool in bips.
Uniswap supports 4 different fee levels.`)
}).passthrough();
var UniswapPoolPriceResponse = z.object({
token_in: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token_out: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
price: z.string().describe(
"The price of the pool. This is expressed as an instantanteous amount of how many token0 you need to buy 1 token1. In any swap this will not change during the trade; use the quote endpoint to get a better idea of how much you will pay!"
),
tick: z.number().int().describe(
"The current tick in the pool. This is a number that represents the price of the pool according to the uniswap v3 concentrated liquidity concept."
)
}).passthrough();
var UniswapCheckInRangeRequest = z.object({
chain: Chain.describe("The chain to use."),
token_id: z.number().int().gte(0).describe("Token ID of the NFT representing the liquidity provisioned position.")
}).passthrough();
var UniswapCheckInRangeResponse = z.object({
in_range: z.boolean().describe(
"Whether the position is in active tick range or not. If not in range, the position is not earning trading fees."
)
}).passthrough();
var UniswapGetLiquidityProvisionPositionsRequest = z.object({
chain: Chain.describe("The chain to use."),
user: z.string().describe("The address of the user to check the balance of")
}).passthrough();
var UniswapPosition = z.object({
nonce: z.number().int(),
operator: z.string(),
token0: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
token1: Token.describe(`A class representing the token.
This class is used to represent the token in the system. Notice individual
endpoints' documentation where per chain tokens are presented.`),
fee: FeeEnum.describe(`The transaction fee of a Uniswap pool in bips.
Uniswap supports 4 different fee levels.`),
tick_lower: z.number().int(),
tick_upper: z.number().int(),
liquidity: z.number().int(),
fee_growth_inside0_last_x128: z.number().int(),
fee_growth_inside1_last_x128: z.number().int(),
tokens_owed0: z.number().int(),
tokens_owed1: z.number().int(),
token_id: z.number().int()
}).passthrough();
var UniswapLPPositionsInfoResponse = z.object({
positions: z.record(UniswapPosition).describe(`Liquidity provision positions belonging to a particular user. The key is a
tuple of the token0, token1, fee, tick_lower, and tick_upper of the position.`)
}).passthrough();
var schemas = {
Chain,
Token,
AaveSupplyRequest,
UnsignedTransaction,
ValidationError,
HTTPValidationError,
InterestRateMode,
AaveBorrowRequest,
AaveRepayRequest,
AaveWithdrawRequest,
AaveGetAssetPriceRequest,
AaveAssetPriceResponse,
AaveGetLiquidityChangeRequest,
AaveLiquidityChangeResponse,
AaveGetUserPositionSummaryRequest,
AaveUserPositionSummaryResponse,
AaveGetUserPositionPerTokenRequest,
AaveUserPositionPerTokenResponse,
AerodromeAddLiquidityRequest,
AerodromeAddLiquidityEthRequest,
AerodromeRemoveLiquidityRequest,
AerodromeRemoveLiquidityEthRequest,
AerodromeSwapTokensRequest,
AerodromeSwapEthForTokenRequest,
AerodromeSwapTokenForEthRequest,
AerodromeSlipstreamSellExactlyRequest,
AerodromeSlipstreamBuyExactlyRequest,
AerodromeSlipstreamMintLiquidityProvisionRequest,
AerodromeSlipstreamIncreaseLiquidityProvisionRequest,
AerodromeSlipstreamWithdrawLiquidityProvisionRequest,
AerodromeSlipstreamGetLiquidityProvisionPositionsRequest,
AerodromePosition,
AerodromeLPPositionsResponse,
AerodromeSlipstreamGetPoolPriceRequest,
AerodromeSlipstreamPoolPriceResponse,
PortfolioRequest,
TokenBalance,
Portfolio,
VisualizePortfolioRequest,
Image,
PriceRequest,
PriceResponse,
TokensRequest,
TokenInfo,
GetErc20BalanceRequest,
BalanceInfoResponse,
ContractName,
GetErc20AllowanceRequest,
AllowanceInfoResponse,
GetEnsDetailsRequest,
EnsNameInfoResponse,
WrapEthRequest,
UnwrapWethRequest,
TransferERC20Request,
TransferEthRequest,
IncreaseAllowanceRequest,
IncreaseAllowanceAnyRequest,
FeeEnum,
UniswapBuyExactlyRequest,
UniswapSellExactlyRequest,
UniswapIncreaseLiquidityProvisionRequest,
UniswapMintLiquidityProvision,
UniswapWithdrawLiquidityProvision,
UniswapGetBuyQuoteRequest,
UniswapBuyQuoteInfoResponse,
UniswapGetSellQuoteRequest,
UniswapSellQuoteInfoResponse,
UniswapGetPoolPriceRequest,
UniswapPoolPriceResponse,
UniswapCheckInRangeRequest,
UniswapCheckInRangeResponse,
UniswapGetLiquidityProvisionPositionsRequest,
UniswapPosition,
UniswapLPPositionsInfoResponse
};
var endpoints = z2([
{
method: "post",
path: "/v0/aave/asset_price/get",
description: `This endpoint retrieves the current price of a specified asset in USD as
determined by the Aave protocol.
It utilizes the Aave V3 Oracle to fetch the asset price, ensuring accurate and up-
to-date information. The request requires the asset identifier and the blockchain
network (chain) on which the asset resides. The response provides the asset price in
a standardized format, converted from Wei to the base currency decimals defined by
Aave.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveGetAssetPriceRequest
}
],
response: z.object({ price: z.string().describe("The price of the asset in USD.") }).passthrough(),
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aave/borrow",
description: `You will pay interest for your borrows.
Price changes in the assets may lead to some or all of your collateral being
liquidated, if the borrow position becomes unhealthy.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveBorrowRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aave/liquidity/change/get",
description: `This endpoint retrieves the change in the reserve liquidity index between two
provided blocks.
This is then converted to a percentage change. The liquidity index represents the
change in debt and interest accrual over each block. Aave does not store individual
user balances directly. Instead, it keeps a scaled balance and uses the liquidity
index to compute real balances dynamically. If a user was to have deposited tokens
at the start block, a positive liquidity index change will represent accrued
interest and a profit. If tokens were borrowed at the start block, this debt will
increase, compound on itself and represent large debt. The reverse in both cases is
true if the liquidity index is negative.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveGetLiquidityChangeRequest
}
],
response: AaveLiquidityChangeResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aave/repay",
description: `This endpoint allows users to repay a portion or the entirety of their borrowed
tokens on the Aave platform.
By repaying borrowed amounts, users can improve their health factor, which is a
measure of the safety of their loan position. A higher health factor reduces the
risk of liquidation, ensuring a more secure borrowing experience. The endpoint
requires specifying the chain and the details of the repayment transaction,
including the amount and the asset to be repaid.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveRepayRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aave/supply",
description: `By supplying assets, users can earn interest on their deposits.
The supplied collateral can be used as a basis for borrowing other assets, allowing
users to leverage their positions. In combination with a trading protocol, this can
create leverage.
Overall, this endpoint is a critical component for users looking to maximize their
asset utility within the AAVEv3 ecosystem, providing both earning potential and
borrowing flexibility.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveSupplyRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aave/user_position_per_token/get",
description: `This endpoint retrieves the user's position for a specific token on the AAVE
platform.
It provides key financial metrics including the current aToken balance, current
stable debt, current variable debt, principal stable debt, principal variable debt,
stable borrow rate, stable borrow rate for new loans, variable borrow rate, and
liquidity rate. These metrics are calculated by aggregating data across all open
positions held by the user for the specified token, offering a detailed view of
their financial standing within the AAVE ecosystem.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveGetUserPositionPerTokenRequest
}
],
response: AaveUserPositionPerTokenResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aave/user_position_summary/get",
description: `This endpoint retrieves a comprehensive summary of a user's position on the AAVE
platform.
It provides key financial metrics including the total collateral deposited, total
debt accrued, available borrowing capacity, liquidation threshold, maximum loan-to-
value ratio, and the health factor of the user's account. These metrics are
calculated by aggregating data across all open positions held by the user, offering
a holistic view of their financial standing within the AAVE ecosystem.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveGetUserPositionSummaryRequest
}
],
response: AaveUserPositionSummaryResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aave/withdraw",
description: `This endpoint facilitates the withdrawal of collateral from the Aave protocol.
Users can withdraw a portion or all of their collateral, which may increase the risk
of liquidation if there are outstanding borrows. The withdrawal process also
includes the collection of any interest earned on the collateral. It is important
for users to carefully consider their outstanding debts and the potential impact on
their liquidation threshold before proceeding with a withdrawal. This endpoint is
designed to provide a seamless and efficient way to manage your collateral within
the Aave ecosystem.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AaveWithdrawRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_basic/liquidity_provision/add_liquidity",
description: `This endpoint allows users to provide liquidity to a specified pool on the
Aerodrome platform.
Users must specify the tokens, desired amounts, minimum amounts, and a deadline for
the transaction. The operation will ensure the pool exists and will use the sender's
address if no recipient is specified.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeAddLiquidityRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_basic/liquidity_provision/add_liquidity_eth",
description: `This endpoint allows users to provide liquidity to a specified pool on the
Aerodrome platform using Wrapped Ether (WETH) and another token.
Users must specify the token pair, desired amounts, minimum amounts, and a deadline
for the transaction. The operation will ensure the pool exists and will use the
sender's address if no recipient is specified. The transaction will be executed
through the Aerodrome Basic Router contract, and the specified amount of WETH will
be sent along with the transaction.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeAddLiquidityEthRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_basic/liquidity_provision/remove_liquidity",
description: `This endpoint allows users to remove liquidity from a specified pool on the
Aerodrome platform.
Users must specify the token pair, the amount of liquidity to remove, minimum
amounts for each token, and a deadline for the transaction. The operation will
ensure the pool exists and will use the sender's address if no recipient is
specified. The transaction will be executed through the Aerodrome Basic Router
contract, and the specified amount of liquidity will be withdrawn from the pool.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeRemoveLiquidityRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_basic/liquidity_provision/remove_liquidity_eth",
description: `This endpoint allows users to remove liquidity from a pool on the Aerodrome
platform using WETH and another token.
Users must specify the token pair, the amount of liquidity to remove, minimum
amounts for each token, and a deadline for the transaction. The operation will
ensure the pool exists and will use the sender's address if no recipient is
specified. The transaction will be executed through the Aerodrome Basic Router
contract, and the specified amount of liquidity will be withdrawn from the pool.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeRemoveLiquidityEthRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_basic/swap/eth_for_token",
description: `This endpoint allows you to swap a specified amount of ETH for a desired token on
the Aerodrome platform.
To protect against unfavorable exchange rates, you must specify the minimum amount
of the token you wish to receive. The transaction will only be executed if this
minimum amount is met, ensuring you do not accidentally trade at a disadvantageous
rate.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSwapEthForTokenRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_basic/swap/token_for_eth",
description: `Swap a specified amount of a token for ETH using the Aerodrome platform.
To protect against unfavorable exchange rates, you must specify the minimum amount
of ETH you wish to receive. The transaction will only be executed if this minimum
amount is met, ensuring you do not trade at a disadvantageous rate.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSwapTokenForEthRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_basic/swap/tokens",
description: `Swap one token for another on Aerodrome.
Ensure you specify the minimum amount you expect to receive to avoid trading at an
unfavorable exchange rate. This endpoint facilitates the exchange of tokens by
interacting with the Aerodrome smart contract, ensuring that the transaction is
executed only if the specified minimum output is met.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSwapTokensRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_slipstream/liquidity_provision/increase",
description: `Increase the liquidity of an existing Liquidity Provider (LP) position.
This endpoint allows users to add more tokens to their current LP position,
enhancing their participation in liquidity provision. By increasing liquidity, users
can potentially earn more rewards and improve their position in the pool. The
process involves specifying additional token amounts and updating the pool details.
The response will confirm the successful increase of the LP position, providing
users with updated information about their enhanced position. This functionality is
vital for users aiming to optimize their liquidity provision strategy, enabling them
to adapt to market conditions and maximize their returns in decentralized finance
(DeFi) markets.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSlipstreamIncreaseLiquidityProvisionRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_slipstream/liquidity_provision/mint",
description: `Initiate a new Liquidity Provider (LP) position by minting tokens.
This endpoint allows users to open a new LP position, enabling them to participate
in liquidity provision. The minting process involves creating a new position with
specified parameters, such as token amounts and pool details. The response will
confirm the successful creation of the LP position, providing users with the
necessary information to manage their newly minted position. This functionality is
crucial for users looking to expand their liquidity provision activities, offering
them the opportunity to engage in decentralized finance (DeFi) markets effectively.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSlipstreamMintLiquidityProvisionRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_slipstream/liquidity_provision/positions/get",
description: `Retrieve the total number of Liquidity Provider (LP) positions associated with a
specific sender.
This endpoint allows users to query and obtain detailed information about their LP
positions, including the number of active positions they hold. The response model,
AerodromeLPPositionsInfo, provides a structured representation of the LP positions
data, ensuring clarity and ease of use. This functionality is essential for users
managing their liquidity provision activities, enabling them to make informed
decisions based on their current positions.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSlipstreamGetLiquidityProvisionPositionsRequest
}
],
response: AerodromeLPPositionsResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_slipstream/liquidity_provision/withdraw",
description: `Withdraw an existing Liquidity Provider (LP) position.
This endpoint allows users to remove their tokens from an LP position, effectively
closing their participation in the liquidity pool. The withdrawal process involves
specifying the LP position to be closed, and the response will confirm the
successful removal of liquidity, providing users with details about the withdrawn
tokens and any remaining balances. This functionality is essential for users who
wish to exit their liquidity provision activities, enabling them to reclaim their
assets and potentially reallocate them to other investment opportunities. The
endpoint ensures a smooth and secure withdrawal process, facilitating users'
strategic management of their decentralized finance (DeFi) portfolios.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSlipstreamWithdrawLiquidityProvisionRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_slipstream/pool_price/get",
description: `This endpoint retrieves the current price of a pool, indicating how many token0
you can purchase for 1 token1.
Note that this is an instantaneous price and may change during any trade. For a more
accurate representation of the trade ratios between the two assets, consider using
the quote endpoint.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSlipstreamGetPoolPriceRequest
}
],
response: AerodromeSlipstreamPoolPriceResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_slipstream/swap/buy_exactly",
description: `This endpoint facilitates the trading of tokens by allowing users to specify the
exact amount of the output token they wish to receive.
Utilizing the Aerodrome Slipstream protocol, the system calculates the necessary
amount of the input token required to achieve the desired output. This operation is
particularly useful for users who have a specific target amount of the output token
in mind and are willing to provide the corresponding input token amount. The
transaction is executed with consideration of current market conditions, including
liquidity and price impact, ensuring that the trade is completed efficiently and
effectively.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSlipstreamBuyExactlyRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/aerodrome_slipstream/swap/sell_exactly",
description: `This endpoint allows users to trade a specific amount of one token into another
token using the Aerodrome Slipstream protocol.
The transaction is executed by specifying the exact amount of the input token to be
sold, and the system calculates the amount of the output token that will be
received. The operation ensures that the trade is conducted within the constraints
of the current market conditions, taking into account the liquidity and price
impact. This endpoint is suitable for users who want to sell a precise quantity of a
token and are willing to accept the resulting amount of the other token.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: AerodromeSlipstreamSellExactlyRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/allowance/get",
description: `In decentralized finance (DeFi) protocols such as Uniswap or AAVE, users must set
a token allowance to authorize the protocol to spend a specified amount of their
tokens on their behalf.
This is a crucial step before engaging in any transactions or operations within
these protocols, ensuring that the protocol has the necessary permissions to manage
the user's tokens securely and efficiently.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: GetErc20AllowanceRequest
}
],
response: AllowanceInfoResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/allowance/set",
description: `This endpoint allows users to modify the token allowance for a specific protocol.
In decentralized finance (DeFi), setting an allowance is a necessary step to
authorize a protocol to spend a specified amount of tokens on behalf of the user.
This operation is crucial for ensuring that the protocol can manage the user's
tokens securely and efficiently, enabling seamless transactions and operations
within the DeFi ecosystem.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: IncreaseAllowanceRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/allowance/set_any",
description: `This endpoint allows users to set an allowance for any arbitrary ERC20 token
address.
In decentralized finance (DeFi), setting an allowance is a critical operation that
permits a protocol to spend a specified amount of tokens on behalf of the user. This
functionality is essential for enabling secure and efficient token management,
facilitating smooth transactions and operations within the DeFi ecosystem. By using
this endpoint, users can specify the token address and the amount they wish to
authorize, ensuring precise control over their token allowances.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: IncreaseAllowanceAnyRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/balance/get",
description: `Returns the balance of a specific ERC20 token for a given user address.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: GetErc20BalanceRequest
}
],
response: BalanceInfoResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/ens/get",
description: `An ENS name is a string ending in `.eth`.
E.g. `vitalik.eth`. This endpoint can be used to
query the actual ethereum wallet address behind the ENS name.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: GetEnsDetailsRequest
}
],
response: EnsNameInfoResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/portfolio/get",
description: `Fetch the detailed portfolio of a specific wallet address on a given blockchain.
This includes the total value of the portfolio in USD and a breakdown of token
balances, including their respective values and quantities.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: PortfolioRequest
}
],
response: Portfolio,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/price/usd/get",
description: `Retrieves the price of the specified token relative to USD using Chainlink's on-
chain price feeds.
Chainlink is a decentralized oracle that aggregates price data from off-chain
sources. This ensures the price is tamper-resistant but the price might be stale
with the update frequency of the oracle.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: PriceRequest
}
],
response: z.object({
token_price_in_usd: z.string().describe("Price of the token in USD")
}).passthrough(),
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/supported_tokens/get",
description: `Get the list of supported tokens on a chain by the Compass API.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: TokensRequest
}
],
response: TokenInfo,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/transfer/erc20",
description: `Sends ERC20 tokens from the sender's address to the specified recipient.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: TransferERC20Request
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/transfer/native_token",
description: `Sends native ETH from the sender's address to the specified recipient.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: TransferEthRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/unwrap_weth",
description: `Unwrapping WETH converts the ERC-20 compliant form of ETH back to native ETH that
can be used for gas and other native purposes.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UnwrapWethRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/visualize_portfolio/get",
description: `Generate a visual representation of the token portfolio for a wallet address.
The response is an SVG image of a pie chart depicting the relative distribution of
tokens held, colored and labeled with token symbols, percentages and token values in
USD.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: VisualizePortfolioRequest
}
],
response: z.object({ image: z.string().describe("Base64 encoded SVG image") }).passthrough(),
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/generic/wrap_eth",
description: `Wrapping ETH creates an ERC-20 compliant form of ETH that is typically needed for
it to be traded on DeFi protocols.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: WrapEthRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/liquidity_provision/in_range/get",
description: `This endpoint allows users to check whether a specific liquidity provider ()
position is within the active tick range on the uniswap platform.
by providing the token id associated with the position, users can verify if the
position is currently within the tick range where trading occurs. this information
is essential for users to monitor the status of their lp positions and ensure that
they are actively participating in the trading activities within the liquidity pool
and earning trading fees.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapCheckInRangeRequest
}
],
response: z.object({
in_range: z.boolean().describe(
"Whether the position is in active tick range or not. If not in range, the position is not earning trading fees."
)
}).passthrough(),
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/liquidity_provision/increase",
description: `This endpoint allows users to increase their existing Liquidity Provider (LP)
positions on the Uniswap platform.
By providing the necessary parameters, users can add more liquidity to their current
positions, thereby increasing their stake in the liquidity pool. This operation is
beneficial for users who wish to enhance their potential earnings from trading fees
within the pool. The endpoint requires details such as the token pair, additional
amount to be added, and any other parameters necessary for the liquidity increase
process.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapIncreaseLiquidityProvisionRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/liquidity_provision/mint",
description: `This endpoint allows users to open a new Liquidity Provider (LP) position on the
Uniswap platform.
By providing the necessary parameters, users can initiate a minting process to
create a new LP token, which represents their stake in a specific liquidity pool.
This operation is essential for users looking to participate in liquidity provision,
enabling them to earn fees from trades that occur within the pool. The endpoint
requires details such as the token pair, amount, and any additional parameters
needed for the minting process.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapMintLiquidityProvision
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/liquidity_provision/positions/get",
description: `This endpoint retrieves the number of Liquidity Provider (LP) positions
associated with a specific sender address on the Uniswap platform.
Users can query this endpoint to obtain detailed information about their LP
positions, including the total number of positions and relevant metadata. This
information is crucial for users to manage and analyze their liquidity provision
activities effectively.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapGetLiquidityProvisionPositionsRequest
}
],
response: UniswapLPPositionsInfoResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/liquidity_provision/withdraw",
description: `This endpoint allows users to withdraw their Liquidity Provider (LP) positions
from the Uniswap platform.
By specifying the necessary parameters, users can initiate the withdrawal process to
remove their stake from a specific liquidity pool. This operation is crucial for
users who wish to reclaim their assets or reallocate their liquidity to different
pools or investments. The endpoint requires details such as the token pair, the
amount to be withdrawn, and any additional parameters needed for the withdrawal
process. Users should ensure they meet any protocol requirements or conditions
before initiating a withdrawal to avoid potential issues or penalties.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapWithdrawLiquidityProvision
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/pool_price/get",
description: `This endpoint calculates the price of a token in a Uniswap pool.
The price is calculated based on the current pool state and the specified fee tier.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapGetPoolPriceRequest
}
],
response: UniswapPoolPriceResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/quote/buy_exactly/get",
description: `This endpoint calculates the amount of input tokens required to purchase a
specified amount of output tokens from a Uniswap pool.
It also provides the resulting price after the transaction. The calculation takes
into account the current pool state and the specified fee tier.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapGetBuyQuoteRequest
}
],
response: UniswapBuyQuoteInfoResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/quote/sell_exactly/get",
description: `This endpoint calculates the amount of input tokens required to purchase a
specified amount of output tokens from a Uniswap pool.
It also provides the resulting price after the transaction. The calculation takes
into account the current pool state and the specified fee tier.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapGetSellQuoteRequest
}
],
response: UniswapSellQuoteInfoResponse,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/swap/buy_exactly",
description: `This endpoint allows users to trade a variable amount of one token to receive an
exact amount of another token using the Uniswap protocol.
The transaction is executed on the specified blockchain network, and the user must
provide the necessary transaction details, including the token to buy, the token to
pay with, and the exact amount to receive. If the token being paid with is WETH and
needs to be wrapped, the appropriate amount will be wrapped automatically.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapBuyExactlyRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
},
{
method: "post",
path: "/v0/uniswap/swap/sell_exactly",
description: `This endpoint allows users to trade a specific amount of one token into another
token using the Uniswap protocol.
The transaction is executed on the specified blockchain network, and the user must
provide the necessary transaction details, including the token to sell, the token to
receive, and the amount to sell. If the token being sold is WETH and needs to be
wrapped, the appropriate amount will be wrapped automatically.`,
requestFormat: "json",
parameters: [
{
name: "body",
type: "Body",
schema: UniswapSellExactlyRequest
}
],
response: UnsignedTransaction,
errors: [
{
status: 422,
description: `Validation Error`,
schema: HTTPValidationError
}
]
}
]);
var api = new te(endpoints);
function createApiClient(baseUrl, options) {
var _a;
const defaultHeaders = {
"x-compass-origin": "ts-sdk"
};
const finalOptions = __spreadProps(__spreadValues({}, options), {
axiosConfig: __spreadProps(__spreadValues({}, options == null ? void 0 : options.axiosConfig), {
headers: __spreadValues(__spreadValues({}, defaultHeaders), (_a = options == null ? void 0 : options.axiosConfig) == null ? void 0 : _a.headers)
})
});
return new te(baseUrl, endpoints, finalOptions);
}
export {
api,
createApiClient,
schemas
};
//# sourceMappingURL=index.mjs.map