@dodopayments/convex 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,3 @@
1
- import { z } from 'zod';
2
-
3
1
  // This is the public-facing client that developers will use.
4
2
  class DodoPayments {
5
3
  constructor(component, config) {
@@ -988,44 +986,4014 @@ var convex_config = defineComponent("dodopayments");
988
986
  */
989
987
  const httpAction = httpActionGeneric;
990
988
 
991
- var PaymentSchema = z.object({
992
- payload_type: z.literal("Payment"),
993
- billing: z.object({
994
- city: z.string().nullable(),
995
- country: z.string().nullable(),
996
- state: z.string().nullable(),
997
- street: z.string().nullable(),
998
- zipcode: z.string().nullable(),
989
+ var util;
990
+ (function (util) {
991
+ util.assertEqual = (_) => { };
992
+ function assertIs(_arg) { }
993
+ util.assertIs = assertIs;
994
+ function assertNever(_x) {
995
+ throw new Error();
996
+ }
997
+ util.assertNever = assertNever;
998
+ util.arrayToEnum = (items) => {
999
+ const obj = {};
1000
+ for (const item of items) {
1001
+ obj[item] = item;
1002
+ }
1003
+ return obj;
1004
+ };
1005
+ util.getValidEnumValues = (obj) => {
1006
+ const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
1007
+ const filtered = {};
1008
+ for (const k of validKeys) {
1009
+ filtered[k] = obj[k];
1010
+ }
1011
+ return util.objectValues(filtered);
1012
+ };
1013
+ util.objectValues = (obj) => {
1014
+ return util.objectKeys(obj).map(function (e) {
1015
+ return obj[e];
1016
+ });
1017
+ };
1018
+ util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
1019
+ ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
1020
+ : (object) => {
1021
+ const keys = [];
1022
+ for (const key in object) {
1023
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
1024
+ keys.push(key);
1025
+ }
1026
+ }
1027
+ return keys;
1028
+ };
1029
+ util.find = (arr, checker) => {
1030
+ for (const item of arr) {
1031
+ if (checker(item))
1032
+ return item;
1033
+ }
1034
+ return undefined;
1035
+ };
1036
+ util.isInteger = typeof Number.isInteger === "function"
1037
+ ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
1038
+ : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
1039
+ function joinValues(array, separator = " | ") {
1040
+ return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
1041
+ }
1042
+ util.joinValues = joinValues;
1043
+ util.jsonStringifyReplacer = (_, value) => {
1044
+ if (typeof value === "bigint") {
1045
+ return value.toString();
1046
+ }
1047
+ return value;
1048
+ };
1049
+ })(util || (util = {}));
1050
+ var objectUtil;
1051
+ (function (objectUtil) {
1052
+ objectUtil.mergeShapes = (first, second) => {
1053
+ return {
1054
+ ...first,
1055
+ ...second, // second overwrites first
1056
+ };
1057
+ };
1058
+ })(objectUtil || (objectUtil = {}));
1059
+ const ZodParsedType = util.arrayToEnum([
1060
+ "string",
1061
+ "nan",
1062
+ "number",
1063
+ "integer",
1064
+ "float",
1065
+ "boolean",
1066
+ "date",
1067
+ "bigint",
1068
+ "symbol",
1069
+ "function",
1070
+ "undefined",
1071
+ "null",
1072
+ "array",
1073
+ "object",
1074
+ "unknown",
1075
+ "promise",
1076
+ "void",
1077
+ "never",
1078
+ "map",
1079
+ "set",
1080
+ ]);
1081
+ const getParsedType = (data) => {
1082
+ const t = typeof data;
1083
+ switch (t) {
1084
+ case "undefined":
1085
+ return ZodParsedType.undefined;
1086
+ case "string":
1087
+ return ZodParsedType.string;
1088
+ case "number":
1089
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
1090
+ case "boolean":
1091
+ return ZodParsedType.boolean;
1092
+ case "function":
1093
+ return ZodParsedType.function;
1094
+ case "bigint":
1095
+ return ZodParsedType.bigint;
1096
+ case "symbol":
1097
+ return ZodParsedType.symbol;
1098
+ case "object":
1099
+ if (Array.isArray(data)) {
1100
+ return ZodParsedType.array;
1101
+ }
1102
+ if (data === null) {
1103
+ return ZodParsedType.null;
1104
+ }
1105
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
1106
+ return ZodParsedType.promise;
1107
+ }
1108
+ if (typeof Map !== "undefined" && data instanceof Map) {
1109
+ return ZodParsedType.map;
1110
+ }
1111
+ if (typeof Set !== "undefined" && data instanceof Set) {
1112
+ return ZodParsedType.set;
1113
+ }
1114
+ if (typeof Date !== "undefined" && data instanceof Date) {
1115
+ return ZodParsedType.date;
1116
+ }
1117
+ return ZodParsedType.object;
1118
+ default:
1119
+ return ZodParsedType.unknown;
1120
+ }
1121
+ };
1122
+
1123
+ const ZodIssueCode = util.arrayToEnum([
1124
+ "invalid_type",
1125
+ "invalid_literal",
1126
+ "custom",
1127
+ "invalid_union",
1128
+ "invalid_union_discriminator",
1129
+ "invalid_enum_value",
1130
+ "unrecognized_keys",
1131
+ "invalid_arguments",
1132
+ "invalid_return_type",
1133
+ "invalid_date",
1134
+ "invalid_string",
1135
+ "too_small",
1136
+ "too_big",
1137
+ "invalid_intersection_types",
1138
+ "not_multiple_of",
1139
+ "not_finite",
1140
+ ]);
1141
+ class ZodError extends Error {
1142
+ get errors() {
1143
+ return this.issues;
1144
+ }
1145
+ constructor(issues) {
1146
+ super();
1147
+ this.issues = [];
1148
+ this.addIssue = (sub) => {
1149
+ this.issues = [...this.issues, sub];
1150
+ };
1151
+ this.addIssues = (subs = []) => {
1152
+ this.issues = [...this.issues, ...subs];
1153
+ };
1154
+ const actualProto = new.target.prototype;
1155
+ if (Object.setPrototypeOf) {
1156
+ // eslint-disable-next-line ban/ban
1157
+ Object.setPrototypeOf(this, actualProto);
1158
+ }
1159
+ else {
1160
+ this.__proto__ = actualProto;
1161
+ }
1162
+ this.name = "ZodError";
1163
+ this.issues = issues;
1164
+ }
1165
+ format(_mapper) {
1166
+ const mapper = _mapper ||
1167
+ function (issue) {
1168
+ return issue.message;
1169
+ };
1170
+ const fieldErrors = { _errors: [] };
1171
+ const processError = (error) => {
1172
+ for (const issue of error.issues) {
1173
+ if (issue.code === "invalid_union") {
1174
+ issue.unionErrors.map(processError);
1175
+ }
1176
+ else if (issue.code === "invalid_return_type") {
1177
+ processError(issue.returnTypeError);
1178
+ }
1179
+ else if (issue.code === "invalid_arguments") {
1180
+ processError(issue.argumentsError);
1181
+ }
1182
+ else if (issue.path.length === 0) {
1183
+ fieldErrors._errors.push(mapper(issue));
1184
+ }
1185
+ else {
1186
+ let curr = fieldErrors;
1187
+ let i = 0;
1188
+ while (i < issue.path.length) {
1189
+ const el = issue.path[i];
1190
+ const terminal = i === issue.path.length - 1;
1191
+ if (!terminal) {
1192
+ curr[el] = curr[el] || { _errors: [] };
1193
+ // if (typeof el === "string") {
1194
+ // curr[el] = curr[el] || { _errors: [] };
1195
+ // } else if (typeof el === "number") {
1196
+ // const errorArray: any = [];
1197
+ // errorArray._errors = [];
1198
+ // curr[el] = curr[el] || errorArray;
1199
+ // }
1200
+ }
1201
+ else {
1202
+ curr[el] = curr[el] || { _errors: [] };
1203
+ curr[el]._errors.push(mapper(issue));
1204
+ }
1205
+ curr = curr[el];
1206
+ i++;
1207
+ }
1208
+ }
1209
+ }
1210
+ };
1211
+ processError(this);
1212
+ return fieldErrors;
1213
+ }
1214
+ static assert(value) {
1215
+ if (!(value instanceof ZodError)) {
1216
+ throw new Error(`Not a ZodError: ${value}`);
1217
+ }
1218
+ }
1219
+ toString() {
1220
+ return this.message;
1221
+ }
1222
+ get message() {
1223
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
1224
+ }
1225
+ get isEmpty() {
1226
+ return this.issues.length === 0;
1227
+ }
1228
+ flatten(mapper = (issue) => issue.message) {
1229
+ const fieldErrors = {};
1230
+ const formErrors = [];
1231
+ for (const sub of this.issues) {
1232
+ if (sub.path.length > 0) {
1233
+ const firstEl = sub.path[0];
1234
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
1235
+ fieldErrors[firstEl].push(mapper(sub));
1236
+ }
1237
+ else {
1238
+ formErrors.push(mapper(sub));
1239
+ }
1240
+ }
1241
+ return { formErrors, fieldErrors };
1242
+ }
1243
+ get formErrors() {
1244
+ return this.flatten();
1245
+ }
1246
+ }
1247
+ ZodError.create = (issues) => {
1248
+ const error = new ZodError(issues);
1249
+ return error;
1250
+ };
1251
+
1252
+ const errorMap = (issue, _ctx) => {
1253
+ let message;
1254
+ switch (issue.code) {
1255
+ case ZodIssueCode.invalid_type:
1256
+ if (issue.received === ZodParsedType.undefined) {
1257
+ message = "Required";
1258
+ }
1259
+ else {
1260
+ message = `Expected ${issue.expected}, received ${issue.received}`;
1261
+ }
1262
+ break;
1263
+ case ZodIssueCode.invalid_literal:
1264
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
1265
+ break;
1266
+ case ZodIssueCode.unrecognized_keys:
1267
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
1268
+ break;
1269
+ case ZodIssueCode.invalid_union:
1270
+ message = `Invalid input`;
1271
+ break;
1272
+ case ZodIssueCode.invalid_union_discriminator:
1273
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
1274
+ break;
1275
+ case ZodIssueCode.invalid_enum_value:
1276
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
1277
+ break;
1278
+ case ZodIssueCode.invalid_arguments:
1279
+ message = `Invalid function arguments`;
1280
+ break;
1281
+ case ZodIssueCode.invalid_return_type:
1282
+ message = `Invalid function return type`;
1283
+ break;
1284
+ case ZodIssueCode.invalid_date:
1285
+ message = `Invalid date`;
1286
+ break;
1287
+ case ZodIssueCode.invalid_string:
1288
+ if (typeof issue.validation === "object") {
1289
+ if ("includes" in issue.validation) {
1290
+ message = `Invalid input: must include "${issue.validation.includes}"`;
1291
+ if (typeof issue.validation.position === "number") {
1292
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
1293
+ }
1294
+ }
1295
+ else if ("startsWith" in issue.validation) {
1296
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
1297
+ }
1298
+ else if ("endsWith" in issue.validation) {
1299
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
1300
+ }
1301
+ else {
1302
+ util.assertNever(issue.validation);
1303
+ }
1304
+ }
1305
+ else if (issue.validation !== "regex") {
1306
+ message = `Invalid ${issue.validation}`;
1307
+ }
1308
+ else {
1309
+ message = "Invalid";
1310
+ }
1311
+ break;
1312
+ case ZodIssueCode.too_small:
1313
+ if (issue.type === "array")
1314
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
1315
+ else if (issue.type === "string")
1316
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
1317
+ else if (issue.type === "number")
1318
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1319
+ else if (issue.type === "bigint")
1320
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1321
+ else if (issue.type === "date")
1322
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
1323
+ else
1324
+ message = "Invalid input";
1325
+ break;
1326
+ case ZodIssueCode.too_big:
1327
+ if (issue.type === "array")
1328
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
1329
+ else if (issue.type === "string")
1330
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
1331
+ else if (issue.type === "number")
1332
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1333
+ else if (issue.type === "bigint")
1334
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1335
+ else if (issue.type === "date")
1336
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
1337
+ else
1338
+ message = "Invalid input";
1339
+ break;
1340
+ case ZodIssueCode.custom:
1341
+ message = `Invalid input`;
1342
+ break;
1343
+ case ZodIssueCode.invalid_intersection_types:
1344
+ message = `Intersection results could not be merged`;
1345
+ break;
1346
+ case ZodIssueCode.not_multiple_of:
1347
+ message = `Number must be a multiple of ${issue.multipleOf}`;
1348
+ break;
1349
+ case ZodIssueCode.not_finite:
1350
+ message = "Number must be finite";
1351
+ break;
1352
+ default:
1353
+ message = _ctx.defaultError;
1354
+ util.assertNever(issue);
1355
+ }
1356
+ return { message };
1357
+ };
1358
+
1359
+ let overrideErrorMap = errorMap;
1360
+ function getErrorMap() {
1361
+ return overrideErrorMap;
1362
+ }
1363
+
1364
+ const makeIssue = (params) => {
1365
+ const { data, path, errorMaps, issueData } = params;
1366
+ const fullPath = [...path, ...(issueData.path || [])];
1367
+ const fullIssue = {
1368
+ ...issueData,
1369
+ path: fullPath,
1370
+ };
1371
+ if (issueData.message !== undefined) {
1372
+ return {
1373
+ ...issueData,
1374
+ path: fullPath,
1375
+ message: issueData.message,
1376
+ };
1377
+ }
1378
+ let errorMessage = "";
1379
+ const maps = errorMaps
1380
+ .filter((m) => !!m)
1381
+ .slice()
1382
+ .reverse();
1383
+ for (const map of maps) {
1384
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
1385
+ }
1386
+ return {
1387
+ ...issueData,
1388
+ path: fullPath,
1389
+ message: errorMessage,
1390
+ };
1391
+ };
1392
+ function addIssueToContext(ctx, issueData) {
1393
+ const overrideMap = getErrorMap();
1394
+ const issue = makeIssue({
1395
+ issueData: issueData,
1396
+ data: ctx.data,
1397
+ path: ctx.path,
1398
+ errorMaps: [
1399
+ ctx.common.contextualErrorMap, // contextual error map is first priority
1400
+ ctx.schemaErrorMap, // then schema-bound map if available
1401
+ overrideMap, // then global override map
1402
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
1403
+ ].filter((x) => !!x),
1404
+ });
1405
+ ctx.common.issues.push(issue);
1406
+ }
1407
+ class ParseStatus {
1408
+ constructor() {
1409
+ this.value = "valid";
1410
+ }
1411
+ dirty() {
1412
+ if (this.value === "valid")
1413
+ this.value = "dirty";
1414
+ }
1415
+ abort() {
1416
+ if (this.value !== "aborted")
1417
+ this.value = "aborted";
1418
+ }
1419
+ static mergeArray(status, results) {
1420
+ const arrayValue = [];
1421
+ for (const s of results) {
1422
+ if (s.status === "aborted")
1423
+ return INVALID;
1424
+ if (s.status === "dirty")
1425
+ status.dirty();
1426
+ arrayValue.push(s.value);
1427
+ }
1428
+ return { status: status.value, value: arrayValue };
1429
+ }
1430
+ static async mergeObjectAsync(status, pairs) {
1431
+ const syncPairs = [];
1432
+ for (const pair of pairs) {
1433
+ const key = await pair.key;
1434
+ const value = await pair.value;
1435
+ syncPairs.push({
1436
+ key,
1437
+ value,
1438
+ });
1439
+ }
1440
+ return ParseStatus.mergeObjectSync(status, syncPairs);
1441
+ }
1442
+ static mergeObjectSync(status, pairs) {
1443
+ const finalObject = {};
1444
+ for (const pair of pairs) {
1445
+ const { key, value } = pair;
1446
+ if (key.status === "aborted")
1447
+ return INVALID;
1448
+ if (value.status === "aborted")
1449
+ return INVALID;
1450
+ if (key.status === "dirty")
1451
+ status.dirty();
1452
+ if (value.status === "dirty")
1453
+ status.dirty();
1454
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1455
+ finalObject[key.value] = value.value;
1456
+ }
1457
+ }
1458
+ return { status: status.value, value: finalObject };
1459
+ }
1460
+ }
1461
+ const INVALID = Object.freeze({
1462
+ status: "aborted",
1463
+ });
1464
+ const DIRTY = (value) => ({ status: "dirty", value });
1465
+ const OK = (value) => ({ status: "valid", value });
1466
+ const isAborted = (x) => x.status === "aborted";
1467
+ const isDirty = (x) => x.status === "dirty";
1468
+ const isValid = (x) => x.status === "valid";
1469
+ const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1470
+
1471
+ var errorUtil;
1472
+ (function (errorUtil) {
1473
+ errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1474
+ // biome-ignore lint:
1475
+ errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
1476
+ })(errorUtil || (errorUtil = {}));
1477
+
1478
+ class ParseInputLazyPath {
1479
+ constructor(parent, value, path, key) {
1480
+ this._cachedPath = [];
1481
+ this.parent = parent;
1482
+ this.data = value;
1483
+ this._path = path;
1484
+ this._key = key;
1485
+ }
1486
+ get path() {
1487
+ if (!this._cachedPath.length) {
1488
+ if (Array.isArray(this._key)) {
1489
+ this._cachedPath.push(...this._path, ...this._key);
1490
+ }
1491
+ else {
1492
+ this._cachedPath.push(...this._path, this._key);
1493
+ }
1494
+ }
1495
+ return this._cachedPath;
1496
+ }
1497
+ }
1498
+ const handleResult = (ctx, result) => {
1499
+ if (isValid(result)) {
1500
+ return { success: true, data: result.value };
1501
+ }
1502
+ else {
1503
+ if (!ctx.common.issues.length) {
1504
+ throw new Error("Validation failed but no issues detected.");
1505
+ }
1506
+ return {
1507
+ success: false,
1508
+ get error() {
1509
+ if (this._error)
1510
+ return this._error;
1511
+ const error = new ZodError(ctx.common.issues);
1512
+ this._error = error;
1513
+ return this._error;
1514
+ },
1515
+ };
1516
+ }
1517
+ };
1518
+ function processCreateParams(params) {
1519
+ if (!params)
1520
+ return {};
1521
+ const { errorMap, invalid_type_error, required_error, description } = params;
1522
+ if (errorMap && (invalid_type_error || required_error)) {
1523
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1524
+ }
1525
+ if (errorMap)
1526
+ return { errorMap: errorMap, description };
1527
+ const customMap = (iss, ctx) => {
1528
+ const { message } = params;
1529
+ if (iss.code === "invalid_enum_value") {
1530
+ return { message: message ?? ctx.defaultError };
1531
+ }
1532
+ if (typeof ctx.data === "undefined") {
1533
+ return { message: message ?? required_error ?? ctx.defaultError };
1534
+ }
1535
+ if (iss.code !== "invalid_type")
1536
+ return { message: ctx.defaultError };
1537
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
1538
+ };
1539
+ return { errorMap: customMap, description };
1540
+ }
1541
+ class ZodType {
1542
+ get description() {
1543
+ return this._def.description;
1544
+ }
1545
+ _getType(input) {
1546
+ return getParsedType(input.data);
1547
+ }
1548
+ _getOrReturnCtx(input, ctx) {
1549
+ return (ctx || {
1550
+ common: input.parent.common,
1551
+ data: input.data,
1552
+ parsedType: getParsedType(input.data),
1553
+ schemaErrorMap: this._def.errorMap,
1554
+ path: input.path,
1555
+ parent: input.parent,
1556
+ });
1557
+ }
1558
+ _processInputParams(input) {
1559
+ return {
1560
+ status: new ParseStatus(),
1561
+ ctx: {
1562
+ common: input.parent.common,
1563
+ data: input.data,
1564
+ parsedType: getParsedType(input.data),
1565
+ schemaErrorMap: this._def.errorMap,
1566
+ path: input.path,
1567
+ parent: input.parent,
1568
+ },
1569
+ };
1570
+ }
1571
+ _parseSync(input) {
1572
+ const result = this._parse(input);
1573
+ if (isAsync(result)) {
1574
+ throw new Error("Synchronous parse encountered promise.");
1575
+ }
1576
+ return result;
1577
+ }
1578
+ _parseAsync(input) {
1579
+ const result = this._parse(input);
1580
+ return Promise.resolve(result);
1581
+ }
1582
+ parse(data, params) {
1583
+ const result = this.safeParse(data, params);
1584
+ if (result.success)
1585
+ return result.data;
1586
+ throw result.error;
1587
+ }
1588
+ safeParse(data, params) {
1589
+ const ctx = {
1590
+ common: {
1591
+ issues: [],
1592
+ async: params?.async ?? false,
1593
+ contextualErrorMap: params?.errorMap,
1594
+ },
1595
+ path: params?.path || [],
1596
+ schemaErrorMap: this._def.errorMap,
1597
+ parent: null,
1598
+ data,
1599
+ parsedType: getParsedType(data),
1600
+ };
1601
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1602
+ return handleResult(ctx, result);
1603
+ }
1604
+ "~validate"(data) {
1605
+ const ctx = {
1606
+ common: {
1607
+ issues: [],
1608
+ async: !!this["~standard"].async,
1609
+ },
1610
+ path: [],
1611
+ schemaErrorMap: this._def.errorMap,
1612
+ parent: null,
1613
+ data,
1614
+ parsedType: getParsedType(data),
1615
+ };
1616
+ if (!this["~standard"].async) {
1617
+ try {
1618
+ const result = this._parseSync({ data, path: [], parent: ctx });
1619
+ return isValid(result)
1620
+ ? {
1621
+ value: result.value,
1622
+ }
1623
+ : {
1624
+ issues: ctx.common.issues,
1625
+ };
1626
+ }
1627
+ catch (err) {
1628
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
1629
+ this["~standard"].async = true;
1630
+ }
1631
+ ctx.common = {
1632
+ issues: [],
1633
+ async: true,
1634
+ };
1635
+ }
1636
+ }
1637
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
1638
+ ? {
1639
+ value: result.value,
1640
+ }
1641
+ : {
1642
+ issues: ctx.common.issues,
1643
+ });
1644
+ }
1645
+ async parseAsync(data, params) {
1646
+ const result = await this.safeParseAsync(data, params);
1647
+ if (result.success)
1648
+ return result.data;
1649
+ throw result.error;
1650
+ }
1651
+ async safeParseAsync(data, params) {
1652
+ const ctx = {
1653
+ common: {
1654
+ issues: [],
1655
+ contextualErrorMap: params?.errorMap,
1656
+ async: true,
1657
+ },
1658
+ path: params?.path || [],
1659
+ schemaErrorMap: this._def.errorMap,
1660
+ parent: null,
1661
+ data,
1662
+ parsedType: getParsedType(data),
1663
+ };
1664
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1665
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1666
+ return handleResult(ctx, result);
1667
+ }
1668
+ refine(check, message) {
1669
+ const getIssueProperties = (val) => {
1670
+ if (typeof message === "string" || typeof message === "undefined") {
1671
+ return { message };
1672
+ }
1673
+ else if (typeof message === "function") {
1674
+ return message(val);
1675
+ }
1676
+ else {
1677
+ return message;
1678
+ }
1679
+ };
1680
+ return this._refinement((val, ctx) => {
1681
+ const result = check(val);
1682
+ const setError = () => ctx.addIssue({
1683
+ code: ZodIssueCode.custom,
1684
+ ...getIssueProperties(val),
1685
+ });
1686
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1687
+ return result.then((data) => {
1688
+ if (!data) {
1689
+ setError();
1690
+ return false;
1691
+ }
1692
+ else {
1693
+ return true;
1694
+ }
1695
+ });
1696
+ }
1697
+ if (!result) {
1698
+ setError();
1699
+ return false;
1700
+ }
1701
+ else {
1702
+ return true;
1703
+ }
1704
+ });
1705
+ }
1706
+ refinement(check, refinementData) {
1707
+ return this._refinement((val, ctx) => {
1708
+ if (!check(val)) {
1709
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1710
+ return false;
1711
+ }
1712
+ else {
1713
+ return true;
1714
+ }
1715
+ });
1716
+ }
1717
+ _refinement(refinement) {
1718
+ return new ZodEffects({
1719
+ schema: this,
1720
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1721
+ effect: { type: "refinement", refinement },
1722
+ });
1723
+ }
1724
+ superRefine(refinement) {
1725
+ return this._refinement(refinement);
1726
+ }
1727
+ constructor(def) {
1728
+ /** Alias of safeParseAsync */
1729
+ this.spa = this.safeParseAsync;
1730
+ this._def = def;
1731
+ this.parse = this.parse.bind(this);
1732
+ this.safeParse = this.safeParse.bind(this);
1733
+ this.parseAsync = this.parseAsync.bind(this);
1734
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1735
+ this.spa = this.spa.bind(this);
1736
+ this.refine = this.refine.bind(this);
1737
+ this.refinement = this.refinement.bind(this);
1738
+ this.superRefine = this.superRefine.bind(this);
1739
+ this.optional = this.optional.bind(this);
1740
+ this.nullable = this.nullable.bind(this);
1741
+ this.nullish = this.nullish.bind(this);
1742
+ this.array = this.array.bind(this);
1743
+ this.promise = this.promise.bind(this);
1744
+ this.or = this.or.bind(this);
1745
+ this.and = this.and.bind(this);
1746
+ this.transform = this.transform.bind(this);
1747
+ this.brand = this.brand.bind(this);
1748
+ this.default = this.default.bind(this);
1749
+ this.catch = this.catch.bind(this);
1750
+ this.describe = this.describe.bind(this);
1751
+ this.pipe = this.pipe.bind(this);
1752
+ this.readonly = this.readonly.bind(this);
1753
+ this.isNullable = this.isNullable.bind(this);
1754
+ this.isOptional = this.isOptional.bind(this);
1755
+ this["~standard"] = {
1756
+ version: 1,
1757
+ vendor: "zod",
1758
+ validate: (data) => this["~validate"](data),
1759
+ };
1760
+ }
1761
+ optional() {
1762
+ return ZodOptional.create(this, this._def);
1763
+ }
1764
+ nullable() {
1765
+ return ZodNullable.create(this, this._def);
1766
+ }
1767
+ nullish() {
1768
+ return this.nullable().optional();
1769
+ }
1770
+ array() {
1771
+ return ZodArray.create(this);
1772
+ }
1773
+ promise() {
1774
+ return ZodPromise.create(this, this._def);
1775
+ }
1776
+ or(option) {
1777
+ return ZodUnion.create([this, option], this._def);
1778
+ }
1779
+ and(incoming) {
1780
+ return ZodIntersection.create(this, incoming, this._def);
1781
+ }
1782
+ transform(transform) {
1783
+ return new ZodEffects({
1784
+ ...processCreateParams(this._def),
1785
+ schema: this,
1786
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1787
+ effect: { type: "transform", transform },
1788
+ });
1789
+ }
1790
+ default(def) {
1791
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1792
+ return new ZodDefault({
1793
+ ...processCreateParams(this._def),
1794
+ innerType: this,
1795
+ defaultValue: defaultValueFunc,
1796
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
1797
+ });
1798
+ }
1799
+ brand() {
1800
+ return new ZodBranded({
1801
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1802
+ type: this,
1803
+ ...processCreateParams(this._def),
1804
+ });
1805
+ }
1806
+ catch(def) {
1807
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1808
+ return new ZodCatch({
1809
+ ...processCreateParams(this._def),
1810
+ innerType: this,
1811
+ catchValue: catchValueFunc,
1812
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
1813
+ });
1814
+ }
1815
+ describe(description) {
1816
+ const This = this.constructor;
1817
+ return new This({
1818
+ ...this._def,
1819
+ description,
1820
+ });
1821
+ }
1822
+ pipe(target) {
1823
+ return ZodPipeline.create(this, target);
1824
+ }
1825
+ readonly() {
1826
+ return ZodReadonly.create(this);
1827
+ }
1828
+ isOptional() {
1829
+ return this.safeParse(undefined).success;
1830
+ }
1831
+ isNullable() {
1832
+ return this.safeParse(null).success;
1833
+ }
1834
+ }
1835
+ const cuidRegex = /^c[^\s-]{8,}$/i;
1836
+ const cuid2Regex = /^[0-9a-z]+$/;
1837
+ const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1838
+ // const uuidRegex =
1839
+ // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
1840
+ const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1841
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
1842
+ const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1843
+ const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1844
+ // from https://stackoverflow.com/a/46181/1550155
1845
+ // old version: too slow, didn't support unicode
1846
+ // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
1847
+ //old email regex
1848
+ // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
1849
+ // eslint-disable-next-line
1850
+ // const emailRegex =
1851
+ // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
1852
+ // const emailRegex =
1853
+ // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1854
+ // const emailRegex =
1855
+ // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
1856
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1857
+ // const emailRegex =
1858
+ // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
1859
+ // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
1860
+ const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1861
+ let emojiRegex;
1862
+ // faster, simpler, safer
1863
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1864
+ const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
1865
+ // const ipv6Regex =
1866
+ // /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
1867
+ const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
1868
+ const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1869
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
1870
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1871
+ // https://base64.guru/standards/base64url
1872
+ const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1873
+ // simple
1874
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
1875
+ // no leap year validation
1876
+ // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
1877
+ // with leap year validation
1878
+ const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1879
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
1880
+ function timeRegexSource(args) {
1881
+ let secondsRegexSource = `[0-5]\\d`;
1882
+ if (args.precision) {
1883
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1884
+ }
1885
+ else if (args.precision == null) {
1886
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1887
+ }
1888
+ const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
1889
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1890
+ }
1891
+ function timeRegex(args) {
1892
+ return new RegExp(`^${timeRegexSource(args)}$`);
1893
+ }
1894
+ // Adapted from https://stackoverflow.com/a/3143231
1895
+ function datetimeRegex(args) {
1896
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1897
+ const opts = [];
1898
+ opts.push(args.local ? `Z?` : `Z`);
1899
+ if (args.offset)
1900
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1901
+ regex = `${regex}(${opts.join("|")})`;
1902
+ return new RegExp(`^${regex}$`);
1903
+ }
1904
+ function isValidIP(ip, version) {
1905
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1906
+ return true;
1907
+ }
1908
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1909
+ return true;
1910
+ }
1911
+ return false;
1912
+ }
1913
+ function isValidJWT(jwt, alg) {
1914
+ if (!jwtRegex.test(jwt))
1915
+ return false;
1916
+ try {
1917
+ const [header] = jwt.split(".");
1918
+ if (!header)
1919
+ return false;
1920
+ // Convert base64url to base64
1921
+ const base64 = header
1922
+ .replace(/-/g, "+")
1923
+ .replace(/_/g, "/")
1924
+ .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
1925
+ const decoded = JSON.parse(atob(base64));
1926
+ if (typeof decoded !== "object" || decoded === null)
1927
+ return false;
1928
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1929
+ return false;
1930
+ if (!decoded.alg)
1931
+ return false;
1932
+ if (alg && decoded.alg !== alg)
1933
+ return false;
1934
+ return true;
1935
+ }
1936
+ catch {
1937
+ return false;
1938
+ }
1939
+ }
1940
+ function isValidCidr(ip, version) {
1941
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1942
+ return true;
1943
+ }
1944
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1945
+ return true;
1946
+ }
1947
+ return false;
1948
+ }
1949
+ class ZodString extends ZodType {
1950
+ _parse(input) {
1951
+ if (this._def.coerce) {
1952
+ input.data = String(input.data);
1953
+ }
1954
+ const parsedType = this._getType(input);
1955
+ if (parsedType !== ZodParsedType.string) {
1956
+ const ctx = this._getOrReturnCtx(input);
1957
+ addIssueToContext(ctx, {
1958
+ code: ZodIssueCode.invalid_type,
1959
+ expected: ZodParsedType.string,
1960
+ received: ctx.parsedType,
1961
+ });
1962
+ return INVALID;
1963
+ }
1964
+ const status = new ParseStatus();
1965
+ let ctx = undefined;
1966
+ for (const check of this._def.checks) {
1967
+ if (check.kind === "min") {
1968
+ if (input.data.length < check.value) {
1969
+ ctx = this._getOrReturnCtx(input, ctx);
1970
+ addIssueToContext(ctx, {
1971
+ code: ZodIssueCode.too_small,
1972
+ minimum: check.value,
1973
+ type: "string",
1974
+ inclusive: true,
1975
+ exact: false,
1976
+ message: check.message,
1977
+ });
1978
+ status.dirty();
1979
+ }
1980
+ }
1981
+ else if (check.kind === "max") {
1982
+ if (input.data.length > check.value) {
1983
+ ctx = this._getOrReturnCtx(input, ctx);
1984
+ addIssueToContext(ctx, {
1985
+ code: ZodIssueCode.too_big,
1986
+ maximum: check.value,
1987
+ type: "string",
1988
+ inclusive: true,
1989
+ exact: false,
1990
+ message: check.message,
1991
+ });
1992
+ status.dirty();
1993
+ }
1994
+ }
1995
+ else if (check.kind === "length") {
1996
+ const tooBig = input.data.length > check.value;
1997
+ const tooSmall = input.data.length < check.value;
1998
+ if (tooBig || tooSmall) {
1999
+ ctx = this._getOrReturnCtx(input, ctx);
2000
+ if (tooBig) {
2001
+ addIssueToContext(ctx, {
2002
+ code: ZodIssueCode.too_big,
2003
+ maximum: check.value,
2004
+ type: "string",
2005
+ inclusive: true,
2006
+ exact: true,
2007
+ message: check.message,
2008
+ });
2009
+ }
2010
+ else if (tooSmall) {
2011
+ addIssueToContext(ctx, {
2012
+ code: ZodIssueCode.too_small,
2013
+ minimum: check.value,
2014
+ type: "string",
2015
+ inclusive: true,
2016
+ exact: true,
2017
+ message: check.message,
2018
+ });
2019
+ }
2020
+ status.dirty();
2021
+ }
2022
+ }
2023
+ else if (check.kind === "email") {
2024
+ if (!emailRegex.test(input.data)) {
2025
+ ctx = this._getOrReturnCtx(input, ctx);
2026
+ addIssueToContext(ctx, {
2027
+ validation: "email",
2028
+ code: ZodIssueCode.invalid_string,
2029
+ message: check.message,
2030
+ });
2031
+ status.dirty();
2032
+ }
2033
+ }
2034
+ else if (check.kind === "emoji") {
2035
+ if (!emojiRegex) {
2036
+ emojiRegex = new RegExp(_emojiRegex, "u");
2037
+ }
2038
+ if (!emojiRegex.test(input.data)) {
2039
+ ctx = this._getOrReturnCtx(input, ctx);
2040
+ addIssueToContext(ctx, {
2041
+ validation: "emoji",
2042
+ code: ZodIssueCode.invalid_string,
2043
+ message: check.message,
2044
+ });
2045
+ status.dirty();
2046
+ }
2047
+ }
2048
+ else if (check.kind === "uuid") {
2049
+ if (!uuidRegex.test(input.data)) {
2050
+ ctx = this._getOrReturnCtx(input, ctx);
2051
+ addIssueToContext(ctx, {
2052
+ validation: "uuid",
2053
+ code: ZodIssueCode.invalid_string,
2054
+ message: check.message,
2055
+ });
2056
+ status.dirty();
2057
+ }
2058
+ }
2059
+ else if (check.kind === "nanoid") {
2060
+ if (!nanoidRegex.test(input.data)) {
2061
+ ctx = this._getOrReturnCtx(input, ctx);
2062
+ addIssueToContext(ctx, {
2063
+ validation: "nanoid",
2064
+ code: ZodIssueCode.invalid_string,
2065
+ message: check.message,
2066
+ });
2067
+ status.dirty();
2068
+ }
2069
+ }
2070
+ else if (check.kind === "cuid") {
2071
+ if (!cuidRegex.test(input.data)) {
2072
+ ctx = this._getOrReturnCtx(input, ctx);
2073
+ addIssueToContext(ctx, {
2074
+ validation: "cuid",
2075
+ code: ZodIssueCode.invalid_string,
2076
+ message: check.message,
2077
+ });
2078
+ status.dirty();
2079
+ }
2080
+ }
2081
+ else if (check.kind === "cuid2") {
2082
+ if (!cuid2Regex.test(input.data)) {
2083
+ ctx = this._getOrReturnCtx(input, ctx);
2084
+ addIssueToContext(ctx, {
2085
+ validation: "cuid2",
2086
+ code: ZodIssueCode.invalid_string,
2087
+ message: check.message,
2088
+ });
2089
+ status.dirty();
2090
+ }
2091
+ }
2092
+ else if (check.kind === "ulid") {
2093
+ if (!ulidRegex.test(input.data)) {
2094
+ ctx = this._getOrReturnCtx(input, ctx);
2095
+ addIssueToContext(ctx, {
2096
+ validation: "ulid",
2097
+ code: ZodIssueCode.invalid_string,
2098
+ message: check.message,
2099
+ });
2100
+ status.dirty();
2101
+ }
2102
+ }
2103
+ else if (check.kind === "url") {
2104
+ try {
2105
+ new URL(input.data);
2106
+ }
2107
+ catch {
2108
+ ctx = this._getOrReturnCtx(input, ctx);
2109
+ addIssueToContext(ctx, {
2110
+ validation: "url",
2111
+ code: ZodIssueCode.invalid_string,
2112
+ message: check.message,
2113
+ });
2114
+ status.dirty();
2115
+ }
2116
+ }
2117
+ else if (check.kind === "regex") {
2118
+ check.regex.lastIndex = 0;
2119
+ const testResult = check.regex.test(input.data);
2120
+ if (!testResult) {
2121
+ ctx = this._getOrReturnCtx(input, ctx);
2122
+ addIssueToContext(ctx, {
2123
+ validation: "regex",
2124
+ code: ZodIssueCode.invalid_string,
2125
+ message: check.message,
2126
+ });
2127
+ status.dirty();
2128
+ }
2129
+ }
2130
+ else if (check.kind === "trim") {
2131
+ input.data = input.data.trim();
2132
+ }
2133
+ else if (check.kind === "includes") {
2134
+ if (!input.data.includes(check.value, check.position)) {
2135
+ ctx = this._getOrReturnCtx(input, ctx);
2136
+ addIssueToContext(ctx, {
2137
+ code: ZodIssueCode.invalid_string,
2138
+ validation: { includes: check.value, position: check.position },
2139
+ message: check.message,
2140
+ });
2141
+ status.dirty();
2142
+ }
2143
+ }
2144
+ else if (check.kind === "toLowerCase") {
2145
+ input.data = input.data.toLowerCase();
2146
+ }
2147
+ else if (check.kind === "toUpperCase") {
2148
+ input.data = input.data.toUpperCase();
2149
+ }
2150
+ else if (check.kind === "startsWith") {
2151
+ if (!input.data.startsWith(check.value)) {
2152
+ ctx = this._getOrReturnCtx(input, ctx);
2153
+ addIssueToContext(ctx, {
2154
+ code: ZodIssueCode.invalid_string,
2155
+ validation: { startsWith: check.value },
2156
+ message: check.message,
2157
+ });
2158
+ status.dirty();
2159
+ }
2160
+ }
2161
+ else if (check.kind === "endsWith") {
2162
+ if (!input.data.endsWith(check.value)) {
2163
+ ctx = this._getOrReturnCtx(input, ctx);
2164
+ addIssueToContext(ctx, {
2165
+ code: ZodIssueCode.invalid_string,
2166
+ validation: { endsWith: check.value },
2167
+ message: check.message,
2168
+ });
2169
+ status.dirty();
2170
+ }
2171
+ }
2172
+ else if (check.kind === "datetime") {
2173
+ const regex = datetimeRegex(check);
2174
+ if (!regex.test(input.data)) {
2175
+ ctx = this._getOrReturnCtx(input, ctx);
2176
+ addIssueToContext(ctx, {
2177
+ code: ZodIssueCode.invalid_string,
2178
+ validation: "datetime",
2179
+ message: check.message,
2180
+ });
2181
+ status.dirty();
2182
+ }
2183
+ }
2184
+ else if (check.kind === "date") {
2185
+ const regex = dateRegex;
2186
+ if (!regex.test(input.data)) {
2187
+ ctx = this._getOrReturnCtx(input, ctx);
2188
+ addIssueToContext(ctx, {
2189
+ code: ZodIssueCode.invalid_string,
2190
+ validation: "date",
2191
+ message: check.message,
2192
+ });
2193
+ status.dirty();
2194
+ }
2195
+ }
2196
+ else if (check.kind === "time") {
2197
+ const regex = timeRegex(check);
2198
+ if (!regex.test(input.data)) {
2199
+ ctx = this._getOrReturnCtx(input, ctx);
2200
+ addIssueToContext(ctx, {
2201
+ code: ZodIssueCode.invalid_string,
2202
+ validation: "time",
2203
+ message: check.message,
2204
+ });
2205
+ status.dirty();
2206
+ }
2207
+ }
2208
+ else if (check.kind === "duration") {
2209
+ if (!durationRegex.test(input.data)) {
2210
+ ctx = this._getOrReturnCtx(input, ctx);
2211
+ addIssueToContext(ctx, {
2212
+ validation: "duration",
2213
+ code: ZodIssueCode.invalid_string,
2214
+ message: check.message,
2215
+ });
2216
+ status.dirty();
2217
+ }
2218
+ }
2219
+ else if (check.kind === "ip") {
2220
+ if (!isValidIP(input.data, check.version)) {
2221
+ ctx = this._getOrReturnCtx(input, ctx);
2222
+ addIssueToContext(ctx, {
2223
+ validation: "ip",
2224
+ code: ZodIssueCode.invalid_string,
2225
+ message: check.message,
2226
+ });
2227
+ status.dirty();
2228
+ }
2229
+ }
2230
+ else if (check.kind === "jwt") {
2231
+ if (!isValidJWT(input.data, check.alg)) {
2232
+ ctx = this._getOrReturnCtx(input, ctx);
2233
+ addIssueToContext(ctx, {
2234
+ validation: "jwt",
2235
+ code: ZodIssueCode.invalid_string,
2236
+ message: check.message,
2237
+ });
2238
+ status.dirty();
2239
+ }
2240
+ }
2241
+ else if (check.kind === "cidr") {
2242
+ if (!isValidCidr(input.data, check.version)) {
2243
+ ctx = this._getOrReturnCtx(input, ctx);
2244
+ addIssueToContext(ctx, {
2245
+ validation: "cidr",
2246
+ code: ZodIssueCode.invalid_string,
2247
+ message: check.message,
2248
+ });
2249
+ status.dirty();
2250
+ }
2251
+ }
2252
+ else if (check.kind === "base64") {
2253
+ if (!base64Regex.test(input.data)) {
2254
+ ctx = this._getOrReturnCtx(input, ctx);
2255
+ addIssueToContext(ctx, {
2256
+ validation: "base64",
2257
+ code: ZodIssueCode.invalid_string,
2258
+ message: check.message,
2259
+ });
2260
+ status.dirty();
2261
+ }
2262
+ }
2263
+ else if (check.kind === "base64url") {
2264
+ if (!base64urlRegex.test(input.data)) {
2265
+ ctx = this._getOrReturnCtx(input, ctx);
2266
+ addIssueToContext(ctx, {
2267
+ validation: "base64url",
2268
+ code: ZodIssueCode.invalid_string,
2269
+ message: check.message,
2270
+ });
2271
+ status.dirty();
2272
+ }
2273
+ }
2274
+ else {
2275
+ util.assertNever(check);
2276
+ }
2277
+ }
2278
+ return { status: status.value, value: input.data };
2279
+ }
2280
+ _regex(regex, validation, message) {
2281
+ return this.refinement((data) => regex.test(data), {
2282
+ validation,
2283
+ code: ZodIssueCode.invalid_string,
2284
+ ...errorUtil.errToObj(message),
2285
+ });
2286
+ }
2287
+ _addCheck(check) {
2288
+ return new ZodString({
2289
+ ...this._def,
2290
+ checks: [...this._def.checks, check],
2291
+ });
2292
+ }
2293
+ email(message) {
2294
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
2295
+ }
2296
+ url(message) {
2297
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
2298
+ }
2299
+ emoji(message) {
2300
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
2301
+ }
2302
+ uuid(message) {
2303
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
2304
+ }
2305
+ nanoid(message) {
2306
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
2307
+ }
2308
+ cuid(message) {
2309
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
2310
+ }
2311
+ cuid2(message) {
2312
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
2313
+ }
2314
+ ulid(message) {
2315
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
2316
+ }
2317
+ base64(message) {
2318
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
2319
+ }
2320
+ base64url(message) {
2321
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
2322
+ return this._addCheck({
2323
+ kind: "base64url",
2324
+ ...errorUtil.errToObj(message),
2325
+ });
2326
+ }
2327
+ jwt(options) {
2328
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
2329
+ }
2330
+ ip(options) {
2331
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
2332
+ }
2333
+ cidr(options) {
2334
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
2335
+ }
2336
+ datetime(options) {
2337
+ if (typeof options === "string") {
2338
+ return this._addCheck({
2339
+ kind: "datetime",
2340
+ precision: null,
2341
+ offset: false,
2342
+ local: false,
2343
+ message: options,
2344
+ });
2345
+ }
2346
+ return this._addCheck({
2347
+ kind: "datetime",
2348
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2349
+ offset: options?.offset ?? false,
2350
+ local: options?.local ?? false,
2351
+ ...errorUtil.errToObj(options?.message),
2352
+ });
2353
+ }
2354
+ date(message) {
2355
+ return this._addCheck({ kind: "date", message });
2356
+ }
2357
+ time(options) {
2358
+ if (typeof options === "string") {
2359
+ return this._addCheck({
2360
+ kind: "time",
2361
+ precision: null,
2362
+ message: options,
2363
+ });
2364
+ }
2365
+ return this._addCheck({
2366
+ kind: "time",
2367
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2368
+ ...errorUtil.errToObj(options?.message),
2369
+ });
2370
+ }
2371
+ duration(message) {
2372
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
2373
+ }
2374
+ regex(regex, message) {
2375
+ return this._addCheck({
2376
+ kind: "regex",
2377
+ regex: regex,
2378
+ ...errorUtil.errToObj(message),
2379
+ });
2380
+ }
2381
+ includes(value, options) {
2382
+ return this._addCheck({
2383
+ kind: "includes",
2384
+ value: value,
2385
+ position: options?.position,
2386
+ ...errorUtil.errToObj(options?.message),
2387
+ });
2388
+ }
2389
+ startsWith(value, message) {
2390
+ return this._addCheck({
2391
+ kind: "startsWith",
2392
+ value: value,
2393
+ ...errorUtil.errToObj(message),
2394
+ });
2395
+ }
2396
+ endsWith(value, message) {
2397
+ return this._addCheck({
2398
+ kind: "endsWith",
2399
+ value: value,
2400
+ ...errorUtil.errToObj(message),
2401
+ });
2402
+ }
2403
+ min(minLength, message) {
2404
+ return this._addCheck({
2405
+ kind: "min",
2406
+ value: minLength,
2407
+ ...errorUtil.errToObj(message),
2408
+ });
2409
+ }
2410
+ max(maxLength, message) {
2411
+ return this._addCheck({
2412
+ kind: "max",
2413
+ value: maxLength,
2414
+ ...errorUtil.errToObj(message),
2415
+ });
2416
+ }
2417
+ length(len, message) {
2418
+ return this._addCheck({
2419
+ kind: "length",
2420
+ value: len,
2421
+ ...errorUtil.errToObj(message),
2422
+ });
2423
+ }
2424
+ /**
2425
+ * Equivalent to `.min(1)`
2426
+ */
2427
+ nonempty(message) {
2428
+ return this.min(1, errorUtil.errToObj(message));
2429
+ }
2430
+ trim() {
2431
+ return new ZodString({
2432
+ ...this._def,
2433
+ checks: [...this._def.checks, { kind: "trim" }],
2434
+ });
2435
+ }
2436
+ toLowerCase() {
2437
+ return new ZodString({
2438
+ ...this._def,
2439
+ checks: [...this._def.checks, { kind: "toLowerCase" }],
2440
+ });
2441
+ }
2442
+ toUpperCase() {
2443
+ return new ZodString({
2444
+ ...this._def,
2445
+ checks: [...this._def.checks, { kind: "toUpperCase" }],
2446
+ });
2447
+ }
2448
+ get isDatetime() {
2449
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
2450
+ }
2451
+ get isDate() {
2452
+ return !!this._def.checks.find((ch) => ch.kind === "date");
2453
+ }
2454
+ get isTime() {
2455
+ return !!this._def.checks.find((ch) => ch.kind === "time");
2456
+ }
2457
+ get isDuration() {
2458
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
2459
+ }
2460
+ get isEmail() {
2461
+ return !!this._def.checks.find((ch) => ch.kind === "email");
2462
+ }
2463
+ get isURL() {
2464
+ return !!this._def.checks.find((ch) => ch.kind === "url");
2465
+ }
2466
+ get isEmoji() {
2467
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
2468
+ }
2469
+ get isUUID() {
2470
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
2471
+ }
2472
+ get isNANOID() {
2473
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
2474
+ }
2475
+ get isCUID() {
2476
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
2477
+ }
2478
+ get isCUID2() {
2479
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
2480
+ }
2481
+ get isULID() {
2482
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
2483
+ }
2484
+ get isIP() {
2485
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
2486
+ }
2487
+ get isCIDR() {
2488
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
2489
+ }
2490
+ get isBase64() {
2491
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
2492
+ }
2493
+ get isBase64url() {
2494
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
2495
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
2496
+ }
2497
+ get minLength() {
2498
+ let min = null;
2499
+ for (const ch of this._def.checks) {
2500
+ if (ch.kind === "min") {
2501
+ if (min === null || ch.value > min)
2502
+ min = ch.value;
2503
+ }
2504
+ }
2505
+ return min;
2506
+ }
2507
+ get maxLength() {
2508
+ let max = null;
2509
+ for (const ch of this._def.checks) {
2510
+ if (ch.kind === "max") {
2511
+ if (max === null || ch.value < max)
2512
+ max = ch.value;
2513
+ }
2514
+ }
2515
+ return max;
2516
+ }
2517
+ }
2518
+ ZodString.create = (params) => {
2519
+ return new ZodString({
2520
+ checks: [],
2521
+ typeName: ZodFirstPartyTypeKind.ZodString,
2522
+ coerce: params?.coerce ?? false,
2523
+ ...processCreateParams(params),
2524
+ });
2525
+ };
2526
+ // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
2527
+ function floatSafeRemainder(val, step) {
2528
+ const valDecCount = (val.toString().split(".")[1] || "").length;
2529
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
2530
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
2531
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
2532
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
2533
+ return (valInt % stepInt) / 10 ** decCount;
2534
+ }
2535
+ class ZodNumber extends ZodType {
2536
+ constructor() {
2537
+ super(...arguments);
2538
+ this.min = this.gte;
2539
+ this.max = this.lte;
2540
+ this.step = this.multipleOf;
2541
+ }
2542
+ _parse(input) {
2543
+ if (this._def.coerce) {
2544
+ input.data = Number(input.data);
2545
+ }
2546
+ const parsedType = this._getType(input);
2547
+ if (parsedType !== ZodParsedType.number) {
2548
+ const ctx = this._getOrReturnCtx(input);
2549
+ addIssueToContext(ctx, {
2550
+ code: ZodIssueCode.invalid_type,
2551
+ expected: ZodParsedType.number,
2552
+ received: ctx.parsedType,
2553
+ });
2554
+ return INVALID;
2555
+ }
2556
+ let ctx = undefined;
2557
+ const status = new ParseStatus();
2558
+ for (const check of this._def.checks) {
2559
+ if (check.kind === "int") {
2560
+ if (!util.isInteger(input.data)) {
2561
+ ctx = this._getOrReturnCtx(input, ctx);
2562
+ addIssueToContext(ctx, {
2563
+ code: ZodIssueCode.invalid_type,
2564
+ expected: "integer",
2565
+ received: "float",
2566
+ message: check.message,
2567
+ });
2568
+ status.dirty();
2569
+ }
2570
+ }
2571
+ else if (check.kind === "min") {
2572
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2573
+ if (tooSmall) {
2574
+ ctx = this._getOrReturnCtx(input, ctx);
2575
+ addIssueToContext(ctx, {
2576
+ code: ZodIssueCode.too_small,
2577
+ minimum: check.value,
2578
+ type: "number",
2579
+ inclusive: check.inclusive,
2580
+ exact: false,
2581
+ message: check.message,
2582
+ });
2583
+ status.dirty();
2584
+ }
2585
+ }
2586
+ else if (check.kind === "max") {
2587
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2588
+ if (tooBig) {
2589
+ ctx = this._getOrReturnCtx(input, ctx);
2590
+ addIssueToContext(ctx, {
2591
+ code: ZodIssueCode.too_big,
2592
+ maximum: check.value,
2593
+ type: "number",
2594
+ inclusive: check.inclusive,
2595
+ exact: false,
2596
+ message: check.message,
2597
+ });
2598
+ status.dirty();
2599
+ }
2600
+ }
2601
+ else if (check.kind === "multipleOf") {
2602
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
2603
+ ctx = this._getOrReturnCtx(input, ctx);
2604
+ addIssueToContext(ctx, {
2605
+ code: ZodIssueCode.not_multiple_of,
2606
+ multipleOf: check.value,
2607
+ message: check.message,
2608
+ });
2609
+ status.dirty();
2610
+ }
2611
+ }
2612
+ else if (check.kind === "finite") {
2613
+ if (!Number.isFinite(input.data)) {
2614
+ ctx = this._getOrReturnCtx(input, ctx);
2615
+ addIssueToContext(ctx, {
2616
+ code: ZodIssueCode.not_finite,
2617
+ message: check.message,
2618
+ });
2619
+ status.dirty();
2620
+ }
2621
+ }
2622
+ else {
2623
+ util.assertNever(check);
2624
+ }
2625
+ }
2626
+ return { status: status.value, value: input.data };
2627
+ }
2628
+ gte(value, message) {
2629
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2630
+ }
2631
+ gt(value, message) {
2632
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2633
+ }
2634
+ lte(value, message) {
2635
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2636
+ }
2637
+ lt(value, message) {
2638
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2639
+ }
2640
+ setLimit(kind, value, inclusive, message) {
2641
+ return new ZodNumber({
2642
+ ...this._def,
2643
+ checks: [
2644
+ ...this._def.checks,
2645
+ {
2646
+ kind,
2647
+ value,
2648
+ inclusive,
2649
+ message: errorUtil.toString(message),
2650
+ },
2651
+ ],
2652
+ });
2653
+ }
2654
+ _addCheck(check) {
2655
+ return new ZodNumber({
2656
+ ...this._def,
2657
+ checks: [...this._def.checks, check],
2658
+ });
2659
+ }
2660
+ int(message) {
2661
+ return this._addCheck({
2662
+ kind: "int",
2663
+ message: errorUtil.toString(message),
2664
+ });
2665
+ }
2666
+ positive(message) {
2667
+ return this._addCheck({
2668
+ kind: "min",
2669
+ value: 0,
2670
+ inclusive: false,
2671
+ message: errorUtil.toString(message),
2672
+ });
2673
+ }
2674
+ negative(message) {
2675
+ return this._addCheck({
2676
+ kind: "max",
2677
+ value: 0,
2678
+ inclusive: false,
2679
+ message: errorUtil.toString(message),
2680
+ });
2681
+ }
2682
+ nonpositive(message) {
2683
+ return this._addCheck({
2684
+ kind: "max",
2685
+ value: 0,
2686
+ inclusive: true,
2687
+ message: errorUtil.toString(message),
2688
+ });
2689
+ }
2690
+ nonnegative(message) {
2691
+ return this._addCheck({
2692
+ kind: "min",
2693
+ value: 0,
2694
+ inclusive: true,
2695
+ message: errorUtil.toString(message),
2696
+ });
2697
+ }
2698
+ multipleOf(value, message) {
2699
+ return this._addCheck({
2700
+ kind: "multipleOf",
2701
+ value: value,
2702
+ message: errorUtil.toString(message),
2703
+ });
2704
+ }
2705
+ finite(message) {
2706
+ return this._addCheck({
2707
+ kind: "finite",
2708
+ message: errorUtil.toString(message),
2709
+ });
2710
+ }
2711
+ safe(message) {
2712
+ return this._addCheck({
2713
+ kind: "min",
2714
+ inclusive: true,
2715
+ value: Number.MIN_SAFE_INTEGER,
2716
+ message: errorUtil.toString(message),
2717
+ })._addCheck({
2718
+ kind: "max",
2719
+ inclusive: true,
2720
+ value: Number.MAX_SAFE_INTEGER,
2721
+ message: errorUtil.toString(message),
2722
+ });
2723
+ }
2724
+ get minValue() {
2725
+ let min = null;
2726
+ for (const ch of this._def.checks) {
2727
+ if (ch.kind === "min") {
2728
+ if (min === null || ch.value > min)
2729
+ min = ch.value;
2730
+ }
2731
+ }
2732
+ return min;
2733
+ }
2734
+ get maxValue() {
2735
+ let max = null;
2736
+ for (const ch of this._def.checks) {
2737
+ if (ch.kind === "max") {
2738
+ if (max === null || ch.value < max)
2739
+ max = ch.value;
2740
+ }
2741
+ }
2742
+ return max;
2743
+ }
2744
+ get isInt() {
2745
+ return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value)));
2746
+ }
2747
+ get isFinite() {
2748
+ let max = null;
2749
+ let min = null;
2750
+ for (const ch of this._def.checks) {
2751
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2752
+ return true;
2753
+ }
2754
+ else if (ch.kind === "min") {
2755
+ if (min === null || ch.value > min)
2756
+ min = ch.value;
2757
+ }
2758
+ else if (ch.kind === "max") {
2759
+ if (max === null || ch.value < max)
2760
+ max = ch.value;
2761
+ }
2762
+ }
2763
+ return Number.isFinite(min) && Number.isFinite(max);
2764
+ }
2765
+ }
2766
+ ZodNumber.create = (params) => {
2767
+ return new ZodNumber({
2768
+ checks: [],
2769
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
2770
+ coerce: params?.coerce || false,
2771
+ ...processCreateParams(params),
2772
+ });
2773
+ };
2774
+ class ZodBigInt extends ZodType {
2775
+ constructor() {
2776
+ super(...arguments);
2777
+ this.min = this.gte;
2778
+ this.max = this.lte;
2779
+ }
2780
+ _parse(input) {
2781
+ if (this._def.coerce) {
2782
+ try {
2783
+ input.data = BigInt(input.data);
2784
+ }
2785
+ catch {
2786
+ return this._getInvalidInput(input);
2787
+ }
2788
+ }
2789
+ const parsedType = this._getType(input);
2790
+ if (parsedType !== ZodParsedType.bigint) {
2791
+ return this._getInvalidInput(input);
2792
+ }
2793
+ let ctx = undefined;
2794
+ const status = new ParseStatus();
2795
+ for (const check of this._def.checks) {
2796
+ if (check.kind === "min") {
2797
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2798
+ if (tooSmall) {
2799
+ ctx = this._getOrReturnCtx(input, ctx);
2800
+ addIssueToContext(ctx, {
2801
+ code: ZodIssueCode.too_small,
2802
+ type: "bigint",
2803
+ minimum: check.value,
2804
+ inclusive: check.inclusive,
2805
+ message: check.message,
2806
+ });
2807
+ status.dirty();
2808
+ }
2809
+ }
2810
+ else if (check.kind === "max") {
2811
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2812
+ if (tooBig) {
2813
+ ctx = this._getOrReturnCtx(input, ctx);
2814
+ addIssueToContext(ctx, {
2815
+ code: ZodIssueCode.too_big,
2816
+ type: "bigint",
2817
+ maximum: check.value,
2818
+ inclusive: check.inclusive,
2819
+ message: check.message,
2820
+ });
2821
+ status.dirty();
2822
+ }
2823
+ }
2824
+ else if (check.kind === "multipleOf") {
2825
+ if (input.data % check.value !== BigInt(0)) {
2826
+ ctx = this._getOrReturnCtx(input, ctx);
2827
+ addIssueToContext(ctx, {
2828
+ code: ZodIssueCode.not_multiple_of,
2829
+ multipleOf: check.value,
2830
+ message: check.message,
2831
+ });
2832
+ status.dirty();
2833
+ }
2834
+ }
2835
+ else {
2836
+ util.assertNever(check);
2837
+ }
2838
+ }
2839
+ return { status: status.value, value: input.data };
2840
+ }
2841
+ _getInvalidInput(input) {
2842
+ const ctx = this._getOrReturnCtx(input);
2843
+ addIssueToContext(ctx, {
2844
+ code: ZodIssueCode.invalid_type,
2845
+ expected: ZodParsedType.bigint,
2846
+ received: ctx.parsedType,
2847
+ });
2848
+ return INVALID;
2849
+ }
2850
+ gte(value, message) {
2851
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2852
+ }
2853
+ gt(value, message) {
2854
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2855
+ }
2856
+ lte(value, message) {
2857
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2858
+ }
2859
+ lt(value, message) {
2860
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2861
+ }
2862
+ setLimit(kind, value, inclusive, message) {
2863
+ return new ZodBigInt({
2864
+ ...this._def,
2865
+ checks: [
2866
+ ...this._def.checks,
2867
+ {
2868
+ kind,
2869
+ value,
2870
+ inclusive,
2871
+ message: errorUtil.toString(message),
2872
+ },
2873
+ ],
2874
+ });
2875
+ }
2876
+ _addCheck(check) {
2877
+ return new ZodBigInt({
2878
+ ...this._def,
2879
+ checks: [...this._def.checks, check],
2880
+ });
2881
+ }
2882
+ positive(message) {
2883
+ return this._addCheck({
2884
+ kind: "min",
2885
+ value: BigInt(0),
2886
+ inclusive: false,
2887
+ message: errorUtil.toString(message),
2888
+ });
2889
+ }
2890
+ negative(message) {
2891
+ return this._addCheck({
2892
+ kind: "max",
2893
+ value: BigInt(0),
2894
+ inclusive: false,
2895
+ message: errorUtil.toString(message),
2896
+ });
2897
+ }
2898
+ nonpositive(message) {
2899
+ return this._addCheck({
2900
+ kind: "max",
2901
+ value: BigInt(0),
2902
+ inclusive: true,
2903
+ message: errorUtil.toString(message),
2904
+ });
2905
+ }
2906
+ nonnegative(message) {
2907
+ return this._addCheck({
2908
+ kind: "min",
2909
+ value: BigInt(0),
2910
+ inclusive: true,
2911
+ message: errorUtil.toString(message),
2912
+ });
2913
+ }
2914
+ multipleOf(value, message) {
2915
+ return this._addCheck({
2916
+ kind: "multipleOf",
2917
+ value,
2918
+ message: errorUtil.toString(message),
2919
+ });
2920
+ }
2921
+ get minValue() {
2922
+ let min = null;
2923
+ for (const ch of this._def.checks) {
2924
+ if (ch.kind === "min") {
2925
+ if (min === null || ch.value > min)
2926
+ min = ch.value;
2927
+ }
2928
+ }
2929
+ return min;
2930
+ }
2931
+ get maxValue() {
2932
+ let max = null;
2933
+ for (const ch of this._def.checks) {
2934
+ if (ch.kind === "max") {
2935
+ if (max === null || ch.value < max)
2936
+ max = ch.value;
2937
+ }
2938
+ }
2939
+ return max;
2940
+ }
2941
+ }
2942
+ ZodBigInt.create = (params) => {
2943
+ return new ZodBigInt({
2944
+ checks: [],
2945
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2946
+ coerce: params?.coerce ?? false,
2947
+ ...processCreateParams(params),
2948
+ });
2949
+ };
2950
+ class ZodBoolean extends ZodType {
2951
+ _parse(input) {
2952
+ if (this._def.coerce) {
2953
+ input.data = Boolean(input.data);
2954
+ }
2955
+ const parsedType = this._getType(input);
2956
+ if (parsedType !== ZodParsedType.boolean) {
2957
+ const ctx = this._getOrReturnCtx(input);
2958
+ addIssueToContext(ctx, {
2959
+ code: ZodIssueCode.invalid_type,
2960
+ expected: ZodParsedType.boolean,
2961
+ received: ctx.parsedType,
2962
+ });
2963
+ return INVALID;
2964
+ }
2965
+ return OK(input.data);
2966
+ }
2967
+ }
2968
+ ZodBoolean.create = (params) => {
2969
+ return new ZodBoolean({
2970
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2971
+ coerce: params?.coerce || false,
2972
+ ...processCreateParams(params),
2973
+ });
2974
+ };
2975
+ class ZodDate extends ZodType {
2976
+ _parse(input) {
2977
+ if (this._def.coerce) {
2978
+ input.data = new Date(input.data);
2979
+ }
2980
+ const parsedType = this._getType(input);
2981
+ if (parsedType !== ZodParsedType.date) {
2982
+ const ctx = this._getOrReturnCtx(input);
2983
+ addIssueToContext(ctx, {
2984
+ code: ZodIssueCode.invalid_type,
2985
+ expected: ZodParsedType.date,
2986
+ received: ctx.parsedType,
2987
+ });
2988
+ return INVALID;
2989
+ }
2990
+ if (Number.isNaN(input.data.getTime())) {
2991
+ const ctx = this._getOrReturnCtx(input);
2992
+ addIssueToContext(ctx, {
2993
+ code: ZodIssueCode.invalid_date,
2994
+ });
2995
+ return INVALID;
2996
+ }
2997
+ const status = new ParseStatus();
2998
+ let ctx = undefined;
2999
+ for (const check of this._def.checks) {
3000
+ if (check.kind === "min") {
3001
+ if (input.data.getTime() < check.value) {
3002
+ ctx = this._getOrReturnCtx(input, ctx);
3003
+ addIssueToContext(ctx, {
3004
+ code: ZodIssueCode.too_small,
3005
+ message: check.message,
3006
+ inclusive: true,
3007
+ exact: false,
3008
+ minimum: check.value,
3009
+ type: "date",
3010
+ });
3011
+ status.dirty();
3012
+ }
3013
+ }
3014
+ else if (check.kind === "max") {
3015
+ if (input.data.getTime() > check.value) {
3016
+ ctx = this._getOrReturnCtx(input, ctx);
3017
+ addIssueToContext(ctx, {
3018
+ code: ZodIssueCode.too_big,
3019
+ message: check.message,
3020
+ inclusive: true,
3021
+ exact: false,
3022
+ maximum: check.value,
3023
+ type: "date",
3024
+ });
3025
+ status.dirty();
3026
+ }
3027
+ }
3028
+ else {
3029
+ util.assertNever(check);
3030
+ }
3031
+ }
3032
+ return {
3033
+ status: status.value,
3034
+ value: new Date(input.data.getTime()),
3035
+ };
3036
+ }
3037
+ _addCheck(check) {
3038
+ return new ZodDate({
3039
+ ...this._def,
3040
+ checks: [...this._def.checks, check],
3041
+ });
3042
+ }
3043
+ min(minDate, message) {
3044
+ return this._addCheck({
3045
+ kind: "min",
3046
+ value: minDate.getTime(),
3047
+ message: errorUtil.toString(message),
3048
+ });
3049
+ }
3050
+ max(maxDate, message) {
3051
+ return this._addCheck({
3052
+ kind: "max",
3053
+ value: maxDate.getTime(),
3054
+ message: errorUtil.toString(message),
3055
+ });
3056
+ }
3057
+ get minDate() {
3058
+ let min = null;
3059
+ for (const ch of this._def.checks) {
3060
+ if (ch.kind === "min") {
3061
+ if (min === null || ch.value > min)
3062
+ min = ch.value;
3063
+ }
3064
+ }
3065
+ return min != null ? new Date(min) : null;
3066
+ }
3067
+ get maxDate() {
3068
+ let max = null;
3069
+ for (const ch of this._def.checks) {
3070
+ if (ch.kind === "max") {
3071
+ if (max === null || ch.value < max)
3072
+ max = ch.value;
3073
+ }
3074
+ }
3075
+ return max != null ? new Date(max) : null;
3076
+ }
3077
+ }
3078
+ ZodDate.create = (params) => {
3079
+ return new ZodDate({
3080
+ checks: [],
3081
+ coerce: params?.coerce || false,
3082
+ typeName: ZodFirstPartyTypeKind.ZodDate,
3083
+ ...processCreateParams(params),
3084
+ });
3085
+ };
3086
+ class ZodSymbol extends ZodType {
3087
+ _parse(input) {
3088
+ const parsedType = this._getType(input);
3089
+ if (parsedType !== ZodParsedType.symbol) {
3090
+ const ctx = this._getOrReturnCtx(input);
3091
+ addIssueToContext(ctx, {
3092
+ code: ZodIssueCode.invalid_type,
3093
+ expected: ZodParsedType.symbol,
3094
+ received: ctx.parsedType,
3095
+ });
3096
+ return INVALID;
3097
+ }
3098
+ return OK(input.data);
3099
+ }
3100
+ }
3101
+ ZodSymbol.create = (params) => {
3102
+ return new ZodSymbol({
3103
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
3104
+ ...processCreateParams(params),
3105
+ });
3106
+ };
3107
+ class ZodUndefined extends ZodType {
3108
+ _parse(input) {
3109
+ const parsedType = this._getType(input);
3110
+ if (parsedType !== ZodParsedType.undefined) {
3111
+ const ctx = this._getOrReturnCtx(input);
3112
+ addIssueToContext(ctx, {
3113
+ code: ZodIssueCode.invalid_type,
3114
+ expected: ZodParsedType.undefined,
3115
+ received: ctx.parsedType,
3116
+ });
3117
+ return INVALID;
3118
+ }
3119
+ return OK(input.data);
3120
+ }
3121
+ }
3122
+ ZodUndefined.create = (params) => {
3123
+ return new ZodUndefined({
3124
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
3125
+ ...processCreateParams(params),
3126
+ });
3127
+ };
3128
+ class ZodNull extends ZodType {
3129
+ _parse(input) {
3130
+ const parsedType = this._getType(input);
3131
+ if (parsedType !== ZodParsedType.null) {
3132
+ const ctx = this._getOrReturnCtx(input);
3133
+ addIssueToContext(ctx, {
3134
+ code: ZodIssueCode.invalid_type,
3135
+ expected: ZodParsedType.null,
3136
+ received: ctx.parsedType,
3137
+ });
3138
+ return INVALID;
3139
+ }
3140
+ return OK(input.data);
3141
+ }
3142
+ }
3143
+ ZodNull.create = (params) => {
3144
+ return new ZodNull({
3145
+ typeName: ZodFirstPartyTypeKind.ZodNull,
3146
+ ...processCreateParams(params),
3147
+ });
3148
+ };
3149
+ class ZodAny extends ZodType {
3150
+ constructor() {
3151
+ super(...arguments);
3152
+ // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
3153
+ this._any = true;
3154
+ }
3155
+ _parse(input) {
3156
+ return OK(input.data);
3157
+ }
3158
+ }
3159
+ ZodAny.create = (params) => {
3160
+ return new ZodAny({
3161
+ typeName: ZodFirstPartyTypeKind.ZodAny,
3162
+ ...processCreateParams(params),
3163
+ });
3164
+ };
3165
+ class ZodUnknown extends ZodType {
3166
+ constructor() {
3167
+ super(...arguments);
3168
+ // required
3169
+ this._unknown = true;
3170
+ }
3171
+ _parse(input) {
3172
+ return OK(input.data);
3173
+ }
3174
+ }
3175
+ ZodUnknown.create = (params) => {
3176
+ return new ZodUnknown({
3177
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
3178
+ ...processCreateParams(params),
3179
+ });
3180
+ };
3181
+ class ZodNever extends ZodType {
3182
+ _parse(input) {
3183
+ const ctx = this._getOrReturnCtx(input);
3184
+ addIssueToContext(ctx, {
3185
+ code: ZodIssueCode.invalid_type,
3186
+ expected: ZodParsedType.never,
3187
+ received: ctx.parsedType,
3188
+ });
3189
+ return INVALID;
3190
+ }
3191
+ }
3192
+ ZodNever.create = (params) => {
3193
+ return new ZodNever({
3194
+ typeName: ZodFirstPartyTypeKind.ZodNever,
3195
+ ...processCreateParams(params),
3196
+ });
3197
+ };
3198
+ class ZodVoid extends ZodType {
3199
+ _parse(input) {
3200
+ const parsedType = this._getType(input);
3201
+ if (parsedType !== ZodParsedType.undefined) {
3202
+ const ctx = this._getOrReturnCtx(input);
3203
+ addIssueToContext(ctx, {
3204
+ code: ZodIssueCode.invalid_type,
3205
+ expected: ZodParsedType.void,
3206
+ received: ctx.parsedType,
3207
+ });
3208
+ return INVALID;
3209
+ }
3210
+ return OK(input.data);
3211
+ }
3212
+ }
3213
+ ZodVoid.create = (params) => {
3214
+ return new ZodVoid({
3215
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
3216
+ ...processCreateParams(params),
3217
+ });
3218
+ };
3219
+ class ZodArray extends ZodType {
3220
+ _parse(input) {
3221
+ const { ctx, status } = this._processInputParams(input);
3222
+ const def = this._def;
3223
+ if (ctx.parsedType !== ZodParsedType.array) {
3224
+ addIssueToContext(ctx, {
3225
+ code: ZodIssueCode.invalid_type,
3226
+ expected: ZodParsedType.array,
3227
+ received: ctx.parsedType,
3228
+ });
3229
+ return INVALID;
3230
+ }
3231
+ if (def.exactLength !== null) {
3232
+ const tooBig = ctx.data.length > def.exactLength.value;
3233
+ const tooSmall = ctx.data.length < def.exactLength.value;
3234
+ if (tooBig || tooSmall) {
3235
+ addIssueToContext(ctx, {
3236
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
3237
+ minimum: (tooSmall ? def.exactLength.value : undefined),
3238
+ maximum: (tooBig ? def.exactLength.value : undefined),
3239
+ type: "array",
3240
+ inclusive: true,
3241
+ exact: true,
3242
+ message: def.exactLength.message,
3243
+ });
3244
+ status.dirty();
3245
+ }
3246
+ }
3247
+ if (def.minLength !== null) {
3248
+ if (ctx.data.length < def.minLength.value) {
3249
+ addIssueToContext(ctx, {
3250
+ code: ZodIssueCode.too_small,
3251
+ minimum: def.minLength.value,
3252
+ type: "array",
3253
+ inclusive: true,
3254
+ exact: false,
3255
+ message: def.minLength.message,
3256
+ });
3257
+ status.dirty();
3258
+ }
3259
+ }
3260
+ if (def.maxLength !== null) {
3261
+ if (ctx.data.length > def.maxLength.value) {
3262
+ addIssueToContext(ctx, {
3263
+ code: ZodIssueCode.too_big,
3264
+ maximum: def.maxLength.value,
3265
+ type: "array",
3266
+ inclusive: true,
3267
+ exact: false,
3268
+ message: def.maxLength.message,
3269
+ });
3270
+ status.dirty();
3271
+ }
3272
+ }
3273
+ if (ctx.common.async) {
3274
+ return Promise.all([...ctx.data].map((item, i) => {
3275
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3276
+ })).then((result) => {
3277
+ return ParseStatus.mergeArray(status, result);
3278
+ });
3279
+ }
3280
+ const result = [...ctx.data].map((item, i) => {
3281
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3282
+ });
3283
+ return ParseStatus.mergeArray(status, result);
3284
+ }
3285
+ get element() {
3286
+ return this._def.type;
3287
+ }
3288
+ min(minLength, message) {
3289
+ return new ZodArray({
3290
+ ...this._def,
3291
+ minLength: { value: minLength, message: errorUtil.toString(message) },
3292
+ });
3293
+ }
3294
+ max(maxLength, message) {
3295
+ return new ZodArray({
3296
+ ...this._def,
3297
+ maxLength: { value: maxLength, message: errorUtil.toString(message) },
3298
+ });
3299
+ }
3300
+ length(len, message) {
3301
+ return new ZodArray({
3302
+ ...this._def,
3303
+ exactLength: { value: len, message: errorUtil.toString(message) },
3304
+ });
3305
+ }
3306
+ nonempty(message) {
3307
+ return this.min(1, message);
3308
+ }
3309
+ }
3310
+ ZodArray.create = (schema, params) => {
3311
+ return new ZodArray({
3312
+ type: schema,
3313
+ minLength: null,
3314
+ maxLength: null,
3315
+ exactLength: null,
3316
+ typeName: ZodFirstPartyTypeKind.ZodArray,
3317
+ ...processCreateParams(params),
3318
+ });
3319
+ };
3320
+ function deepPartialify(schema) {
3321
+ if (schema instanceof ZodObject) {
3322
+ const newShape = {};
3323
+ for (const key in schema.shape) {
3324
+ const fieldSchema = schema.shape[key];
3325
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
3326
+ }
3327
+ return new ZodObject({
3328
+ ...schema._def,
3329
+ shape: () => newShape,
3330
+ });
3331
+ }
3332
+ else if (schema instanceof ZodArray) {
3333
+ return new ZodArray({
3334
+ ...schema._def,
3335
+ type: deepPartialify(schema.element),
3336
+ });
3337
+ }
3338
+ else if (schema instanceof ZodOptional) {
3339
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
3340
+ }
3341
+ else if (schema instanceof ZodNullable) {
3342
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
3343
+ }
3344
+ else if (schema instanceof ZodTuple) {
3345
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
3346
+ }
3347
+ else {
3348
+ return schema;
3349
+ }
3350
+ }
3351
+ class ZodObject extends ZodType {
3352
+ constructor() {
3353
+ super(...arguments);
3354
+ this._cached = null;
3355
+ /**
3356
+ * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
3357
+ * If you want to pass through unknown properties, use `.passthrough()` instead.
3358
+ */
3359
+ this.nonstrict = this.passthrough;
3360
+ // extend<
3361
+ // Augmentation extends ZodRawShape,
3362
+ // NewOutput extends util.flatten<{
3363
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
3364
+ // ? Augmentation[k]["_output"]
3365
+ // : k extends keyof Output
3366
+ // ? Output[k]
3367
+ // : never;
3368
+ // }>,
3369
+ // NewInput extends util.flatten<{
3370
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
3371
+ // ? Augmentation[k]["_input"]
3372
+ // : k extends keyof Input
3373
+ // ? Input[k]
3374
+ // : never;
3375
+ // }>
3376
+ // >(
3377
+ // augmentation: Augmentation
3378
+ // ): ZodObject<
3379
+ // extendShape<T, Augmentation>,
3380
+ // UnknownKeys,
3381
+ // Catchall,
3382
+ // NewOutput,
3383
+ // NewInput
3384
+ // > {
3385
+ // return new ZodObject({
3386
+ // ...this._def,
3387
+ // shape: () => ({
3388
+ // ...this._def.shape(),
3389
+ // ...augmentation,
3390
+ // }),
3391
+ // }) as any;
3392
+ // }
3393
+ /**
3394
+ * @deprecated Use `.extend` instead
3395
+ * */
3396
+ this.augment = this.extend;
3397
+ }
3398
+ _getCached() {
3399
+ if (this._cached !== null)
3400
+ return this._cached;
3401
+ const shape = this._def.shape();
3402
+ const keys = util.objectKeys(shape);
3403
+ this._cached = { shape, keys };
3404
+ return this._cached;
3405
+ }
3406
+ _parse(input) {
3407
+ const parsedType = this._getType(input);
3408
+ if (parsedType !== ZodParsedType.object) {
3409
+ const ctx = this._getOrReturnCtx(input);
3410
+ addIssueToContext(ctx, {
3411
+ code: ZodIssueCode.invalid_type,
3412
+ expected: ZodParsedType.object,
3413
+ received: ctx.parsedType,
3414
+ });
3415
+ return INVALID;
3416
+ }
3417
+ const { status, ctx } = this._processInputParams(input);
3418
+ const { shape, keys: shapeKeys } = this._getCached();
3419
+ const extraKeys = [];
3420
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
3421
+ for (const key in ctx.data) {
3422
+ if (!shapeKeys.includes(key)) {
3423
+ extraKeys.push(key);
3424
+ }
3425
+ }
3426
+ }
3427
+ const pairs = [];
3428
+ for (const key of shapeKeys) {
3429
+ const keyValidator = shape[key];
3430
+ const value = ctx.data[key];
3431
+ pairs.push({
3432
+ key: { status: "valid", value: key },
3433
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3434
+ alwaysSet: key in ctx.data,
3435
+ });
3436
+ }
3437
+ if (this._def.catchall instanceof ZodNever) {
3438
+ const unknownKeys = this._def.unknownKeys;
3439
+ if (unknownKeys === "passthrough") {
3440
+ for (const key of extraKeys) {
3441
+ pairs.push({
3442
+ key: { status: "valid", value: key },
3443
+ value: { status: "valid", value: ctx.data[key] },
3444
+ });
3445
+ }
3446
+ }
3447
+ else if (unknownKeys === "strict") {
3448
+ if (extraKeys.length > 0) {
3449
+ addIssueToContext(ctx, {
3450
+ code: ZodIssueCode.unrecognized_keys,
3451
+ keys: extraKeys,
3452
+ });
3453
+ status.dirty();
3454
+ }
3455
+ }
3456
+ else if (unknownKeys === "strip") ;
3457
+ else {
3458
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
3459
+ }
3460
+ }
3461
+ else {
3462
+ // run catchall validation
3463
+ const catchall = this._def.catchall;
3464
+ for (const key of extraKeys) {
3465
+ const value = ctx.data[key];
3466
+ pairs.push({
3467
+ key: { status: "valid", value: key },
3468
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
3469
+ ),
3470
+ alwaysSet: key in ctx.data,
3471
+ });
3472
+ }
3473
+ }
3474
+ if (ctx.common.async) {
3475
+ return Promise.resolve()
3476
+ .then(async () => {
3477
+ const syncPairs = [];
3478
+ for (const pair of pairs) {
3479
+ const key = await pair.key;
3480
+ const value = await pair.value;
3481
+ syncPairs.push({
3482
+ key,
3483
+ value,
3484
+ alwaysSet: pair.alwaysSet,
3485
+ });
3486
+ }
3487
+ return syncPairs;
3488
+ })
3489
+ .then((syncPairs) => {
3490
+ return ParseStatus.mergeObjectSync(status, syncPairs);
3491
+ });
3492
+ }
3493
+ else {
3494
+ return ParseStatus.mergeObjectSync(status, pairs);
3495
+ }
3496
+ }
3497
+ get shape() {
3498
+ return this._def.shape();
3499
+ }
3500
+ strict(message) {
3501
+ errorUtil.errToObj;
3502
+ return new ZodObject({
3503
+ ...this._def,
3504
+ unknownKeys: "strict",
3505
+ ...(message !== undefined
3506
+ ? {
3507
+ errorMap: (issue, ctx) => {
3508
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
3509
+ if (issue.code === "unrecognized_keys")
3510
+ return {
3511
+ message: errorUtil.errToObj(message).message ?? defaultError,
3512
+ };
3513
+ return {
3514
+ message: defaultError,
3515
+ };
3516
+ },
3517
+ }
3518
+ : {}),
3519
+ });
3520
+ }
3521
+ strip() {
3522
+ return new ZodObject({
3523
+ ...this._def,
3524
+ unknownKeys: "strip",
3525
+ });
3526
+ }
3527
+ passthrough() {
3528
+ return new ZodObject({
3529
+ ...this._def,
3530
+ unknownKeys: "passthrough",
3531
+ });
3532
+ }
3533
+ // const AugmentFactory =
3534
+ // <Def extends ZodObjectDef>(def: Def) =>
3535
+ // <Augmentation extends ZodRawShape>(
3536
+ // augmentation: Augmentation
3537
+ // ): ZodObject<
3538
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
3539
+ // Def["unknownKeys"],
3540
+ // Def["catchall"]
3541
+ // > => {
3542
+ // return new ZodObject({
3543
+ // ...def,
3544
+ // shape: () => ({
3545
+ // ...def.shape(),
3546
+ // ...augmentation,
3547
+ // }),
3548
+ // }) as any;
3549
+ // };
3550
+ extend(augmentation) {
3551
+ return new ZodObject({
3552
+ ...this._def,
3553
+ shape: () => ({
3554
+ ...this._def.shape(),
3555
+ ...augmentation,
3556
+ }),
3557
+ });
3558
+ }
3559
+ /**
3560
+ * Prior to zod@1.0.12 there was a bug in the
3561
+ * inferred type of merged objects. Please
3562
+ * upgrade if you are experiencing issues.
3563
+ */
3564
+ merge(merging) {
3565
+ const merged = new ZodObject({
3566
+ unknownKeys: merging._def.unknownKeys,
3567
+ catchall: merging._def.catchall,
3568
+ shape: () => ({
3569
+ ...this._def.shape(),
3570
+ ...merging._def.shape(),
3571
+ }),
3572
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3573
+ });
3574
+ return merged;
3575
+ }
3576
+ // merge<
3577
+ // Incoming extends AnyZodObject,
3578
+ // Augmentation extends Incoming["shape"],
3579
+ // NewOutput extends {
3580
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
3581
+ // ? Augmentation[k]["_output"]
3582
+ // : k extends keyof Output
3583
+ // ? Output[k]
3584
+ // : never;
3585
+ // },
3586
+ // NewInput extends {
3587
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
3588
+ // ? Augmentation[k]["_input"]
3589
+ // : k extends keyof Input
3590
+ // ? Input[k]
3591
+ // : never;
3592
+ // }
3593
+ // >(
3594
+ // merging: Incoming
3595
+ // ): ZodObject<
3596
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
3597
+ // Incoming["_def"]["unknownKeys"],
3598
+ // Incoming["_def"]["catchall"],
3599
+ // NewOutput,
3600
+ // NewInput
3601
+ // > {
3602
+ // const merged: any = new ZodObject({
3603
+ // unknownKeys: merging._def.unknownKeys,
3604
+ // catchall: merging._def.catchall,
3605
+ // shape: () =>
3606
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
3607
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
3608
+ // }) as any;
3609
+ // return merged;
3610
+ // }
3611
+ setKey(key, schema) {
3612
+ return this.augment({ [key]: schema });
3613
+ }
3614
+ // merge<Incoming extends AnyZodObject>(
3615
+ // merging: Incoming
3616
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
3617
+ // ZodObject<
3618
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
3619
+ // Incoming["_def"]["unknownKeys"],
3620
+ // Incoming["_def"]["catchall"]
3621
+ // > {
3622
+ // // const mergedShape = objectUtil.mergeShapes(
3623
+ // // this._def.shape(),
3624
+ // // merging._def.shape()
3625
+ // // );
3626
+ // const merged: any = new ZodObject({
3627
+ // unknownKeys: merging._def.unknownKeys,
3628
+ // catchall: merging._def.catchall,
3629
+ // shape: () =>
3630
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
3631
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
3632
+ // }) as any;
3633
+ // return merged;
3634
+ // }
3635
+ catchall(index) {
3636
+ return new ZodObject({
3637
+ ...this._def,
3638
+ catchall: index,
3639
+ });
3640
+ }
3641
+ pick(mask) {
3642
+ const shape = {};
3643
+ for (const key of util.objectKeys(mask)) {
3644
+ if (mask[key] && this.shape[key]) {
3645
+ shape[key] = this.shape[key];
3646
+ }
3647
+ }
3648
+ return new ZodObject({
3649
+ ...this._def,
3650
+ shape: () => shape,
3651
+ });
3652
+ }
3653
+ omit(mask) {
3654
+ const shape = {};
3655
+ for (const key of util.objectKeys(this.shape)) {
3656
+ if (!mask[key]) {
3657
+ shape[key] = this.shape[key];
3658
+ }
3659
+ }
3660
+ return new ZodObject({
3661
+ ...this._def,
3662
+ shape: () => shape,
3663
+ });
3664
+ }
3665
+ /**
3666
+ * @deprecated
3667
+ */
3668
+ deepPartial() {
3669
+ return deepPartialify(this);
3670
+ }
3671
+ partial(mask) {
3672
+ const newShape = {};
3673
+ for (const key of util.objectKeys(this.shape)) {
3674
+ const fieldSchema = this.shape[key];
3675
+ if (mask && !mask[key]) {
3676
+ newShape[key] = fieldSchema;
3677
+ }
3678
+ else {
3679
+ newShape[key] = fieldSchema.optional();
3680
+ }
3681
+ }
3682
+ return new ZodObject({
3683
+ ...this._def,
3684
+ shape: () => newShape,
3685
+ });
3686
+ }
3687
+ required(mask) {
3688
+ const newShape = {};
3689
+ for (const key of util.objectKeys(this.shape)) {
3690
+ if (mask && !mask[key]) {
3691
+ newShape[key] = this.shape[key];
3692
+ }
3693
+ else {
3694
+ const fieldSchema = this.shape[key];
3695
+ let newField = fieldSchema;
3696
+ while (newField instanceof ZodOptional) {
3697
+ newField = newField._def.innerType;
3698
+ }
3699
+ newShape[key] = newField;
3700
+ }
3701
+ }
3702
+ return new ZodObject({
3703
+ ...this._def,
3704
+ shape: () => newShape,
3705
+ });
3706
+ }
3707
+ keyof() {
3708
+ return createZodEnum(util.objectKeys(this.shape));
3709
+ }
3710
+ }
3711
+ ZodObject.create = (shape, params) => {
3712
+ return new ZodObject({
3713
+ shape: () => shape,
3714
+ unknownKeys: "strip",
3715
+ catchall: ZodNever.create(),
3716
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3717
+ ...processCreateParams(params),
3718
+ });
3719
+ };
3720
+ ZodObject.strictCreate = (shape, params) => {
3721
+ return new ZodObject({
3722
+ shape: () => shape,
3723
+ unknownKeys: "strict",
3724
+ catchall: ZodNever.create(),
3725
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3726
+ ...processCreateParams(params),
3727
+ });
3728
+ };
3729
+ ZodObject.lazycreate = (shape, params) => {
3730
+ return new ZodObject({
3731
+ shape,
3732
+ unknownKeys: "strip",
3733
+ catchall: ZodNever.create(),
3734
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3735
+ ...processCreateParams(params),
3736
+ });
3737
+ };
3738
+ class ZodUnion extends ZodType {
3739
+ _parse(input) {
3740
+ const { ctx } = this._processInputParams(input);
3741
+ const options = this._def.options;
3742
+ function handleResults(results) {
3743
+ // return first issue-free validation if it exists
3744
+ for (const result of results) {
3745
+ if (result.result.status === "valid") {
3746
+ return result.result;
3747
+ }
3748
+ }
3749
+ for (const result of results) {
3750
+ if (result.result.status === "dirty") {
3751
+ // add issues from dirty option
3752
+ ctx.common.issues.push(...result.ctx.common.issues);
3753
+ return result.result;
3754
+ }
3755
+ }
3756
+ // return invalid
3757
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3758
+ addIssueToContext(ctx, {
3759
+ code: ZodIssueCode.invalid_union,
3760
+ unionErrors,
3761
+ });
3762
+ return INVALID;
3763
+ }
3764
+ if (ctx.common.async) {
3765
+ return Promise.all(options.map(async (option) => {
3766
+ const childCtx = {
3767
+ ...ctx,
3768
+ common: {
3769
+ ...ctx.common,
3770
+ issues: [],
3771
+ },
3772
+ parent: null,
3773
+ };
3774
+ return {
3775
+ result: await option._parseAsync({
3776
+ data: ctx.data,
3777
+ path: ctx.path,
3778
+ parent: childCtx,
3779
+ }),
3780
+ ctx: childCtx,
3781
+ };
3782
+ })).then(handleResults);
3783
+ }
3784
+ else {
3785
+ let dirty = undefined;
3786
+ const issues = [];
3787
+ for (const option of options) {
3788
+ const childCtx = {
3789
+ ...ctx,
3790
+ common: {
3791
+ ...ctx.common,
3792
+ issues: [],
3793
+ },
3794
+ parent: null,
3795
+ };
3796
+ const result = option._parseSync({
3797
+ data: ctx.data,
3798
+ path: ctx.path,
3799
+ parent: childCtx,
3800
+ });
3801
+ if (result.status === "valid") {
3802
+ return result;
3803
+ }
3804
+ else if (result.status === "dirty" && !dirty) {
3805
+ dirty = { result, ctx: childCtx };
3806
+ }
3807
+ if (childCtx.common.issues.length) {
3808
+ issues.push(childCtx.common.issues);
3809
+ }
3810
+ }
3811
+ if (dirty) {
3812
+ ctx.common.issues.push(...dirty.ctx.common.issues);
3813
+ return dirty.result;
3814
+ }
3815
+ const unionErrors = issues.map((issues) => new ZodError(issues));
3816
+ addIssueToContext(ctx, {
3817
+ code: ZodIssueCode.invalid_union,
3818
+ unionErrors,
3819
+ });
3820
+ return INVALID;
3821
+ }
3822
+ }
3823
+ get options() {
3824
+ return this._def.options;
3825
+ }
3826
+ }
3827
+ ZodUnion.create = (types, params) => {
3828
+ return new ZodUnion({
3829
+ options: types,
3830
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
3831
+ ...processCreateParams(params),
3832
+ });
3833
+ };
3834
+ /////////////////////////////////////////////////////
3835
+ /////////////////////////////////////////////////////
3836
+ ////////// //////////
3837
+ ////////// ZodDiscriminatedUnion //////////
3838
+ ////////// //////////
3839
+ /////////////////////////////////////////////////////
3840
+ /////////////////////////////////////////////////////
3841
+ const getDiscriminator = (type) => {
3842
+ if (type instanceof ZodLazy) {
3843
+ return getDiscriminator(type.schema);
3844
+ }
3845
+ else if (type instanceof ZodEffects) {
3846
+ return getDiscriminator(type.innerType());
3847
+ }
3848
+ else if (type instanceof ZodLiteral) {
3849
+ return [type.value];
3850
+ }
3851
+ else if (type instanceof ZodEnum) {
3852
+ return type.options;
3853
+ }
3854
+ else if (type instanceof ZodNativeEnum) {
3855
+ // eslint-disable-next-line ban/ban
3856
+ return util.objectValues(type.enum);
3857
+ }
3858
+ else if (type instanceof ZodDefault) {
3859
+ return getDiscriminator(type._def.innerType);
3860
+ }
3861
+ else if (type instanceof ZodUndefined) {
3862
+ return [undefined];
3863
+ }
3864
+ else if (type instanceof ZodNull) {
3865
+ return [null];
3866
+ }
3867
+ else if (type instanceof ZodOptional) {
3868
+ return [undefined, ...getDiscriminator(type.unwrap())];
3869
+ }
3870
+ else if (type instanceof ZodNullable) {
3871
+ return [null, ...getDiscriminator(type.unwrap())];
3872
+ }
3873
+ else if (type instanceof ZodBranded) {
3874
+ return getDiscriminator(type.unwrap());
3875
+ }
3876
+ else if (type instanceof ZodReadonly) {
3877
+ return getDiscriminator(type.unwrap());
3878
+ }
3879
+ else if (type instanceof ZodCatch) {
3880
+ return getDiscriminator(type._def.innerType);
3881
+ }
3882
+ else {
3883
+ return [];
3884
+ }
3885
+ };
3886
+ class ZodDiscriminatedUnion extends ZodType {
3887
+ _parse(input) {
3888
+ const { ctx } = this._processInputParams(input);
3889
+ if (ctx.parsedType !== ZodParsedType.object) {
3890
+ addIssueToContext(ctx, {
3891
+ code: ZodIssueCode.invalid_type,
3892
+ expected: ZodParsedType.object,
3893
+ received: ctx.parsedType,
3894
+ });
3895
+ return INVALID;
3896
+ }
3897
+ const discriminator = this.discriminator;
3898
+ const discriminatorValue = ctx.data[discriminator];
3899
+ const option = this.optionsMap.get(discriminatorValue);
3900
+ if (!option) {
3901
+ addIssueToContext(ctx, {
3902
+ code: ZodIssueCode.invalid_union_discriminator,
3903
+ options: Array.from(this.optionsMap.keys()),
3904
+ path: [discriminator],
3905
+ });
3906
+ return INVALID;
3907
+ }
3908
+ if (ctx.common.async) {
3909
+ return option._parseAsync({
3910
+ data: ctx.data,
3911
+ path: ctx.path,
3912
+ parent: ctx,
3913
+ });
3914
+ }
3915
+ else {
3916
+ return option._parseSync({
3917
+ data: ctx.data,
3918
+ path: ctx.path,
3919
+ parent: ctx,
3920
+ });
3921
+ }
3922
+ }
3923
+ get discriminator() {
3924
+ return this._def.discriminator;
3925
+ }
3926
+ get options() {
3927
+ return this._def.options;
3928
+ }
3929
+ get optionsMap() {
3930
+ return this._def.optionsMap;
3931
+ }
3932
+ /**
3933
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
3934
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
3935
+ * have a different value for each object in the union.
3936
+ * @param discriminator the name of the discriminator property
3937
+ * @param types an array of object schemas
3938
+ * @param params
3939
+ */
3940
+ static create(discriminator, options, params) {
3941
+ // Get all the valid discriminator values
3942
+ const optionsMap = new Map();
3943
+ // try {
3944
+ for (const type of options) {
3945
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3946
+ if (!discriminatorValues.length) {
3947
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3948
+ }
3949
+ for (const value of discriminatorValues) {
3950
+ if (optionsMap.has(value)) {
3951
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3952
+ }
3953
+ optionsMap.set(value, type);
3954
+ }
3955
+ }
3956
+ return new ZodDiscriminatedUnion({
3957
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3958
+ discriminator,
3959
+ options,
3960
+ optionsMap,
3961
+ ...processCreateParams(params),
3962
+ });
3963
+ }
3964
+ }
3965
+ function mergeValues(a, b) {
3966
+ const aType = getParsedType(a);
3967
+ const bType = getParsedType(b);
3968
+ if (a === b) {
3969
+ return { valid: true, data: a };
3970
+ }
3971
+ else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3972
+ const bKeys = util.objectKeys(b);
3973
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3974
+ const newObj = { ...a, ...b };
3975
+ for (const key of sharedKeys) {
3976
+ const sharedValue = mergeValues(a[key], b[key]);
3977
+ if (!sharedValue.valid) {
3978
+ return { valid: false };
3979
+ }
3980
+ newObj[key] = sharedValue.data;
3981
+ }
3982
+ return { valid: true, data: newObj };
3983
+ }
3984
+ else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3985
+ if (a.length !== b.length) {
3986
+ return { valid: false };
3987
+ }
3988
+ const newArray = [];
3989
+ for (let index = 0; index < a.length; index++) {
3990
+ const itemA = a[index];
3991
+ const itemB = b[index];
3992
+ const sharedValue = mergeValues(itemA, itemB);
3993
+ if (!sharedValue.valid) {
3994
+ return { valid: false };
3995
+ }
3996
+ newArray.push(sharedValue.data);
3997
+ }
3998
+ return { valid: true, data: newArray };
3999
+ }
4000
+ else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
4001
+ return { valid: true, data: a };
4002
+ }
4003
+ else {
4004
+ return { valid: false };
4005
+ }
4006
+ }
4007
+ class ZodIntersection extends ZodType {
4008
+ _parse(input) {
4009
+ const { status, ctx } = this._processInputParams(input);
4010
+ const handleParsed = (parsedLeft, parsedRight) => {
4011
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
4012
+ return INVALID;
4013
+ }
4014
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
4015
+ if (!merged.valid) {
4016
+ addIssueToContext(ctx, {
4017
+ code: ZodIssueCode.invalid_intersection_types,
4018
+ });
4019
+ return INVALID;
4020
+ }
4021
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
4022
+ status.dirty();
4023
+ }
4024
+ return { status: status.value, value: merged.data };
4025
+ };
4026
+ if (ctx.common.async) {
4027
+ return Promise.all([
4028
+ this._def.left._parseAsync({
4029
+ data: ctx.data,
4030
+ path: ctx.path,
4031
+ parent: ctx,
4032
+ }),
4033
+ this._def.right._parseAsync({
4034
+ data: ctx.data,
4035
+ path: ctx.path,
4036
+ parent: ctx,
4037
+ }),
4038
+ ]).then(([left, right]) => handleParsed(left, right));
4039
+ }
4040
+ else {
4041
+ return handleParsed(this._def.left._parseSync({
4042
+ data: ctx.data,
4043
+ path: ctx.path,
4044
+ parent: ctx,
4045
+ }), this._def.right._parseSync({
4046
+ data: ctx.data,
4047
+ path: ctx.path,
4048
+ parent: ctx,
4049
+ }));
4050
+ }
4051
+ }
4052
+ }
4053
+ ZodIntersection.create = (left, right, params) => {
4054
+ return new ZodIntersection({
4055
+ left: left,
4056
+ right: right,
4057
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
4058
+ ...processCreateParams(params),
4059
+ });
4060
+ };
4061
+ // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
4062
+ class ZodTuple extends ZodType {
4063
+ _parse(input) {
4064
+ const { status, ctx } = this._processInputParams(input);
4065
+ if (ctx.parsedType !== ZodParsedType.array) {
4066
+ addIssueToContext(ctx, {
4067
+ code: ZodIssueCode.invalid_type,
4068
+ expected: ZodParsedType.array,
4069
+ received: ctx.parsedType,
4070
+ });
4071
+ return INVALID;
4072
+ }
4073
+ if (ctx.data.length < this._def.items.length) {
4074
+ addIssueToContext(ctx, {
4075
+ code: ZodIssueCode.too_small,
4076
+ minimum: this._def.items.length,
4077
+ inclusive: true,
4078
+ exact: false,
4079
+ type: "array",
4080
+ });
4081
+ return INVALID;
4082
+ }
4083
+ const rest = this._def.rest;
4084
+ if (!rest && ctx.data.length > this._def.items.length) {
4085
+ addIssueToContext(ctx, {
4086
+ code: ZodIssueCode.too_big,
4087
+ maximum: this._def.items.length,
4088
+ inclusive: true,
4089
+ exact: false,
4090
+ type: "array",
4091
+ });
4092
+ status.dirty();
4093
+ }
4094
+ const items = [...ctx.data]
4095
+ .map((item, itemIndex) => {
4096
+ const schema = this._def.items[itemIndex] || this._def.rest;
4097
+ if (!schema)
4098
+ return null;
4099
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
4100
+ })
4101
+ .filter((x) => !!x); // filter nulls
4102
+ if (ctx.common.async) {
4103
+ return Promise.all(items).then((results) => {
4104
+ return ParseStatus.mergeArray(status, results);
4105
+ });
4106
+ }
4107
+ else {
4108
+ return ParseStatus.mergeArray(status, items);
4109
+ }
4110
+ }
4111
+ get items() {
4112
+ return this._def.items;
4113
+ }
4114
+ rest(rest) {
4115
+ return new ZodTuple({
4116
+ ...this._def,
4117
+ rest,
4118
+ });
4119
+ }
4120
+ }
4121
+ ZodTuple.create = (schemas, params) => {
4122
+ if (!Array.isArray(schemas)) {
4123
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
4124
+ }
4125
+ return new ZodTuple({
4126
+ items: schemas,
4127
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
4128
+ rest: null,
4129
+ ...processCreateParams(params),
4130
+ });
4131
+ };
4132
+ class ZodRecord extends ZodType {
4133
+ get keySchema() {
4134
+ return this._def.keyType;
4135
+ }
4136
+ get valueSchema() {
4137
+ return this._def.valueType;
4138
+ }
4139
+ _parse(input) {
4140
+ const { status, ctx } = this._processInputParams(input);
4141
+ if (ctx.parsedType !== ZodParsedType.object) {
4142
+ addIssueToContext(ctx, {
4143
+ code: ZodIssueCode.invalid_type,
4144
+ expected: ZodParsedType.object,
4145
+ received: ctx.parsedType,
4146
+ });
4147
+ return INVALID;
4148
+ }
4149
+ const pairs = [];
4150
+ const keyType = this._def.keyType;
4151
+ const valueType = this._def.valueType;
4152
+ for (const key in ctx.data) {
4153
+ pairs.push({
4154
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
4155
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
4156
+ alwaysSet: key in ctx.data,
4157
+ });
4158
+ }
4159
+ if (ctx.common.async) {
4160
+ return ParseStatus.mergeObjectAsync(status, pairs);
4161
+ }
4162
+ else {
4163
+ return ParseStatus.mergeObjectSync(status, pairs);
4164
+ }
4165
+ }
4166
+ get element() {
4167
+ return this._def.valueType;
4168
+ }
4169
+ static create(first, second, third) {
4170
+ if (second instanceof ZodType) {
4171
+ return new ZodRecord({
4172
+ keyType: first,
4173
+ valueType: second,
4174
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
4175
+ ...processCreateParams(third),
4176
+ });
4177
+ }
4178
+ return new ZodRecord({
4179
+ keyType: ZodString.create(),
4180
+ valueType: first,
4181
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
4182
+ ...processCreateParams(second),
4183
+ });
4184
+ }
4185
+ }
4186
+ class ZodMap extends ZodType {
4187
+ get keySchema() {
4188
+ return this._def.keyType;
4189
+ }
4190
+ get valueSchema() {
4191
+ return this._def.valueType;
4192
+ }
4193
+ _parse(input) {
4194
+ const { status, ctx } = this._processInputParams(input);
4195
+ if (ctx.parsedType !== ZodParsedType.map) {
4196
+ addIssueToContext(ctx, {
4197
+ code: ZodIssueCode.invalid_type,
4198
+ expected: ZodParsedType.map,
4199
+ received: ctx.parsedType,
4200
+ });
4201
+ return INVALID;
4202
+ }
4203
+ const keyType = this._def.keyType;
4204
+ const valueType = this._def.valueType;
4205
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
4206
+ return {
4207
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
4208
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
4209
+ };
4210
+ });
4211
+ if (ctx.common.async) {
4212
+ const finalMap = new Map();
4213
+ return Promise.resolve().then(async () => {
4214
+ for (const pair of pairs) {
4215
+ const key = await pair.key;
4216
+ const value = await pair.value;
4217
+ if (key.status === "aborted" || value.status === "aborted") {
4218
+ return INVALID;
4219
+ }
4220
+ if (key.status === "dirty" || value.status === "dirty") {
4221
+ status.dirty();
4222
+ }
4223
+ finalMap.set(key.value, value.value);
4224
+ }
4225
+ return { status: status.value, value: finalMap };
4226
+ });
4227
+ }
4228
+ else {
4229
+ const finalMap = new Map();
4230
+ for (const pair of pairs) {
4231
+ const key = pair.key;
4232
+ const value = pair.value;
4233
+ if (key.status === "aborted" || value.status === "aborted") {
4234
+ return INVALID;
4235
+ }
4236
+ if (key.status === "dirty" || value.status === "dirty") {
4237
+ status.dirty();
4238
+ }
4239
+ finalMap.set(key.value, value.value);
4240
+ }
4241
+ return { status: status.value, value: finalMap };
4242
+ }
4243
+ }
4244
+ }
4245
+ ZodMap.create = (keyType, valueType, params) => {
4246
+ return new ZodMap({
4247
+ valueType,
4248
+ keyType,
4249
+ typeName: ZodFirstPartyTypeKind.ZodMap,
4250
+ ...processCreateParams(params),
4251
+ });
4252
+ };
4253
+ class ZodSet extends ZodType {
4254
+ _parse(input) {
4255
+ const { status, ctx } = this._processInputParams(input);
4256
+ if (ctx.parsedType !== ZodParsedType.set) {
4257
+ addIssueToContext(ctx, {
4258
+ code: ZodIssueCode.invalid_type,
4259
+ expected: ZodParsedType.set,
4260
+ received: ctx.parsedType,
4261
+ });
4262
+ return INVALID;
4263
+ }
4264
+ const def = this._def;
4265
+ if (def.minSize !== null) {
4266
+ if (ctx.data.size < def.minSize.value) {
4267
+ addIssueToContext(ctx, {
4268
+ code: ZodIssueCode.too_small,
4269
+ minimum: def.minSize.value,
4270
+ type: "set",
4271
+ inclusive: true,
4272
+ exact: false,
4273
+ message: def.minSize.message,
4274
+ });
4275
+ status.dirty();
4276
+ }
4277
+ }
4278
+ if (def.maxSize !== null) {
4279
+ if (ctx.data.size > def.maxSize.value) {
4280
+ addIssueToContext(ctx, {
4281
+ code: ZodIssueCode.too_big,
4282
+ maximum: def.maxSize.value,
4283
+ type: "set",
4284
+ inclusive: true,
4285
+ exact: false,
4286
+ message: def.maxSize.message,
4287
+ });
4288
+ status.dirty();
4289
+ }
4290
+ }
4291
+ const valueType = this._def.valueType;
4292
+ function finalizeSet(elements) {
4293
+ const parsedSet = new Set();
4294
+ for (const element of elements) {
4295
+ if (element.status === "aborted")
4296
+ return INVALID;
4297
+ if (element.status === "dirty")
4298
+ status.dirty();
4299
+ parsedSet.add(element.value);
4300
+ }
4301
+ return { status: status.value, value: parsedSet };
4302
+ }
4303
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
4304
+ if (ctx.common.async) {
4305
+ return Promise.all(elements).then((elements) => finalizeSet(elements));
4306
+ }
4307
+ else {
4308
+ return finalizeSet(elements);
4309
+ }
4310
+ }
4311
+ min(minSize, message) {
4312
+ return new ZodSet({
4313
+ ...this._def,
4314
+ minSize: { value: minSize, message: errorUtil.toString(message) },
4315
+ });
4316
+ }
4317
+ max(maxSize, message) {
4318
+ return new ZodSet({
4319
+ ...this._def,
4320
+ maxSize: { value: maxSize, message: errorUtil.toString(message) },
4321
+ });
4322
+ }
4323
+ size(size, message) {
4324
+ return this.min(size, message).max(size, message);
4325
+ }
4326
+ nonempty(message) {
4327
+ return this.min(1, message);
4328
+ }
4329
+ }
4330
+ ZodSet.create = (valueType, params) => {
4331
+ return new ZodSet({
4332
+ valueType,
4333
+ minSize: null,
4334
+ maxSize: null,
4335
+ typeName: ZodFirstPartyTypeKind.ZodSet,
4336
+ ...processCreateParams(params),
4337
+ });
4338
+ };
4339
+ class ZodLazy extends ZodType {
4340
+ get schema() {
4341
+ return this._def.getter();
4342
+ }
4343
+ _parse(input) {
4344
+ const { ctx } = this._processInputParams(input);
4345
+ const lazySchema = this._def.getter();
4346
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
4347
+ }
4348
+ }
4349
+ ZodLazy.create = (getter, params) => {
4350
+ return new ZodLazy({
4351
+ getter: getter,
4352
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
4353
+ ...processCreateParams(params),
4354
+ });
4355
+ };
4356
+ class ZodLiteral extends ZodType {
4357
+ _parse(input) {
4358
+ if (input.data !== this._def.value) {
4359
+ const ctx = this._getOrReturnCtx(input);
4360
+ addIssueToContext(ctx, {
4361
+ received: ctx.data,
4362
+ code: ZodIssueCode.invalid_literal,
4363
+ expected: this._def.value,
4364
+ });
4365
+ return INVALID;
4366
+ }
4367
+ return { status: "valid", value: input.data };
4368
+ }
4369
+ get value() {
4370
+ return this._def.value;
4371
+ }
4372
+ }
4373
+ ZodLiteral.create = (value, params) => {
4374
+ return new ZodLiteral({
4375
+ value: value,
4376
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
4377
+ ...processCreateParams(params),
4378
+ });
4379
+ };
4380
+ function createZodEnum(values, params) {
4381
+ return new ZodEnum({
4382
+ values,
4383
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
4384
+ ...processCreateParams(params),
4385
+ });
4386
+ }
4387
+ class ZodEnum extends ZodType {
4388
+ _parse(input) {
4389
+ if (typeof input.data !== "string") {
4390
+ const ctx = this._getOrReturnCtx(input);
4391
+ const expectedValues = this._def.values;
4392
+ addIssueToContext(ctx, {
4393
+ expected: util.joinValues(expectedValues),
4394
+ received: ctx.parsedType,
4395
+ code: ZodIssueCode.invalid_type,
4396
+ });
4397
+ return INVALID;
4398
+ }
4399
+ if (!this._cache) {
4400
+ this._cache = new Set(this._def.values);
4401
+ }
4402
+ if (!this._cache.has(input.data)) {
4403
+ const ctx = this._getOrReturnCtx(input);
4404
+ const expectedValues = this._def.values;
4405
+ addIssueToContext(ctx, {
4406
+ received: ctx.data,
4407
+ code: ZodIssueCode.invalid_enum_value,
4408
+ options: expectedValues,
4409
+ });
4410
+ return INVALID;
4411
+ }
4412
+ return OK(input.data);
4413
+ }
4414
+ get options() {
4415
+ return this._def.values;
4416
+ }
4417
+ get enum() {
4418
+ const enumValues = {};
4419
+ for (const val of this._def.values) {
4420
+ enumValues[val] = val;
4421
+ }
4422
+ return enumValues;
4423
+ }
4424
+ get Values() {
4425
+ const enumValues = {};
4426
+ for (const val of this._def.values) {
4427
+ enumValues[val] = val;
4428
+ }
4429
+ return enumValues;
4430
+ }
4431
+ get Enum() {
4432
+ const enumValues = {};
4433
+ for (const val of this._def.values) {
4434
+ enumValues[val] = val;
4435
+ }
4436
+ return enumValues;
4437
+ }
4438
+ extract(values, newDef = this._def) {
4439
+ return ZodEnum.create(values, {
4440
+ ...this._def,
4441
+ ...newDef,
4442
+ });
4443
+ }
4444
+ exclude(values, newDef = this._def) {
4445
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4446
+ ...this._def,
4447
+ ...newDef,
4448
+ });
4449
+ }
4450
+ }
4451
+ ZodEnum.create = createZodEnum;
4452
+ class ZodNativeEnum extends ZodType {
4453
+ _parse(input) {
4454
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
4455
+ const ctx = this._getOrReturnCtx(input);
4456
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
4457
+ const expectedValues = util.objectValues(nativeEnumValues);
4458
+ addIssueToContext(ctx, {
4459
+ expected: util.joinValues(expectedValues),
4460
+ received: ctx.parsedType,
4461
+ code: ZodIssueCode.invalid_type,
4462
+ });
4463
+ return INVALID;
4464
+ }
4465
+ if (!this._cache) {
4466
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
4467
+ }
4468
+ if (!this._cache.has(input.data)) {
4469
+ const expectedValues = util.objectValues(nativeEnumValues);
4470
+ addIssueToContext(ctx, {
4471
+ received: ctx.data,
4472
+ code: ZodIssueCode.invalid_enum_value,
4473
+ options: expectedValues,
4474
+ });
4475
+ return INVALID;
4476
+ }
4477
+ return OK(input.data);
4478
+ }
4479
+ get enum() {
4480
+ return this._def.values;
4481
+ }
4482
+ }
4483
+ ZodNativeEnum.create = (values, params) => {
4484
+ return new ZodNativeEnum({
4485
+ values: values,
4486
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
4487
+ ...processCreateParams(params),
4488
+ });
4489
+ };
4490
+ class ZodPromise extends ZodType {
4491
+ unwrap() {
4492
+ return this._def.type;
4493
+ }
4494
+ _parse(input) {
4495
+ const { ctx } = this._processInputParams(input);
4496
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
4497
+ addIssueToContext(ctx, {
4498
+ code: ZodIssueCode.invalid_type,
4499
+ expected: ZodParsedType.promise,
4500
+ received: ctx.parsedType,
4501
+ });
4502
+ return INVALID;
4503
+ }
4504
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
4505
+ return OK(promisified.then((data) => {
4506
+ return this._def.type.parseAsync(data, {
4507
+ path: ctx.path,
4508
+ errorMap: ctx.common.contextualErrorMap,
4509
+ });
4510
+ }));
4511
+ }
4512
+ }
4513
+ ZodPromise.create = (schema, params) => {
4514
+ return new ZodPromise({
4515
+ type: schema,
4516
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
4517
+ ...processCreateParams(params),
4518
+ });
4519
+ };
4520
+ class ZodEffects extends ZodType {
4521
+ innerType() {
4522
+ return this._def.schema;
4523
+ }
4524
+ sourceType() {
4525
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
4526
+ ? this._def.schema.sourceType()
4527
+ : this._def.schema;
4528
+ }
4529
+ _parse(input) {
4530
+ const { status, ctx } = this._processInputParams(input);
4531
+ const effect = this._def.effect || null;
4532
+ const checkCtx = {
4533
+ addIssue: (arg) => {
4534
+ addIssueToContext(ctx, arg);
4535
+ if (arg.fatal) {
4536
+ status.abort();
4537
+ }
4538
+ else {
4539
+ status.dirty();
4540
+ }
4541
+ },
4542
+ get path() {
4543
+ return ctx.path;
4544
+ },
4545
+ };
4546
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
4547
+ if (effect.type === "preprocess") {
4548
+ const processed = effect.transform(ctx.data, checkCtx);
4549
+ if (ctx.common.async) {
4550
+ return Promise.resolve(processed).then(async (processed) => {
4551
+ if (status.value === "aborted")
4552
+ return INVALID;
4553
+ const result = await this._def.schema._parseAsync({
4554
+ data: processed,
4555
+ path: ctx.path,
4556
+ parent: ctx,
4557
+ });
4558
+ if (result.status === "aborted")
4559
+ return INVALID;
4560
+ if (result.status === "dirty")
4561
+ return DIRTY(result.value);
4562
+ if (status.value === "dirty")
4563
+ return DIRTY(result.value);
4564
+ return result;
4565
+ });
4566
+ }
4567
+ else {
4568
+ if (status.value === "aborted")
4569
+ return INVALID;
4570
+ const result = this._def.schema._parseSync({
4571
+ data: processed,
4572
+ path: ctx.path,
4573
+ parent: ctx,
4574
+ });
4575
+ if (result.status === "aborted")
4576
+ return INVALID;
4577
+ if (result.status === "dirty")
4578
+ return DIRTY(result.value);
4579
+ if (status.value === "dirty")
4580
+ return DIRTY(result.value);
4581
+ return result;
4582
+ }
4583
+ }
4584
+ if (effect.type === "refinement") {
4585
+ const executeRefinement = (acc) => {
4586
+ const result = effect.refinement(acc, checkCtx);
4587
+ if (ctx.common.async) {
4588
+ return Promise.resolve(result);
4589
+ }
4590
+ if (result instanceof Promise) {
4591
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4592
+ }
4593
+ return acc;
4594
+ };
4595
+ if (ctx.common.async === false) {
4596
+ const inner = this._def.schema._parseSync({
4597
+ data: ctx.data,
4598
+ path: ctx.path,
4599
+ parent: ctx,
4600
+ });
4601
+ if (inner.status === "aborted")
4602
+ return INVALID;
4603
+ if (inner.status === "dirty")
4604
+ status.dirty();
4605
+ // return value is ignored
4606
+ executeRefinement(inner.value);
4607
+ return { status: status.value, value: inner.value };
4608
+ }
4609
+ else {
4610
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
4611
+ if (inner.status === "aborted")
4612
+ return INVALID;
4613
+ if (inner.status === "dirty")
4614
+ status.dirty();
4615
+ return executeRefinement(inner.value).then(() => {
4616
+ return { status: status.value, value: inner.value };
4617
+ });
4618
+ });
4619
+ }
4620
+ }
4621
+ if (effect.type === "transform") {
4622
+ if (ctx.common.async === false) {
4623
+ const base = this._def.schema._parseSync({
4624
+ data: ctx.data,
4625
+ path: ctx.path,
4626
+ parent: ctx,
4627
+ });
4628
+ if (!isValid(base))
4629
+ return INVALID;
4630
+ const result = effect.transform(base.value, checkCtx);
4631
+ if (result instanceof Promise) {
4632
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4633
+ }
4634
+ return { status: status.value, value: result };
4635
+ }
4636
+ else {
4637
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4638
+ if (!isValid(base))
4639
+ return INVALID;
4640
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4641
+ status: status.value,
4642
+ value: result,
4643
+ }));
4644
+ });
4645
+ }
4646
+ }
4647
+ util.assertNever(effect);
4648
+ }
4649
+ }
4650
+ ZodEffects.create = (schema, effect, params) => {
4651
+ return new ZodEffects({
4652
+ schema,
4653
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4654
+ effect,
4655
+ ...processCreateParams(params),
4656
+ });
4657
+ };
4658
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
4659
+ return new ZodEffects({
4660
+ schema,
4661
+ effect: { type: "preprocess", transform: preprocess },
4662
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4663
+ ...processCreateParams(params),
4664
+ });
4665
+ };
4666
+ class ZodOptional extends ZodType {
4667
+ _parse(input) {
4668
+ const parsedType = this._getType(input);
4669
+ if (parsedType === ZodParsedType.undefined) {
4670
+ return OK(undefined);
4671
+ }
4672
+ return this._def.innerType._parse(input);
4673
+ }
4674
+ unwrap() {
4675
+ return this._def.innerType;
4676
+ }
4677
+ }
4678
+ ZodOptional.create = (type, params) => {
4679
+ return new ZodOptional({
4680
+ innerType: type,
4681
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
4682
+ ...processCreateParams(params),
4683
+ });
4684
+ };
4685
+ class ZodNullable extends ZodType {
4686
+ _parse(input) {
4687
+ const parsedType = this._getType(input);
4688
+ if (parsedType === ZodParsedType.null) {
4689
+ return OK(null);
4690
+ }
4691
+ return this._def.innerType._parse(input);
4692
+ }
4693
+ unwrap() {
4694
+ return this._def.innerType;
4695
+ }
4696
+ }
4697
+ ZodNullable.create = (type, params) => {
4698
+ return new ZodNullable({
4699
+ innerType: type,
4700
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
4701
+ ...processCreateParams(params),
4702
+ });
4703
+ };
4704
+ class ZodDefault extends ZodType {
4705
+ _parse(input) {
4706
+ const { ctx } = this._processInputParams(input);
4707
+ let data = ctx.data;
4708
+ if (ctx.parsedType === ZodParsedType.undefined) {
4709
+ data = this._def.defaultValue();
4710
+ }
4711
+ return this._def.innerType._parse({
4712
+ data,
4713
+ path: ctx.path,
4714
+ parent: ctx,
4715
+ });
4716
+ }
4717
+ removeDefault() {
4718
+ return this._def.innerType;
4719
+ }
4720
+ }
4721
+ ZodDefault.create = (type, params) => {
4722
+ return new ZodDefault({
4723
+ innerType: type,
4724
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
4725
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4726
+ ...processCreateParams(params),
4727
+ });
4728
+ };
4729
+ class ZodCatch extends ZodType {
4730
+ _parse(input) {
4731
+ const { ctx } = this._processInputParams(input);
4732
+ // newCtx is used to not collect issues from inner types in ctx
4733
+ const newCtx = {
4734
+ ...ctx,
4735
+ common: {
4736
+ ...ctx.common,
4737
+ issues: [],
4738
+ },
4739
+ };
4740
+ const result = this._def.innerType._parse({
4741
+ data: newCtx.data,
4742
+ path: newCtx.path,
4743
+ parent: {
4744
+ ...newCtx,
4745
+ },
4746
+ });
4747
+ if (isAsync(result)) {
4748
+ return result.then((result) => {
4749
+ return {
4750
+ status: "valid",
4751
+ value: result.status === "valid"
4752
+ ? result.value
4753
+ : this._def.catchValue({
4754
+ get error() {
4755
+ return new ZodError(newCtx.common.issues);
4756
+ },
4757
+ input: newCtx.data,
4758
+ }),
4759
+ };
4760
+ });
4761
+ }
4762
+ else {
4763
+ return {
4764
+ status: "valid",
4765
+ value: result.status === "valid"
4766
+ ? result.value
4767
+ : this._def.catchValue({
4768
+ get error() {
4769
+ return new ZodError(newCtx.common.issues);
4770
+ },
4771
+ input: newCtx.data,
4772
+ }),
4773
+ };
4774
+ }
4775
+ }
4776
+ removeCatch() {
4777
+ return this._def.innerType;
4778
+ }
4779
+ }
4780
+ ZodCatch.create = (type, params) => {
4781
+ return new ZodCatch({
4782
+ innerType: type,
4783
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
4784
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4785
+ ...processCreateParams(params),
4786
+ });
4787
+ };
4788
+ class ZodNaN extends ZodType {
4789
+ _parse(input) {
4790
+ const parsedType = this._getType(input);
4791
+ if (parsedType !== ZodParsedType.nan) {
4792
+ const ctx = this._getOrReturnCtx(input);
4793
+ addIssueToContext(ctx, {
4794
+ code: ZodIssueCode.invalid_type,
4795
+ expected: ZodParsedType.nan,
4796
+ received: ctx.parsedType,
4797
+ });
4798
+ return INVALID;
4799
+ }
4800
+ return { status: "valid", value: input.data };
4801
+ }
4802
+ }
4803
+ ZodNaN.create = (params) => {
4804
+ return new ZodNaN({
4805
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
4806
+ ...processCreateParams(params),
4807
+ });
4808
+ };
4809
+ class ZodBranded extends ZodType {
4810
+ _parse(input) {
4811
+ const { ctx } = this._processInputParams(input);
4812
+ const data = ctx.data;
4813
+ return this._def.type._parse({
4814
+ data,
4815
+ path: ctx.path,
4816
+ parent: ctx,
4817
+ });
4818
+ }
4819
+ unwrap() {
4820
+ return this._def.type;
4821
+ }
4822
+ }
4823
+ class ZodPipeline extends ZodType {
4824
+ _parse(input) {
4825
+ const { status, ctx } = this._processInputParams(input);
4826
+ if (ctx.common.async) {
4827
+ const handleAsync = async () => {
4828
+ const inResult = await this._def.in._parseAsync({
4829
+ data: ctx.data,
4830
+ path: ctx.path,
4831
+ parent: ctx,
4832
+ });
4833
+ if (inResult.status === "aborted")
4834
+ return INVALID;
4835
+ if (inResult.status === "dirty") {
4836
+ status.dirty();
4837
+ return DIRTY(inResult.value);
4838
+ }
4839
+ else {
4840
+ return this._def.out._parseAsync({
4841
+ data: inResult.value,
4842
+ path: ctx.path,
4843
+ parent: ctx,
4844
+ });
4845
+ }
4846
+ };
4847
+ return handleAsync();
4848
+ }
4849
+ else {
4850
+ const inResult = this._def.in._parseSync({
4851
+ data: ctx.data,
4852
+ path: ctx.path,
4853
+ parent: ctx,
4854
+ });
4855
+ if (inResult.status === "aborted")
4856
+ return INVALID;
4857
+ if (inResult.status === "dirty") {
4858
+ status.dirty();
4859
+ return {
4860
+ status: "dirty",
4861
+ value: inResult.value,
4862
+ };
4863
+ }
4864
+ else {
4865
+ return this._def.out._parseSync({
4866
+ data: inResult.value,
4867
+ path: ctx.path,
4868
+ parent: ctx,
4869
+ });
4870
+ }
4871
+ }
4872
+ }
4873
+ static create(a, b) {
4874
+ return new ZodPipeline({
4875
+ in: a,
4876
+ out: b,
4877
+ typeName: ZodFirstPartyTypeKind.ZodPipeline,
4878
+ });
4879
+ }
4880
+ }
4881
+ class ZodReadonly extends ZodType {
4882
+ _parse(input) {
4883
+ const result = this._def.innerType._parse(input);
4884
+ const freeze = (data) => {
4885
+ if (isValid(data)) {
4886
+ data.value = Object.freeze(data.value);
4887
+ }
4888
+ return data;
4889
+ };
4890
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4891
+ }
4892
+ unwrap() {
4893
+ return this._def.innerType;
4894
+ }
4895
+ }
4896
+ ZodReadonly.create = (type, params) => {
4897
+ return new ZodReadonly({
4898
+ innerType: type,
4899
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4900
+ ...processCreateParams(params),
4901
+ });
4902
+ };
4903
+ var ZodFirstPartyTypeKind;
4904
+ (function (ZodFirstPartyTypeKind) {
4905
+ ZodFirstPartyTypeKind["ZodString"] = "ZodString";
4906
+ ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
4907
+ ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
4908
+ ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
4909
+ ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
4910
+ ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
4911
+ ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
4912
+ ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
4913
+ ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
4914
+ ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
4915
+ ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
4916
+ ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
4917
+ ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
4918
+ ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
4919
+ ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
4920
+ ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
4921
+ ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4922
+ ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
4923
+ ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
4924
+ ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
4925
+ ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
4926
+ ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
4927
+ ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
4928
+ ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
4929
+ ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
4930
+ ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
4931
+ ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
4932
+ ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
4933
+ ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
4934
+ ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
4935
+ ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
4936
+ ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
4937
+ ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
4938
+ ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
4939
+ ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
4940
+ ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
4941
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4942
+ const stringType = ZodString.create;
4943
+ const numberType = ZodNumber.create;
4944
+ const booleanType = ZodBoolean.create;
4945
+ const anyType = ZodAny.create;
4946
+ ZodNever.create;
4947
+ const arrayType = ZodArray.create;
4948
+ const objectType = ZodObject.create;
4949
+ ZodUnion.create;
4950
+ const discriminatedUnionType = ZodDiscriminatedUnion.create;
4951
+ ZodIntersection.create;
4952
+ ZodTuple.create;
4953
+ const recordType = ZodRecord.create;
4954
+ const literalType = ZodLiteral.create;
4955
+ const enumType = ZodEnum.create;
4956
+ ZodPromise.create;
4957
+ ZodOptional.create;
4958
+ ZodNullable.create;
4959
+
4960
+ var PaymentSchema = objectType({
4961
+ payload_type: literalType("Payment"),
4962
+ billing: objectType({
4963
+ city: stringType().nullable(),
4964
+ country: stringType().nullable(),
4965
+ state: stringType().nullable(),
4966
+ street: stringType().nullable(),
4967
+ zipcode: stringType().nullable(),
999
4968
  }),
1000
- brand_id: z.string(),
1001
- business_id: z.string(),
1002
- card_issuing_country: z.string().nullable(),
1003
- card_last_four: z.string().nullable(),
1004
- card_network: z.string().nullable(),
1005
- card_type: z.string().nullable(),
1006
- created_at: z.string().transform(function (d) { return new Date(d); }),
1007
- currency: z.string(),
1008
- customer: z.object({
1009
- customer_id: z.string(),
1010
- email: z.string(),
1011
- name: z.string().nullable(),
4969
+ brand_id: stringType(),
4970
+ business_id: stringType(),
4971
+ card_issuing_country: stringType().nullable(),
4972
+ card_last_four: stringType().nullable(),
4973
+ card_network: stringType().nullable(),
4974
+ card_type: stringType().nullable(),
4975
+ created_at: stringType().transform(function (d) { return new Date(d); }),
4976
+ currency: stringType(),
4977
+ customer: objectType({
4978
+ customer_id: stringType(),
4979
+ email: stringType(),
4980
+ name: stringType().nullable(),
1012
4981
  }),
1013
- digital_products_delivered: z.boolean(),
1014
- discount_id: z.string().nullable(),
1015
- disputes: z
1016
- .array(z.object({
1017
- amount: z.string(),
1018
- business_id: z.string(),
1019
- created_at: z.string().transform(function (d) { return new Date(d); }),
1020
- currency: z.string(),
1021
- dispute_id: z.string(),
1022
- dispute_stage: z.enum([
4982
+ digital_products_delivered: booleanType(),
4983
+ discount_id: stringType().nullable(),
4984
+ disputes: arrayType(objectType({
4985
+ amount: stringType(),
4986
+ business_id: stringType(),
4987
+ created_at: stringType().transform(function (d) { return new Date(d); }),
4988
+ currency: stringType(),
4989
+ dispute_id: stringType(),
4990
+ dispute_stage: enumType([
1023
4991
  "pre_dispute",
1024
4992
  "dispute_opened",
1025
4993
  "dispute_won",
1026
4994
  "dispute_lost",
1027
4995
  ]),
1028
- dispute_status: z.enum([
4996
+ dispute_status: enumType([
1029
4997
  "dispute_opened",
1030
4998
  "dispute_won",
1031
4999
  "dispute_lost",
@@ -1033,92 +5001,85 @@ var PaymentSchema = z.object({
1033
5001
  "dispute_cancelled",
1034
5002
  "dispute_challenged",
1035
5003
  ]),
1036
- payment_id: z.string(),
1037
- remarks: z.string().nullable(),
5004
+ payment_id: stringType(),
5005
+ remarks: stringType().nullable(),
1038
5006
  }))
1039
5007
  .nullable(),
1040
- error_code: z.string().nullable(),
1041
- error_message: z.string().nullable(),
1042
- metadata: z.record(z.any()).nullable(),
1043
- payment_id: z.string(),
1044
- payment_link: z.string().nullable(),
1045
- payment_method: z.string().nullable(),
1046
- payment_method_type: z.string().nullable(),
1047
- product_cart: z
1048
- .array(z.object({
1049
- product_id: z.string(),
1050
- quantity: z.number(),
5008
+ error_code: stringType().nullable(),
5009
+ error_message: stringType().nullable(),
5010
+ metadata: recordType(anyType()).nullable(),
5011
+ payment_id: stringType(),
5012
+ payment_link: stringType().nullable(),
5013
+ payment_method: stringType().nullable(),
5014
+ payment_method_type: stringType().nullable(),
5015
+ product_cart: arrayType(objectType({
5016
+ product_id: stringType(),
5017
+ quantity: numberType(),
1051
5018
  }))
1052
5019
  .nullable(),
1053
- refunds: z
1054
- .array(z.object({
1055
- amount: z.number(),
1056
- business_id: z.string(),
1057
- created_at: z.string().transform(function (d) { return new Date(d); }),
1058
- currency: z.string(),
1059
- is_partial: z.boolean(),
1060
- payment_id: z.string(),
1061
- reason: z.string().nullable(),
1062
- refund_id: z.string(),
1063
- status: z.enum(["succeeded", "failed", "pending"]),
5020
+ refunds: arrayType(objectType({
5021
+ amount: numberType(),
5022
+ business_id: stringType(),
5023
+ created_at: stringType().transform(function (d) { return new Date(d); }),
5024
+ currency: stringType(),
5025
+ is_partial: booleanType(),
5026
+ payment_id: stringType(),
5027
+ reason: stringType().nullable(),
5028
+ refund_id: stringType(),
5029
+ status: enumType(["succeeded", "failed", "pending"]),
1064
5030
  }))
1065
5031
  .nullable(),
1066
- settlement_amount: z.number(),
1067
- settlement_currency: z.string(),
1068
- settlement_tax: z.number().nullable(),
1069
- status: z.enum(["succeeded", "failed", "pending", "processing", "cancelled"]),
1070
- subscription_id: z.string().nullable(),
1071
- tax: z.number().nullable(),
1072
- total_amount: z.number(),
1073
- updated_at: z
1074
- .string()
5032
+ settlement_amount: numberType(),
5033
+ settlement_currency: stringType(),
5034
+ settlement_tax: numberType().nullable(),
5035
+ status: enumType(["succeeded", "failed", "pending", "processing", "cancelled"]),
5036
+ subscription_id: stringType().nullable(),
5037
+ tax: numberType().nullable(),
5038
+ total_amount: numberType(),
5039
+ updated_at: stringType()
1075
5040
  .transform(function (d) { return new Date(d); })
1076
5041
  .nullable(),
1077
5042
  });
1078
- var SubscriptionSchema = z.object({
1079
- payload_type: z.literal("Subscription"),
1080
- addons: z
1081
- .array(z.object({
1082
- addon_id: z.string(),
1083
- quantity: z.number(),
5043
+ var SubscriptionSchema = objectType({
5044
+ payload_type: literalType("Subscription"),
5045
+ addons: arrayType(objectType({
5046
+ addon_id: stringType(),
5047
+ quantity: numberType(),
1084
5048
  }))
1085
5049
  .nullable(),
1086
- billing: z.object({
1087
- city: z.string().nullable(),
1088
- country: z.string().nullable(),
1089
- state: z.string().nullable(),
1090
- street: z.string().nullable(),
1091
- zipcode: z.string().nullable(),
5050
+ billing: objectType({
5051
+ city: stringType().nullable(),
5052
+ country: stringType().nullable(),
5053
+ state: stringType().nullable(),
5054
+ street: stringType().nullable(),
5055
+ zipcode: stringType().nullable(),
1092
5056
  }),
1093
- cancel_at_next_billing_date: z.boolean(),
1094
- cancelled_at: z
1095
- .string()
5057
+ cancel_at_next_billing_date: booleanType(),
5058
+ cancelled_at: stringType()
1096
5059
  .transform(function (d) { return new Date(d); })
1097
5060
  .nullable(),
1098
- created_at: z.string().transform(function (d) { return new Date(d); }),
1099
- currency: z.string(),
1100
- customer: z.object({
1101
- customer_id: z.string(),
1102
- email: z.string(),
1103
- name: z.string().nullable(),
5061
+ created_at: stringType().transform(function (d) { return new Date(d); }),
5062
+ currency: stringType(),
5063
+ customer: objectType({
5064
+ customer_id: stringType(),
5065
+ email: stringType(),
5066
+ name: stringType().nullable(),
1104
5067
  }),
1105
- discount_id: z.string().nullable(),
1106
- metadata: z.record(z.any()).nullable(),
1107
- next_billing_date: z
1108
- .string()
5068
+ discount_id: stringType().nullable(),
5069
+ metadata: recordType(anyType()).nullable(),
5070
+ next_billing_date: stringType()
1109
5071
  .transform(function (d) { return new Date(d); })
1110
5072
  .nullable(),
1111
- on_demand: z.boolean(),
1112
- payment_frequency_count: z.number(),
1113
- payment_frequency_interval: z.enum(["Day", "Week", "Month", "Year"]),
1114
- previous_billing_date: z
1115
- .string()
5073
+ on_demand: booleanType(),
5074
+ payment_frequency_count: numberType(),
5075
+ payment_frequency_interval: enumType(["Day", "Week", "Month", "Year"]),
5076
+ previous_billing_date: stringType()
1116
5077
  .transform(function (d) { return new Date(d); })
1117
5078
  .nullable(),
1118
- product_id: z.string(),
1119
- quantity: z.number(),
1120
- recurring_pre_tax_amount: z.number(),
1121
- status: z.enum([
5079
+ product_id: stringType(),
5080
+ quantity: numberType(),
5081
+ recurring_pre_tax_amount: numberType(),
5082
+ status: enumType([
1122
5083
  "pending",
1123
5084
  "active",
1124
5085
  "on_hold",
@@ -1127,38 +5088,38 @@ var SubscriptionSchema = z.object({
1127
5088
  "expired",
1128
5089
  "failed",
1129
5090
  ]),
1130
- subscription_id: z.string(),
1131
- subscription_period_count: z.number(),
1132
- subscription_period_interval: z.enum(["Day", "Week", "Month", "Year"]),
1133
- tax_inclusive: z.boolean(),
1134
- trial_period_days: z.number(),
5091
+ subscription_id: stringType(),
5092
+ subscription_period_count: numberType(),
5093
+ subscription_period_interval: enumType(["Day", "Week", "Month", "Year"]),
5094
+ tax_inclusive: booleanType(),
5095
+ trial_period_days: numberType(),
1135
5096
  });
1136
- var RefundSchema = z.object({
1137
- payload_type: z.literal("Refund"),
1138
- amount: z.number(),
1139
- business_id: z.string(),
1140
- created_at: z.string().transform(function (d) { return new Date(d); }),
1141
- currency: z.string(),
1142
- is_partial: z.boolean(),
1143
- payment_id: z.string(),
1144
- reason: z.string().nullable(),
1145
- refund_id: z.string(),
1146
- status: z.enum(["succeeded", "failed", "pending"]),
5097
+ var RefundSchema = objectType({
5098
+ payload_type: literalType("Refund"),
5099
+ amount: numberType(),
5100
+ business_id: stringType(),
5101
+ created_at: stringType().transform(function (d) { return new Date(d); }),
5102
+ currency: stringType(),
5103
+ is_partial: booleanType(),
5104
+ payment_id: stringType(),
5105
+ reason: stringType().nullable(),
5106
+ refund_id: stringType(),
5107
+ status: enumType(["succeeded", "failed", "pending"]),
1147
5108
  });
1148
- var DisputeSchema = z.object({
1149
- payload_type: z.literal("Dispute"),
1150
- amount: z.string(),
1151
- business_id: z.string(),
1152
- created_at: z.string().transform(function (d) { return new Date(d); }),
1153
- currency: z.string(),
1154
- dispute_id: z.string(),
1155
- dispute_stage: z.enum([
5109
+ var DisputeSchema = objectType({
5110
+ payload_type: literalType("Dispute"),
5111
+ amount: stringType(),
5112
+ business_id: stringType(),
5113
+ created_at: stringType().transform(function (d) { return new Date(d); }),
5114
+ currency: stringType(),
5115
+ dispute_id: stringType(),
5116
+ dispute_stage: enumType([
1156
5117
  "pre_dispute",
1157
5118
  "dispute_opened",
1158
5119
  "dispute_won",
1159
5120
  "dispute_lost",
1160
5121
  ]),
1161
- dispute_status: z.enum([
5122
+ dispute_status: enumType([
1162
5123
  "dispute_opened",
1163
5124
  "dispute_won",
1164
5125
  "dispute_lost",
@@ -1166,160 +5127,159 @@ var DisputeSchema = z.object({
1166
5127
  "dispute_cancelled",
1167
5128
  "dispute_challenged",
1168
5129
  ]),
1169
- payment_id: z.string(),
1170
- remarks: z.string().nullable(),
5130
+ payment_id: stringType(),
5131
+ remarks: stringType().nullable(),
1171
5132
  });
1172
- var LicenseKeySchema = z.object({
1173
- payload_type: z.literal("LicenseKey"),
1174
- activations_limit: z.number(),
1175
- business_id: z.string(),
1176
- created_at: z.string().transform(function (d) { return new Date(d); }),
1177
- customer_id: z.string(),
1178
- expires_at: z
1179
- .string()
5133
+ var LicenseKeySchema = objectType({
5134
+ payload_type: literalType("LicenseKey"),
5135
+ activations_limit: numberType(),
5136
+ business_id: stringType(),
5137
+ created_at: stringType().transform(function (d) { return new Date(d); }),
5138
+ customer_id: stringType(),
5139
+ expires_at: stringType()
1180
5140
  .transform(function (d) { return new Date(d); })
1181
5141
  .nullable(),
1182
- id: z.string(),
1183
- instances_count: z.number(),
1184
- key: z.string(),
1185
- payment_id: z.string(),
1186
- product_id: z.string(),
1187
- status: z.enum(["active", "inactive", "expired"]),
1188
- subscription_id: z.string().nullable(),
5142
+ id: stringType(),
5143
+ instances_count: numberType(),
5144
+ key: stringType(),
5145
+ payment_id: stringType(),
5146
+ product_id: stringType(),
5147
+ status: enumType(["active", "inactive", "expired"]),
5148
+ subscription_id: stringType().nullable(),
1189
5149
  });
1190
- var PaymentSucceededPayloadSchema = z.object({
1191
- business_id: z.string(),
1192
- type: z.literal("payment.succeeded"),
1193
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5150
+ var PaymentSucceededPayloadSchema = objectType({
5151
+ business_id: stringType(),
5152
+ type: literalType("payment.succeeded"),
5153
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1194
5154
  data: PaymentSchema,
1195
5155
  });
1196
- var PaymentFailedPayloadSchema = z.object({
1197
- business_id: z.string(),
1198
- type: z.literal("payment.failed"),
1199
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5156
+ var PaymentFailedPayloadSchema = objectType({
5157
+ business_id: stringType(),
5158
+ type: literalType("payment.failed"),
5159
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1200
5160
  data: PaymentSchema,
1201
5161
  });
1202
- var PaymentProcessingPayloadSchema = z.object({
1203
- business_id: z.string(),
1204
- type: z.literal("payment.processing"),
1205
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5162
+ var PaymentProcessingPayloadSchema = objectType({
5163
+ business_id: stringType(),
5164
+ type: literalType("payment.processing"),
5165
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1206
5166
  data: PaymentSchema,
1207
5167
  });
1208
- var PaymentCancelledPayloadSchema = z.object({
1209
- business_id: z.string(),
1210
- type: z.literal("payment.cancelled"),
1211
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5168
+ var PaymentCancelledPayloadSchema = objectType({
5169
+ business_id: stringType(),
5170
+ type: literalType("payment.cancelled"),
5171
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1212
5172
  data: PaymentSchema,
1213
5173
  });
1214
- var RefundSucceededPayloadSchema = z.object({
1215
- business_id: z.string(),
1216
- type: z.literal("refund.succeeded"),
1217
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5174
+ var RefundSucceededPayloadSchema = objectType({
5175
+ business_id: stringType(),
5176
+ type: literalType("refund.succeeded"),
5177
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1218
5178
  data: RefundSchema,
1219
5179
  });
1220
- var RefundFailedPayloadSchema = z.object({
1221
- business_id: z.string(),
1222
- type: z.literal("refund.failed"),
1223
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5180
+ var RefundFailedPayloadSchema = objectType({
5181
+ business_id: stringType(),
5182
+ type: literalType("refund.failed"),
5183
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1224
5184
  data: RefundSchema,
1225
5185
  });
1226
- var DisputeOpenedPayloadSchema = z.object({
1227
- business_id: z.string(),
1228
- type: z.literal("dispute.opened"),
1229
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5186
+ var DisputeOpenedPayloadSchema = objectType({
5187
+ business_id: stringType(),
5188
+ type: literalType("dispute.opened"),
5189
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1230
5190
  data: DisputeSchema,
1231
5191
  });
1232
- var DisputeExpiredPayloadSchema = z.object({
1233
- business_id: z.string(),
1234
- type: z.literal("dispute.expired"),
1235
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5192
+ var DisputeExpiredPayloadSchema = objectType({
5193
+ business_id: stringType(),
5194
+ type: literalType("dispute.expired"),
5195
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1236
5196
  data: DisputeSchema,
1237
5197
  });
1238
- var DisputeAcceptedPayloadSchema = z.object({
1239
- business_id: z.string(),
1240
- type: z.literal("dispute.accepted"),
1241
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5198
+ var DisputeAcceptedPayloadSchema = objectType({
5199
+ business_id: stringType(),
5200
+ type: literalType("dispute.accepted"),
5201
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1242
5202
  data: DisputeSchema,
1243
5203
  });
1244
- var DisputeCancelledPayloadSchema = z.object({
1245
- business_id: z.string(),
1246
- type: z.literal("dispute.cancelled"),
1247
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5204
+ var DisputeCancelledPayloadSchema = objectType({
5205
+ business_id: stringType(),
5206
+ type: literalType("dispute.cancelled"),
5207
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1248
5208
  data: DisputeSchema,
1249
5209
  });
1250
- var DisputeChallengedPayloadSchema = z.object({
1251
- business_id: z.string(),
1252
- type: z.literal("dispute.challenged"),
1253
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5210
+ var DisputeChallengedPayloadSchema = objectType({
5211
+ business_id: stringType(),
5212
+ type: literalType("dispute.challenged"),
5213
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1254
5214
  data: DisputeSchema,
1255
5215
  });
1256
- var DisputeWonPayloadSchema = z.object({
1257
- business_id: z.string(),
1258
- type: z.literal("dispute.won"),
1259
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5216
+ var DisputeWonPayloadSchema = objectType({
5217
+ business_id: stringType(),
5218
+ type: literalType("dispute.won"),
5219
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1260
5220
  data: DisputeSchema,
1261
5221
  });
1262
- var DisputeLostPayloadSchema = z.object({
1263
- business_id: z.string(),
1264
- type: z.literal("dispute.lost"),
1265
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5222
+ var DisputeLostPayloadSchema = objectType({
5223
+ business_id: stringType(),
5224
+ type: literalType("dispute.lost"),
5225
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1266
5226
  data: DisputeSchema,
1267
5227
  });
1268
- var SubscriptionActivePayloadSchema = z.object({
1269
- business_id: z.string(),
1270
- type: z.literal("subscription.active"),
1271
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5228
+ var SubscriptionActivePayloadSchema = objectType({
5229
+ business_id: stringType(),
5230
+ type: literalType("subscription.active"),
5231
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1272
5232
  data: SubscriptionSchema,
1273
5233
  });
1274
- var SubscriptionOnHoldPayloadSchema = z.object({
1275
- business_id: z.string(),
1276
- type: z.literal("subscription.on_hold"),
1277
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5234
+ var SubscriptionOnHoldPayloadSchema = objectType({
5235
+ business_id: stringType(),
5236
+ type: literalType("subscription.on_hold"),
5237
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1278
5238
  data: SubscriptionSchema,
1279
5239
  });
1280
- var SubscriptionRenewedPayloadSchema = z.object({
1281
- business_id: z.string(),
1282
- type: z.literal("subscription.renewed"),
1283
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5240
+ var SubscriptionRenewedPayloadSchema = objectType({
5241
+ business_id: stringType(),
5242
+ type: literalType("subscription.renewed"),
5243
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1284
5244
  data: SubscriptionSchema,
1285
5245
  });
1286
- var SubscriptionPausedPayloadSchema = z.object({
1287
- business_id: z.string(),
1288
- type: z.literal("subscription.paused"),
1289
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5246
+ var SubscriptionPausedPayloadSchema = objectType({
5247
+ business_id: stringType(),
5248
+ type: literalType("subscription.paused"),
5249
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1290
5250
  data: SubscriptionSchema,
1291
5251
  });
1292
- var SubscriptionPlanChangedPayloadSchema = z.object({
1293
- business_id: z.string(),
1294
- type: z.literal("subscription.plan_changed"),
1295
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5252
+ var SubscriptionPlanChangedPayloadSchema = objectType({
5253
+ business_id: stringType(),
5254
+ type: literalType("subscription.plan_changed"),
5255
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1296
5256
  data: SubscriptionSchema,
1297
5257
  });
1298
- var SubscriptionCancelledPayloadSchema = z.object({
1299
- business_id: z.string(),
1300
- type: z.literal("subscription.cancelled"),
1301
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5258
+ var SubscriptionCancelledPayloadSchema = objectType({
5259
+ business_id: stringType(),
5260
+ type: literalType("subscription.cancelled"),
5261
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1302
5262
  data: SubscriptionSchema,
1303
5263
  });
1304
- var SubscriptionFailedPayloadSchema = z.object({
1305
- business_id: z.string(),
1306
- type: z.literal("subscription.failed"),
1307
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5264
+ var SubscriptionFailedPayloadSchema = objectType({
5265
+ business_id: stringType(),
5266
+ type: literalType("subscription.failed"),
5267
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1308
5268
  data: SubscriptionSchema,
1309
5269
  });
1310
- var SubscriptionExpiredPayloadSchema = z.object({
1311
- business_id: z.string(),
1312
- type: z.literal("subscription.expired"),
1313
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5270
+ var SubscriptionExpiredPayloadSchema = objectType({
5271
+ business_id: stringType(),
5272
+ type: literalType("subscription.expired"),
5273
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1314
5274
  data: SubscriptionSchema,
1315
5275
  });
1316
- var LicenseKeyCreatedPayloadSchema = z.object({
1317
- business_id: z.string(),
1318
- type: z.literal("license_key.created"),
1319
- timestamp: z.string().transform(function (d) { return new Date(d); }),
5276
+ var LicenseKeyCreatedPayloadSchema = objectType({
5277
+ business_id: stringType(),
5278
+ type: literalType("license_key.created"),
5279
+ timestamp: stringType().transform(function (d) { return new Date(d); }),
1320
5280
  data: LicenseKeySchema,
1321
5281
  });
1322
- var WebhookPayloadSchema = z.discriminatedUnion("type", [
5282
+ var WebhookPayloadSchema = discriminatedUnionType("type", [
1323
5283
  PaymentSucceededPayloadSchema,
1324
5284
  PaymentFailedPayloadSchema,
1325
5285
  PaymentProcessingPayloadSchema,
@@ -2456,7 +6416,7 @@ const createDodoWebhookHandler = (handlers) => {
2456
6416
  return new Response(null, { status: 200 });
2457
6417
  }
2458
6418
  catch (error) {
2459
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
6419
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
2460
6420
  console.error("Dodo Payments Webhook Error:", errorMessage);
2461
6421
  return new Response("Error while processing webhook", { status: 400 });
2462
6422
  }