@chainflip/sdk 0.2.8 → 0.2.10

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/swap.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { __name, isString, Chains, Assets, ChainflipNetworks, __publicField, assert, getVaultManagerContractAddress, approve, isTokenCall, isTokenSwap, getTokenContractAddress, checkAllowance, Vault__factory, chainContractIds, assetContractIds, extractOverrides, assetDecimals, isTestnet, getMinimumDepositAmount, getMinimumSwapAmount } from './chunk-MGNNXMB7.mjs';
2
- export { Assets, ChainflipNetworks, Chains, assetChains, assetContractIds, assetDecimals, chainAssets, chainContractIds } from './chunk-MGNNXMB7.mjs';
3
- import { encodeAddress, decodeAddress, base58Decode } from '@polkadot/util-crypto';
4
- import { hexToU8a } from '@polkadot/util';
5
- import * as ethers from 'ethers';
1
+ import { getVaultManagerContractAddress, approve, getTokenContractAddress, checkAllowance, Vault__factory, extractOverrides, getMinimumDepositAmount, getMinimumSwapAmount } from './chunk-LNM2TOMZ.mjs';
2
+ import { z, numericString, ethereumAddress, dotAddress, btcAddress, ccmMetadataSchema } from './chunk-DGDQYRRV.mjs';
3
+ import { __name, Chains, Assets, ChainflipNetworks, __publicField, assert, isTokenCall, isTokenSwap, chainContractIds, assetContractIds, assetDecimals, isTestnet } from './chunk-NX4K76K7.mjs';
4
+ export { Assets, ChainflipNetworks, Chains, assetChains, assetContractIds, assetDecimals, chainAssets, chainContractIds } from './chunk-NX4K76K7.mjs';
5
+ import { decodeAddress } from '@polkadot/util-crypto';
6
6
  import axios from 'axios';
7
7
 
8
8
  // ../../node_modules/.pnpm/@trpc+server@10.40.0/node_modules/@trpc/server/dist/observable-ade1bad8.mjs
@@ -572,8 +572,8 @@ function dataLoader(batchLoader) {
572
572
  index++;
573
573
  continue;
574
574
  }
575
- const isValid2 = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));
576
- if (isValid2) {
575
+ const isValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));
576
+ if (isValid) {
577
577
  lastGroup.push(item);
578
578
  index++;
579
579
  continue;
@@ -1270,7 +1270,7 @@ var isEmptyObject = /* @__PURE__ */ __name(function(payload) {
1270
1270
  var isArray = /* @__PURE__ */ __name(function(payload) {
1271
1271
  return Array.isArray(payload);
1272
1272
  }, "isArray");
1273
- var isString2 = /* @__PURE__ */ __name(function(payload) {
1273
+ var isString = /* @__PURE__ */ __name(function(payload) {
1274
1274
  return typeof payload === "string";
1275
1275
  }, "isString");
1276
1276
  var isNumber = /* @__PURE__ */ __name(function(payload) {
@@ -1301,7 +1301,7 @@ var isNaNValue = /* @__PURE__ */ __name(function(payload) {
1301
1301
  return typeof payload === "number" && isNaN(payload);
1302
1302
  }, "isNaNValue");
1303
1303
  var isPrimitive = /* @__PURE__ */ __name(function(payload) {
1304
- return isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString2(payload) || isSymbol(payload);
1304
+ return isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
1305
1305
  }, "isPrimitive");
1306
1306
  var isBigint = /* @__PURE__ */ __name(function(payload) {
1307
1307
  return typeof payload === "bigint";
@@ -1323,12 +1323,12 @@ var escapeKey = /* @__PURE__ */ __name(function(key) {
1323
1323
  var stringifyPath = /* @__PURE__ */ __name(function(path) {
1324
1324
  return path.map(String).map(escapeKey).join(".");
1325
1325
  }, "stringifyPath");
1326
- var parsePath = /* @__PURE__ */ __name(function(string2) {
1326
+ var parsePath = /* @__PURE__ */ __name(function(string) {
1327
1327
  var result = [];
1328
1328
  var segment = "";
1329
- for (var i = 0; i < string2.length; i++) {
1330
- var char = string2.charAt(i);
1331
- var isEscapedDot = char === "\\" && string2.charAt(i + 1) === ".";
1329
+ for (var i = 0; i < string.length; i++) {
1330
+ var char = string.charAt(i);
1331
+ var isEscapedDot = char === "\\" && string.charAt(i + 1) === ".";
1332
1332
  if (isEscapedDot) {
1333
1333
  segment += ".";
1334
1334
  i++;
@@ -2127,8 +2127,8 @@ var SuperJSON = (
2127
2127
  SuperJSON2.prototype.stringify = function(object) {
2128
2128
  return JSON.stringify(this.serialize(object));
2129
2129
  };
2130
- SuperJSON2.prototype.parse = function(string2) {
2131
- return this.deserialize(JSON.parse(string2));
2130
+ SuperJSON2.prototype.parse = function(string) {
2131
+ return this.deserialize(JSON.parse(string));
2132
2132
  };
2133
2133
  SuperJSON2.prototype.registerClass = function(v, options) {
2134
2134
  this.classRegistry.register(v, options);
@@ -2170,4182 +2170,6 @@ SuperJSON.registerClass;
2170
2170
  SuperJSON.registerCustom;
2171
2171
  SuperJSON.registerSymbol;
2172
2172
  SuperJSON.allowErrorProps;
2173
-
2174
- // ../../node_modules/.pnpm/zod@3.22.4/node_modules/zod/lib/index.mjs
2175
- var util;
2176
- (function(util2) {
2177
- util2.assertEqual = (val) => val;
2178
- function assertIs(_arg) {
2179
- }
2180
- __name(assertIs, "assertIs");
2181
- util2.assertIs = assertIs;
2182
- function assertNever(_x) {
2183
- throw new Error();
2184
- }
2185
- __name(assertNever, "assertNever");
2186
- util2.assertNever = assertNever;
2187
- util2.arrayToEnum = (items) => {
2188
- const obj = {};
2189
- for (const item of items) {
2190
- obj[item] = item;
2191
- }
2192
- return obj;
2193
- };
2194
- util2.getValidEnumValues = (obj) => {
2195
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
2196
- const filtered = {};
2197
- for (const k of validKeys) {
2198
- filtered[k] = obj[k];
2199
- }
2200
- return util2.objectValues(filtered);
2201
- };
2202
- util2.objectValues = (obj) => {
2203
- return util2.objectKeys(obj).map(function(e) {
2204
- return obj[e];
2205
- });
2206
- };
2207
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
2208
- const keys = [];
2209
- for (const key in object) {
2210
- if (Object.prototype.hasOwnProperty.call(object, key)) {
2211
- keys.push(key);
2212
- }
2213
- }
2214
- return keys;
2215
- };
2216
- util2.find = (arr, checker) => {
2217
- for (const item of arr) {
2218
- if (checker(item))
2219
- return item;
2220
- }
2221
- return void 0;
2222
- };
2223
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
2224
- function joinValues(array, separator = " | ") {
2225
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
2226
- }
2227
- __name(joinValues, "joinValues");
2228
- util2.joinValues = joinValues;
2229
- util2.jsonStringifyReplacer = (_, value) => {
2230
- if (typeof value === "bigint") {
2231
- return value.toString();
2232
- }
2233
- return value;
2234
- };
2235
- })(util || (util = {}));
2236
- var objectUtil;
2237
- (function(objectUtil2) {
2238
- objectUtil2.mergeShapes = (first, second) => {
2239
- return {
2240
- ...first,
2241
- ...second
2242
- // second overwrites first
2243
- };
2244
- };
2245
- })(objectUtil || (objectUtil = {}));
2246
- var ZodParsedType = util.arrayToEnum([
2247
- "string",
2248
- "nan",
2249
- "number",
2250
- "integer",
2251
- "float",
2252
- "boolean",
2253
- "date",
2254
- "bigint",
2255
- "symbol",
2256
- "function",
2257
- "undefined",
2258
- "null",
2259
- "array",
2260
- "object",
2261
- "unknown",
2262
- "promise",
2263
- "void",
2264
- "never",
2265
- "map",
2266
- "set"
2267
- ]);
2268
- var getParsedType = /* @__PURE__ */ __name((data) => {
2269
- const t = typeof data;
2270
- switch (t) {
2271
- case "undefined":
2272
- return ZodParsedType.undefined;
2273
- case "string":
2274
- return ZodParsedType.string;
2275
- case "number":
2276
- return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
2277
- case "boolean":
2278
- return ZodParsedType.boolean;
2279
- case "function":
2280
- return ZodParsedType.function;
2281
- case "bigint":
2282
- return ZodParsedType.bigint;
2283
- case "symbol":
2284
- return ZodParsedType.symbol;
2285
- case "object":
2286
- if (Array.isArray(data)) {
2287
- return ZodParsedType.array;
2288
- }
2289
- if (data === null) {
2290
- return ZodParsedType.null;
2291
- }
2292
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
2293
- return ZodParsedType.promise;
2294
- }
2295
- if (typeof Map !== "undefined" && data instanceof Map) {
2296
- return ZodParsedType.map;
2297
- }
2298
- if (typeof Set !== "undefined" && data instanceof Set) {
2299
- return ZodParsedType.set;
2300
- }
2301
- if (typeof Date !== "undefined" && data instanceof Date) {
2302
- return ZodParsedType.date;
2303
- }
2304
- return ZodParsedType.object;
2305
- default:
2306
- return ZodParsedType.unknown;
2307
- }
2308
- }, "getParsedType");
2309
- var ZodIssueCode = util.arrayToEnum([
2310
- "invalid_type",
2311
- "invalid_literal",
2312
- "custom",
2313
- "invalid_union",
2314
- "invalid_union_discriminator",
2315
- "invalid_enum_value",
2316
- "unrecognized_keys",
2317
- "invalid_arguments",
2318
- "invalid_return_type",
2319
- "invalid_date",
2320
- "invalid_string",
2321
- "too_small",
2322
- "too_big",
2323
- "invalid_intersection_types",
2324
- "not_multiple_of",
2325
- "not_finite"
2326
- ]);
2327
- var quotelessJson = /* @__PURE__ */ __name((obj) => {
2328
- const json = JSON.stringify(obj, null, 2);
2329
- return json.replace(/"([^"]+)":/g, "$1:");
2330
- }, "quotelessJson");
2331
- var _ZodError = class _ZodError extends Error {
2332
- constructor(issues) {
2333
- super();
2334
- this.issues = [];
2335
- this.addIssue = (sub) => {
2336
- this.issues = [...this.issues, sub];
2337
- };
2338
- this.addIssues = (subs = []) => {
2339
- this.issues = [...this.issues, ...subs];
2340
- };
2341
- const actualProto = new.target.prototype;
2342
- if (Object.setPrototypeOf) {
2343
- Object.setPrototypeOf(this, actualProto);
2344
- } else {
2345
- this.__proto__ = actualProto;
2346
- }
2347
- this.name = "ZodError";
2348
- this.issues = issues;
2349
- }
2350
- get errors() {
2351
- return this.issues;
2352
- }
2353
- format(_mapper) {
2354
- const mapper = _mapper || function(issue) {
2355
- return issue.message;
2356
- };
2357
- const fieldErrors = { _errors: [] };
2358
- const processError = /* @__PURE__ */ __name((error) => {
2359
- for (const issue of error.issues) {
2360
- if (issue.code === "invalid_union") {
2361
- issue.unionErrors.map(processError);
2362
- } else if (issue.code === "invalid_return_type") {
2363
- processError(issue.returnTypeError);
2364
- } else if (issue.code === "invalid_arguments") {
2365
- processError(issue.argumentsError);
2366
- } else if (issue.path.length === 0) {
2367
- fieldErrors._errors.push(mapper(issue));
2368
- } else {
2369
- let curr = fieldErrors;
2370
- let i = 0;
2371
- while (i < issue.path.length) {
2372
- const el = issue.path[i];
2373
- const terminal = i === issue.path.length - 1;
2374
- if (!terminal) {
2375
- curr[el] = curr[el] || { _errors: [] };
2376
- } else {
2377
- curr[el] = curr[el] || { _errors: [] };
2378
- curr[el]._errors.push(mapper(issue));
2379
- }
2380
- curr = curr[el];
2381
- i++;
2382
- }
2383
- }
2384
- }
2385
- }, "processError");
2386
- processError(this);
2387
- return fieldErrors;
2388
- }
2389
- toString() {
2390
- return this.message;
2391
- }
2392
- get message() {
2393
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
2394
- }
2395
- get isEmpty() {
2396
- return this.issues.length === 0;
2397
- }
2398
- flatten(mapper = (issue) => issue.message) {
2399
- const fieldErrors = {};
2400
- const formErrors = [];
2401
- for (const sub of this.issues) {
2402
- if (sub.path.length > 0) {
2403
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
2404
- fieldErrors[sub.path[0]].push(mapper(sub));
2405
- } else {
2406
- formErrors.push(mapper(sub));
2407
- }
2408
- }
2409
- return { formErrors, fieldErrors };
2410
- }
2411
- get formErrors() {
2412
- return this.flatten();
2413
- }
2414
- };
2415
- __name(_ZodError, "ZodError");
2416
- var ZodError = _ZodError;
2417
- ZodError.create = (issues) => {
2418
- const error = new ZodError(issues);
2419
- return error;
2420
- };
2421
- var errorMap = /* @__PURE__ */ __name((issue, _ctx) => {
2422
- let message;
2423
- switch (issue.code) {
2424
- case ZodIssueCode.invalid_type:
2425
- if (issue.received === ZodParsedType.undefined) {
2426
- message = "Required";
2427
- } else {
2428
- message = `Expected ${issue.expected}, received ${issue.received}`;
2429
- }
2430
- break;
2431
- case ZodIssueCode.invalid_literal:
2432
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
2433
- break;
2434
- case ZodIssueCode.unrecognized_keys:
2435
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
2436
- break;
2437
- case ZodIssueCode.invalid_union:
2438
- message = `Invalid input`;
2439
- break;
2440
- case ZodIssueCode.invalid_union_discriminator:
2441
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
2442
- break;
2443
- case ZodIssueCode.invalid_enum_value:
2444
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
2445
- break;
2446
- case ZodIssueCode.invalid_arguments:
2447
- message = `Invalid function arguments`;
2448
- break;
2449
- case ZodIssueCode.invalid_return_type:
2450
- message = `Invalid function return type`;
2451
- break;
2452
- case ZodIssueCode.invalid_date:
2453
- message = `Invalid date`;
2454
- break;
2455
- case ZodIssueCode.invalid_string:
2456
- if (typeof issue.validation === "object") {
2457
- if ("includes" in issue.validation) {
2458
- message = `Invalid input: must include "${issue.validation.includes}"`;
2459
- if (typeof issue.validation.position === "number") {
2460
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
2461
- }
2462
- } else if ("startsWith" in issue.validation) {
2463
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
2464
- } else if ("endsWith" in issue.validation) {
2465
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
2466
- } else {
2467
- util.assertNever(issue.validation);
2468
- }
2469
- } else if (issue.validation !== "regex") {
2470
- message = `Invalid ${issue.validation}`;
2471
- } else {
2472
- message = "Invalid";
2473
- }
2474
- break;
2475
- case ZodIssueCode.too_small:
2476
- if (issue.type === "array")
2477
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
2478
- else if (issue.type === "string")
2479
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
2480
- else if (issue.type === "number")
2481
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
2482
- else if (issue.type === "date")
2483
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
2484
- else
2485
- message = "Invalid input";
2486
- break;
2487
- case ZodIssueCode.too_big:
2488
- if (issue.type === "array")
2489
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
2490
- else if (issue.type === "string")
2491
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
2492
- else if (issue.type === "number")
2493
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
2494
- else if (issue.type === "bigint")
2495
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
2496
- else if (issue.type === "date")
2497
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
2498
- else
2499
- message = "Invalid input";
2500
- break;
2501
- case ZodIssueCode.custom:
2502
- message = `Invalid input`;
2503
- break;
2504
- case ZodIssueCode.invalid_intersection_types:
2505
- message = `Intersection results could not be merged`;
2506
- break;
2507
- case ZodIssueCode.not_multiple_of:
2508
- message = `Number must be a multiple of ${issue.multipleOf}`;
2509
- break;
2510
- case ZodIssueCode.not_finite:
2511
- message = "Number must be finite";
2512
- break;
2513
- default:
2514
- message = _ctx.defaultError;
2515
- util.assertNever(issue);
2516
- }
2517
- return { message };
2518
- }, "errorMap");
2519
- var overrideErrorMap = errorMap;
2520
- function setErrorMap(map) {
2521
- overrideErrorMap = map;
2522
- }
2523
- __name(setErrorMap, "setErrorMap");
2524
- function getErrorMap() {
2525
- return overrideErrorMap;
2526
- }
2527
- __name(getErrorMap, "getErrorMap");
2528
- var makeIssue = /* @__PURE__ */ __name((params) => {
2529
- const { data, path, errorMaps, issueData } = params;
2530
- const fullPath = [...path, ...issueData.path || []];
2531
- const fullIssue = {
2532
- ...issueData,
2533
- path: fullPath
2534
- };
2535
- let errorMessage = "";
2536
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
2537
- for (const map of maps) {
2538
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
2539
- }
2540
- return {
2541
- ...issueData,
2542
- path: fullPath,
2543
- message: issueData.message || errorMessage
2544
- };
2545
- }, "makeIssue");
2546
- var EMPTY_PATH = [];
2547
- function addIssueToContext(ctx, issueData) {
2548
- const issue = makeIssue({
2549
- issueData,
2550
- data: ctx.data,
2551
- path: ctx.path,
2552
- errorMaps: [
2553
- ctx.common.contextualErrorMap,
2554
- ctx.schemaErrorMap,
2555
- getErrorMap(),
2556
- errorMap
2557
- // then global default map
2558
- ].filter((x) => !!x)
2559
- });
2560
- ctx.common.issues.push(issue);
2561
- }
2562
- __name(addIssueToContext, "addIssueToContext");
2563
- var _ParseStatus = class _ParseStatus {
2564
- constructor() {
2565
- this.value = "valid";
2566
- }
2567
- dirty() {
2568
- if (this.value === "valid")
2569
- this.value = "dirty";
2570
- }
2571
- abort() {
2572
- if (this.value !== "aborted")
2573
- this.value = "aborted";
2574
- }
2575
- static mergeArray(status, results) {
2576
- const arrayValue = [];
2577
- for (const s of results) {
2578
- if (s.status === "aborted")
2579
- return INVALID;
2580
- if (s.status === "dirty")
2581
- status.dirty();
2582
- arrayValue.push(s.value);
2583
- }
2584
- return { status: status.value, value: arrayValue };
2585
- }
2586
- static async mergeObjectAsync(status, pairs) {
2587
- const syncPairs = [];
2588
- for (const pair of pairs) {
2589
- syncPairs.push({
2590
- key: await pair.key,
2591
- value: await pair.value
2592
- });
2593
- }
2594
- return _ParseStatus.mergeObjectSync(status, syncPairs);
2595
- }
2596
- static mergeObjectSync(status, pairs) {
2597
- const finalObject = {};
2598
- for (const pair of pairs) {
2599
- const { key, value } = pair;
2600
- if (key.status === "aborted")
2601
- return INVALID;
2602
- if (value.status === "aborted")
2603
- return INVALID;
2604
- if (key.status === "dirty")
2605
- status.dirty();
2606
- if (value.status === "dirty")
2607
- status.dirty();
2608
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
2609
- finalObject[key.value] = value.value;
2610
- }
2611
- }
2612
- return { status: status.value, value: finalObject };
2613
- }
2614
- };
2615
- __name(_ParseStatus, "ParseStatus");
2616
- var ParseStatus = _ParseStatus;
2617
- var INVALID = Object.freeze({
2618
- status: "aborted"
2619
- });
2620
- var DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
2621
- var OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
2622
- var isAborted = /* @__PURE__ */ __name((x) => x.status === "aborted", "isAborted");
2623
- var isDirty = /* @__PURE__ */ __name((x) => x.status === "dirty", "isDirty");
2624
- var isValid = /* @__PURE__ */ __name((x) => x.status === "valid", "isValid");
2625
- var isAsync = /* @__PURE__ */ __name((x) => typeof Promise !== "undefined" && x instanceof Promise, "isAsync");
2626
- var errorUtil;
2627
- (function(errorUtil2) {
2628
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
2629
- errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2630
- })(errorUtil || (errorUtil = {}));
2631
- var _ParseInputLazyPath = class _ParseInputLazyPath {
2632
- constructor(parent, value, path, key) {
2633
- this._cachedPath = [];
2634
- this.parent = parent;
2635
- this.data = value;
2636
- this._path = path;
2637
- this._key = key;
2638
- }
2639
- get path() {
2640
- if (!this._cachedPath.length) {
2641
- if (this._key instanceof Array) {
2642
- this._cachedPath.push(...this._path, ...this._key);
2643
- } else {
2644
- this._cachedPath.push(...this._path, this._key);
2645
- }
2646
- }
2647
- return this._cachedPath;
2648
- }
2649
- };
2650
- __name(_ParseInputLazyPath, "ParseInputLazyPath");
2651
- var ParseInputLazyPath = _ParseInputLazyPath;
2652
- var handleResult = /* @__PURE__ */ __name((ctx, result) => {
2653
- if (isValid(result)) {
2654
- return { success: true, data: result.value };
2655
- } else {
2656
- if (!ctx.common.issues.length) {
2657
- throw new Error("Validation failed but no issues detected.");
2658
- }
2659
- return {
2660
- success: false,
2661
- get error() {
2662
- if (this._error)
2663
- return this._error;
2664
- const error = new ZodError(ctx.common.issues);
2665
- this._error = error;
2666
- return this._error;
2667
- }
2668
- };
2669
- }
2670
- }, "handleResult");
2671
- function processCreateParams(params) {
2672
- if (!params)
2673
- return {};
2674
- const { errorMap: errorMap3, invalid_type_error, required_error, description } = params;
2675
- if (errorMap3 && (invalid_type_error || required_error)) {
2676
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
2677
- }
2678
- if (errorMap3)
2679
- return { errorMap: errorMap3, description };
2680
- const customMap = /* @__PURE__ */ __name((iss, ctx) => {
2681
- if (iss.code !== "invalid_type")
2682
- return { message: ctx.defaultError };
2683
- if (typeof ctx.data === "undefined") {
2684
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
2685
- }
2686
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
2687
- }, "customMap");
2688
- return { errorMap: customMap, description };
2689
- }
2690
- __name(processCreateParams, "processCreateParams");
2691
- var _ZodType = class _ZodType {
2692
- constructor(def) {
2693
- this.spa = this.safeParseAsync;
2694
- this._def = def;
2695
- this.parse = this.parse.bind(this);
2696
- this.safeParse = this.safeParse.bind(this);
2697
- this.parseAsync = this.parseAsync.bind(this);
2698
- this.safeParseAsync = this.safeParseAsync.bind(this);
2699
- this.spa = this.spa.bind(this);
2700
- this.refine = this.refine.bind(this);
2701
- this.refinement = this.refinement.bind(this);
2702
- this.superRefine = this.superRefine.bind(this);
2703
- this.optional = this.optional.bind(this);
2704
- this.nullable = this.nullable.bind(this);
2705
- this.nullish = this.nullish.bind(this);
2706
- this.array = this.array.bind(this);
2707
- this.promise = this.promise.bind(this);
2708
- this.or = this.or.bind(this);
2709
- this.and = this.and.bind(this);
2710
- this.transform = this.transform.bind(this);
2711
- this.brand = this.brand.bind(this);
2712
- this.default = this.default.bind(this);
2713
- this.catch = this.catch.bind(this);
2714
- this.describe = this.describe.bind(this);
2715
- this.pipe = this.pipe.bind(this);
2716
- this.readonly = this.readonly.bind(this);
2717
- this.isNullable = this.isNullable.bind(this);
2718
- this.isOptional = this.isOptional.bind(this);
2719
- }
2720
- get description() {
2721
- return this._def.description;
2722
- }
2723
- _getType(input) {
2724
- return getParsedType(input.data);
2725
- }
2726
- _getOrReturnCtx(input, ctx) {
2727
- return ctx || {
2728
- common: input.parent.common,
2729
- data: input.data,
2730
- parsedType: getParsedType(input.data),
2731
- schemaErrorMap: this._def.errorMap,
2732
- path: input.path,
2733
- parent: input.parent
2734
- };
2735
- }
2736
- _processInputParams(input) {
2737
- return {
2738
- status: new ParseStatus(),
2739
- ctx: {
2740
- common: input.parent.common,
2741
- data: input.data,
2742
- parsedType: getParsedType(input.data),
2743
- schemaErrorMap: this._def.errorMap,
2744
- path: input.path,
2745
- parent: input.parent
2746
- }
2747
- };
2748
- }
2749
- _parseSync(input) {
2750
- const result = this._parse(input);
2751
- if (isAsync(result)) {
2752
- throw new Error("Synchronous parse encountered promise.");
2753
- }
2754
- return result;
2755
- }
2756
- _parseAsync(input) {
2757
- const result = this._parse(input);
2758
- return Promise.resolve(result);
2759
- }
2760
- parse(data, params) {
2761
- const result = this.safeParse(data, params);
2762
- if (result.success)
2763
- return result.data;
2764
- throw result.error;
2765
- }
2766
- safeParse(data, params) {
2767
- var _a;
2768
- const ctx = {
2769
- common: {
2770
- issues: [],
2771
- async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
2772
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
2773
- },
2774
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
2775
- schemaErrorMap: this._def.errorMap,
2776
- parent: null,
2777
- data,
2778
- parsedType: getParsedType(data)
2779
- };
2780
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
2781
- return handleResult(ctx, result);
2782
- }
2783
- async parseAsync(data, params) {
2784
- const result = await this.safeParseAsync(data, params);
2785
- if (result.success)
2786
- return result.data;
2787
- throw result.error;
2788
- }
2789
- async safeParseAsync(data, params) {
2790
- const ctx = {
2791
- common: {
2792
- issues: [],
2793
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
2794
- async: true
2795
- },
2796
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
2797
- schemaErrorMap: this._def.errorMap,
2798
- parent: null,
2799
- data,
2800
- parsedType: getParsedType(data)
2801
- };
2802
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
2803
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
2804
- return handleResult(ctx, result);
2805
- }
2806
- refine(check, message) {
2807
- const getIssueProperties = /* @__PURE__ */ __name((val) => {
2808
- if (typeof message === "string" || typeof message === "undefined") {
2809
- return { message };
2810
- } else if (typeof message === "function") {
2811
- return message(val);
2812
- } else {
2813
- return message;
2814
- }
2815
- }, "getIssueProperties");
2816
- return this._refinement((val, ctx) => {
2817
- const result = check(val);
2818
- const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
2819
- code: ZodIssueCode.custom,
2820
- ...getIssueProperties(val)
2821
- }), "setError");
2822
- if (typeof Promise !== "undefined" && result instanceof Promise) {
2823
- return result.then((data) => {
2824
- if (!data) {
2825
- setError();
2826
- return false;
2827
- } else {
2828
- return true;
2829
- }
2830
- });
2831
- }
2832
- if (!result) {
2833
- setError();
2834
- return false;
2835
- } else {
2836
- return true;
2837
- }
2838
- });
2839
- }
2840
- refinement(check, refinementData) {
2841
- return this._refinement((val, ctx) => {
2842
- if (!check(val)) {
2843
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
2844
- return false;
2845
- } else {
2846
- return true;
2847
- }
2848
- });
2849
- }
2850
- _refinement(refinement) {
2851
- return new ZodEffects({
2852
- schema: this,
2853
- typeName: ZodFirstPartyTypeKind.ZodEffects,
2854
- effect: { type: "refinement", refinement }
2855
- });
2856
- }
2857
- superRefine(refinement) {
2858
- return this._refinement(refinement);
2859
- }
2860
- optional() {
2861
- return ZodOptional.create(this, this._def);
2862
- }
2863
- nullable() {
2864
- return ZodNullable.create(this, this._def);
2865
- }
2866
- nullish() {
2867
- return this.nullable().optional();
2868
- }
2869
- array() {
2870
- return ZodArray.create(this, this._def);
2871
- }
2872
- promise() {
2873
- return ZodPromise.create(this, this._def);
2874
- }
2875
- or(option) {
2876
- return ZodUnion.create([this, option], this._def);
2877
- }
2878
- and(incoming) {
2879
- return ZodIntersection.create(this, incoming, this._def);
2880
- }
2881
- transform(transform) {
2882
- return new ZodEffects({
2883
- ...processCreateParams(this._def),
2884
- schema: this,
2885
- typeName: ZodFirstPartyTypeKind.ZodEffects,
2886
- effect: { type: "transform", transform }
2887
- });
2888
- }
2889
- default(def) {
2890
- const defaultValueFunc = typeof def === "function" ? def : () => def;
2891
- return new ZodDefault({
2892
- ...processCreateParams(this._def),
2893
- innerType: this,
2894
- defaultValue: defaultValueFunc,
2895
- typeName: ZodFirstPartyTypeKind.ZodDefault
2896
- });
2897
- }
2898
- brand() {
2899
- return new ZodBranded({
2900
- typeName: ZodFirstPartyTypeKind.ZodBranded,
2901
- type: this,
2902
- ...processCreateParams(this._def)
2903
- });
2904
- }
2905
- catch(def) {
2906
- const catchValueFunc = typeof def === "function" ? def : () => def;
2907
- return new ZodCatch({
2908
- ...processCreateParams(this._def),
2909
- innerType: this,
2910
- catchValue: catchValueFunc,
2911
- typeName: ZodFirstPartyTypeKind.ZodCatch
2912
- });
2913
- }
2914
- describe(description) {
2915
- const This = this.constructor;
2916
- return new This({
2917
- ...this._def,
2918
- description
2919
- });
2920
- }
2921
- pipe(target) {
2922
- return ZodPipeline.create(this, target);
2923
- }
2924
- readonly() {
2925
- return ZodReadonly.create(this);
2926
- }
2927
- isOptional() {
2928
- return this.safeParse(void 0).success;
2929
- }
2930
- isNullable() {
2931
- return this.safeParse(null).success;
2932
- }
2933
- };
2934
- __name(_ZodType, "ZodType");
2935
- var ZodType = _ZodType;
2936
- var cuidRegex = /^c[^\s-]{8,}$/i;
2937
- var cuid2Regex = /^[a-z][a-z0-9]*$/;
2938
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
2939
- var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
2940
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
2941
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
2942
- var emojiRegex;
2943
- var ipv4Regex = /^(((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}))$/;
2944
- var ipv6Regex = /^(([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})))$/;
2945
- var datetimeRegex = /* @__PURE__ */ __name((args) => {
2946
- if (args.precision) {
2947
- if (args.offset) {
2948
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
2949
- } else {
2950
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
2951
- }
2952
- } else if (args.precision === 0) {
2953
- if (args.offset) {
2954
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
2955
- } else {
2956
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
2957
- }
2958
- } else {
2959
- if (args.offset) {
2960
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
2961
- } else {
2962
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
2963
- }
2964
- }
2965
- }, "datetimeRegex");
2966
- function isValidIP(ip, version) {
2967
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
2968
- return true;
2969
- }
2970
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
2971
- return true;
2972
- }
2973
- return false;
2974
- }
2975
- __name(isValidIP, "isValidIP");
2976
- var _ZodString = class _ZodString extends ZodType {
2977
- _parse(input) {
2978
- if (this._def.coerce) {
2979
- input.data = String(input.data);
2980
- }
2981
- const parsedType = this._getType(input);
2982
- if (parsedType !== ZodParsedType.string) {
2983
- const ctx2 = this._getOrReturnCtx(input);
2984
- addIssueToContext(
2985
- ctx2,
2986
- {
2987
- code: ZodIssueCode.invalid_type,
2988
- expected: ZodParsedType.string,
2989
- received: ctx2.parsedType
2990
- }
2991
- //
2992
- );
2993
- return INVALID;
2994
- }
2995
- const status = new ParseStatus();
2996
- let ctx = void 0;
2997
- for (const check of this._def.checks) {
2998
- if (check.kind === "min") {
2999
- if (input.data.length < check.value) {
3000
- ctx = this._getOrReturnCtx(input, ctx);
3001
- addIssueToContext(ctx, {
3002
- code: ZodIssueCode.too_small,
3003
- minimum: check.value,
3004
- type: "string",
3005
- inclusive: true,
3006
- exact: false,
3007
- message: check.message
3008
- });
3009
- status.dirty();
3010
- }
3011
- } else if (check.kind === "max") {
3012
- if (input.data.length > check.value) {
3013
- ctx = this._getOrReturnCtx(input, ctx);
3014
- addIssueToContext(ctx, {
3015
- code: ZodIssueCode.too_big,
3016
- maximum: check.value,
3017
- type: "string",
3018
- inclusive: true,
3019
- exact: false,
3020
- message: check.message
3021
- });
3022
- status.dirty();
3023
- }
3024
- } else if (check.kind === "length") {
3025
- const tooBig = input.data.length > check.value;
3026
- const tooSmall = input.data.length < check.value;
3027
- if (tooBig || tooSmall) {
3028
- ctx = this._getOrReturnCtx(input, ctx);
3029
- if (tooBig) {
3030
- addIssueToContext(ctx, {
3031
- code: ZodIssueCode.too_big,
3032
- maximum: check.value,
3033
- type: "string",
3034
- inclusive: true,
3035
- exact: true,
3036
- message: check.message
3037
- });
3038
- } else if (tooSmall) {
3039
- addIssueToContext(ctx, {
3040
- code: ZodIssueCode.too_small,
3041
- minimum: check.value,
3042
- type: "string",
3043
- inclusive: true,
3044
- exact: true,
3045
- message: check.message
3046
- });
3047
- }
3048
- status.dirty();
3049
- }
3050
- } else if (check.kind === "email") {
3051
- if (!emailRegex.test(input.data)) {
3052
- ctx = this._getOrReturnCtx(input, ctx);
3053
- addIssueToContext(ctx, {
3054
- validation: "email",
3055
- code: ZodIssueCode.invalid_string,
3056
- message: check.message
3057
- });
3058
- status.dirty();
3059
- }
3060
- } else if (check.kind === "emoji") {
3061
- if (!emojiRegex) {
3062
- emojiRegex = new RegExp(_emojiRegex, "u");
3063
- }
3064
- if (!emojiRegex.test(input.data)) {
3065
- ctx = this._getOrReturnCtx(input, ctx);
3066
- addIssueToContext(ctx, {
3067
- validation: "emoji",
3068
- code: ZodIssueCode.invalid_string,
3069
- message: check.message
3070
- });
3071
- status.dirty();
3072
- }
3073
- } else if (check.kind === "uuid") {
3074
- if (!uuidRegex.test(input.data)) {
3075
- ctx = this._getOrReturnCtx(input, ctx);
3076
- addIssueToContext(ctx, {
3077
- validation: "uuid",
3078
- code: ZodIssueCode.invalid_string,
3079
- message: check.message
3080
- });
3081
- status.dirty();
3082
- }
3083
- } else if (check.kind === "cuid") {
3084
- if (!cuidRegex.test(input.data)) {
3085
- ctx = this._getOrReturnCtx(input, ctx);
3086
- addIssueToContext(ctx, {
3087
- validation: "cuid",
3088
- code: ZodIssueCode.invalid_string,
3089
- message: check.message
3090
- });
3091
- status.dirty();
3092
- }
3093
- } else if (check.kind === "cuid2") {
3094
- if (!cuid2Regex.test(input.data)) {
3095
- ctx = this._getOrReturnCtx(input, ctx);
3096
- addIssueToContext(ctx, {
3097
- validation: "cuid2",
3098
- code: ZodIssueCode.invalid_string,
3099
- message: check.message
3100
- });
3101
- status.dirty();
3102
- }
3103
- } else if (check.kind === "ulid") {
3104
- if (!ulidRegex.test(input.data)) {
3105
- ctx = this._getOrReturnCtx(input, ctx);
3106
- addIssueToContext(ctx, {
3107
- validation: "ulid",
3108
- code: ZodIssueCode.invalid_string,
3109
- message: check.message
3110
- });
3111
- status.dirty();
3112
- }
3113
- } else if (check.kind === "url") {
3114
- try {
3115
- new URL(input.data);
3116
- } catch (_a) {
3117
- ctx = this._getOrReturnCtx(input, ctx);
3118
- addIssueToContext(ctx, {
3119
- validation: "url",
3120
- code: ZodIssueCode.invalid_string,
3121
- message: check.message
3122
- });
3123
- status.dirty();
3124
- }
3125
- } else if (check.kind === "regex") {
3126
- check.regex.lastIndex = 0;
3127
- const testResult = check.regex.test(input.data);
3128
- if (!testResult) {
3129
- ctx = this._getOrReturnCtx(input, ctx);
3130
- addIssueToContext(ctx, {
3131
- validation: "regex",
3132
- code: ZodIssueCode.invalid_string,
3133
- message: check.message
3134
- });
3135
- status.dirty();
3136
- }
3137
- } else if (check.kind === "trim") {
3138
- input.data = input.data.trim();
3139
- } else if (check.kind === "includes") {
3140
- if (!input.data.includes(check.value, check.position)) {
3141
- ctx = this._getOrReturnCtx(input, ctx);
3142
- addIssueToContext(ctx, {
3143
- code: ZodIssueCode.invalid_string,
3144
- validation: { includes: check.value, position: check.position },
3145
- message: check.message
3146
- });
3147
- status.dirty();
3148
- }
3149
- } else if (check.kind === "toLowerCase") {
3150
- input.data = input.data.toLowerCase();
3151
- } else if (check.kind === "toUpperCase") {
3152
- input.data = input.data.toUpperCase();
3153
- } else if (check.kind === "startsWith") {
3154
- if (!input.data.startsWith(check.value)) {
3155
- ctx = this._getOrReturnCtx(input, ctx);
3156
- addIssueToContext(ctx, {
3157
- code: ZodIssueCode.invalid_string,
3158
- validation: { startsWith: check.value },
3159
- message: check.message
3160
- });
3161
- status.dirty();
3162
- }
3163
- } else if (check.kind === "endsWith") {
3164
- if (!input.data.endsWith(check.value)) {
3165
- ctx = this._getOrReturnCtx(input, ctx);
3166
- addIssueToContext(ctx, {
3167
- code: ZodIssueCode.invalid_string,
3168
- validation: { endsWith: check.value },
3169
- message: check.message
3170
- });
3171
- status.dirty();
3172
- }
3173
- } else if (check.kind === "datetime") {
3174
- const regex = datetimeRegex(check);
3175
- if (!regex.test(input.data)) {
3176
- ctx = this._getOrReturnCtx(input, ctx);
3177
- addIssueToContext(ctx, {
3178
- code: ZodIssueCode.invalid_string,
3179
- validation: "datetime",
3180
- message: check.message
3181
- });
3182
- status.dirty();
3183
- }
3184
- } else if (check.kind === "ip") {
3185
- if (!isValidIP(input.data, check.version)) {
3186
- ctx = this._getOrReturnCtx(input, ctx);
3187
- addIssueToContext(ctx, {
3188
- validation: "ip",
3189
- code: ZodIssueCode.invalid_string,
3190
- message: check.message
3191
- });
3192
- status.dirty();
3193
- }
3194
- } else {
3195
- util.assertNever(check);
3196
- }
3197
- }
3198
- return { status: status.value, value: input.data };
3199
- }
3200
- _regex(regex, validation, message) {
3201
- return this.refinement((data) => regex.test(data), {
3202
- validation,
3203
- code: ZodIssueCode.invalid_string,
3204
- ...errorUtil.errToObj(message)
3205
- });
3206
- }
3207
- _addCheck(check) {
3208
- return new _ZodString({
3209
- ...this._def,
3210
- checks: [...this._def.checks, check]
3211
- });
3212
- }
3213
- email(message) {
3214
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
3215
- }
3216
- url(message) {
3217
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
3218
- }
3219
- emoji(message) {
3220
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
3221
- }
3222
- uuid(message) {
3223
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
3224
- }
3225
- cuid(message) {
3226
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
3227
- }
3228
- cuid2(message) {
3229
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
3230
- }
3231
- ulid(message) {
3232
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
3233
- }
3234
- ip(options) {
3235
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
3236
- }
3237
- datetime(options) {
3238
- var _a;
3239
- if (typeof options === "string") {
3240
- return this._addCheck({
3241
- kind: "datetime",
3242
- precision: null,
3243
- offset: false,
3244
- message: options
3245
- });
3246
- }
3247
- return this._addCheck({
3248
- kind: "datetime",
3249
- precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
3250
- offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
3251
- ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
3252
- });
3253
- }
3254
- regex(regex, message) {
3255
- return this._addCheck({
3256
- kind: "regex",
3257
- regex,
3258
- ...errorUtil.errToObj(message)
3259
- });
3260
- }
3261
- includes(value, options) {
3262
- return this._addCheck({
3263
- kind: "includes",
3264
- value,
3265
- position: options === null || options === void 0 ? void 0 : options.position,
3266
- ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
3267
- });
3268
- }
3269
- startsWith(value, message) {
3270
- return this._addCheck({
3271
- kind: "startsWith",
3272
- value,
3273
- ...errorUtil.errToObj(message)
3274
- });
3275
- }
3276
- endsWith(value, message) {
3277
- return this._addCheck({
3278
- kind: "endsWith",
3279
- value,
3280
- ...errorUtil.errToObj(message)
3281
- });
3282
- }
3283
- min(minLength, message) {
3284
- return this._addCheck({
3285
- kind: "min",
3286
- value: minLength,
3287
- ...errorUtil.errToObj(message)
3288
- });
3289
- }
3290
- max(maxLength, message) {
3291
- return this._addCheck({
3292
- kind: "max",
3293
- value: maxLength,
3294
- ...errorUtil.errToObj(message)
3295
- });
3296
- }
3297
- length(len, message) {
3298
- return this._addCheck({
3299
- kind: "length",
3300
- value: len,
3301
- ...errorUtil.errToObj(message)
3302
- });
3303
- }
3304
- /**
3305
- * @deprecated Use z.string().min(1) instead.
3306
- * @see {@link ZodString.min}
3307
- */
3308
- nonempty(message) {
3309
- return this.min(1, errorUtil.errToObj(message));
3310
- }
3311
- trim() {
3312
- return new _ZodString({
3313
- ...this._def,
3314
- checks: [...this._def.checks, { kind: "trim" }]
3315
- });
3316
- }
3317
- toLowerCase() {
3318
- return new _ZodString({
3319
- ...this._def,
3320
- checks: [...this._def.checks, { kind: "toLowerCase" }]
3321
- });
3322
- }
3323
- toUpperCase() {
3324
- return new _ZodString({
3325
- ...this._def,
3326
- checks: [...this._def.checks, { kind: "toUpperCase" }]
3327
- });
3328
- }
3329
- get isDatetime() {
3330
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
3331
- }
3332
- get isEmail() {
3333
- return !!this._def.checks.find((ch) => ch.kind === "email");
3334
- }
3335
- get isURL() {
3336
- return !!this._def.checks.find((ch) => ch.kind === "url");
3337
- }
3338
- get isEmoji() {
3339
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
3340
- }
3341
- get isUUID() {
3342
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
3343
- }
3344
- get isCUID() {
3345
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
3346
- }
3347
- get isCUID2() {
3348
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
3349
- }
3350
- get isULID() {
3351
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
3352
- }
3353
- get isIP() {
3354
- return !!this._def.checks.find((ch) => ch.kind === "ip");
3355
- }
3356
- get minLength() {
3357
- let min = null;
3358
- for (const ch of this._def.checks) {
3359
- if (ch.kind === "min") {
3360
- if (min === null || ch.value > min)
3361
- min = ch.value;
3362
- }
3363
- }
3364
- return min;
3365
- }
3366
- get maxLength() {
3367
- let max = null;
3368
- for (const ch of this._def.checks) {
3369
- if (ch.kind === "max") {
3370
- if (max === null || ch.value < max)
3371
- max = ch.value;
3372
- }
3373
- }
3374
- return max;
3375
- }
3376
- };
3377
- __name(_ZodString, "ZodString");
3378
- var ZodString = _ZodString;
3379
- ZodString.create = (params) => {
3380
- var _a;
3381
- return new ZodString({
3382
- checks: [],
3383
- typeName: ZodFirstPartyTypeKind.ZodString,
3384
- coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
3385
- ...processCreateParams(params)
3386
- });
3387
- };
3388
- function floatSafeRemainder(val, step) {
3389
- const valDecCount = (val.toString().split(".")[1] || "").length;
3390
- const stepDecCount = (step.toString().split(".")[1] || "").length;
3391
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
3392
- const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
3393
- const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
3394
- return valInt % stepInt / Math.pow(10, decCount);
3395
- }
3396
- __name(floatSafeRemainder, "floatSafeRemainder");
3397
- var _ZodNumber = class _ZodNumber extends ZodType {
3398
- constructor() {
3399
- super(...arguments);
3400
- this.min = this.gte;
3401
- this.max = this.lte;
3402
- this.step = this.multipleOf;
3403
- }
3404
- _parse(input) {
3405
- if (this._def.coerce) {
3406
- input.data = Number(input.data);
3407
- }
3408
- const parsedType = this._getType(input);
3409
- if (parsedType !== ZodParsedType.number) {
3410
- const ctx2 = this._getOrReturnCtx(input);
3411
- addIssueToContext(ctx2, {
3412
- code: ZodIssueCode.invalid_type,
3413
- expected: ZodParsedType.number,
3414
- received: ctx2.parsedType
3415
- });
3416
- return INVALID;
3417
- }
3418
- let ctx = void 0;
3419
- const status = new ParseStatus();
3420
- for (const check of this._def.checks) {
3421
- if (check.kind === "int") {
3422
- if (!util.isInteger(input.data)) {
3423
- ctx = this._getOrReturnCtx(input, ctx);
3424
- addIssueToContext(ctx, {
3425
- code: ZodIssueCode.invalid_type,
3426
- expected: "integer",
3427
- received: "float",
3428
- message: check.message
3429
- });
3430
- status.dirty();
3431
- }
3432
- } else if (check.kind === "min") {
3433
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
3434
- if (tooSmall) {
3435
- ctx = this._getOrReturnCtx(input, ctx);
3436
- addIssueToContext(ctx, {
3437
- code: ZodIssueCode.too_small,
3438
- minimum: check.value,
3439
- type: "number",
3440
- inclusive: check.inclusive,
3441
- exact: false,
3442
- message: check.message
3443
- });
3444
- status.dirty();
3445
- }
3446
- } else if (check.kind === "max") {
3447
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
3448
- if (tooBig) {
3449
- ctx = this._getOrReturnCtx(input, ctx);
3450
- addIssueToContext(ctx, {
3451
- code: ZodIssueCode.too_big,
3452
- maximum: check.value,
3453
- type: "number",
3454
- inclusive: check.inclusive,
3455
- exact: false,
3456
- message: check.message
3457
- });
3458
- status.dirty();
3459
- }
3460
- } else if (check.kind === "multipleOf") {
3461
- if (floatSafeRemainder(input.data, check.value) !== 0) {
3462
- ctx = this._getOrReturnCtx(input, ctx);
3463
- addIssueToContext(ctx, {
3464
- code: ZodIssueCode.not_multiple_of,
3465
- multipleOf: check.value,
3466
- message: check.message
3467
- });
3468
- status.dirty();
3469
- }
3470
- } else if (check.kind === "finite") {
3471
- if (!Number.isFinite(input.data)) {
3472
- ctx = this._getOrReturnCtx(input, ctx);
3473
- addIssueToContext(ctx, {
3474
- code: ZodIssueCode.not_finite,
3475
- message: check.message
3476
- });
3477
- status.dirty();
3478
- }
3479
- } else {
3480
- util.assertNever(check);
3481
- }
3482
- }
3483
- return { status: status.value, value: input.data };
3484
- }
3485
- gte(value, message) {
3486
- return this.setLimit("min", value, true, errorUtil.toString(message));
3487
- }
3488
- gt(value, message) {
3489
- return this.setLimit("min", value, false, errorUtil.toString(message));
3490
- }
3491
- lte(value, message) {
3492
- return this.setLimit("max", value, true, errorUtil.toString(message));
3493
- }
3494
- lt(value, message) {
3495
- return this.setLimit("max", value, false, errorUtil.toString(message));
3496
- }
3497
- setLimit(kind, value, inclusive, message) {
3498
- return new _ZodNumber({
3499
- ...this._def,
3500
- checks: [
3501
- ...this._def.checks,
3502
- {
3503
- kind,
3504
- value,
3505
- inclusive,
3506
- message: errorUtil.toString(message)
3507
- }
3508
- ]
3509
- });
3510
- }
3511
- _addCheck(check) {
3512
- return new _ZodNumber({
3513
- ...this._def,
3514
- checks: [...this._def.checks, check]
3515
- });
3516
- }
3517
- int(message) {
3518
- return this._addCheck({
3519
- kind: "int",
3520
- message: errorUtil.toString(message)
3521
- });
3522
- }
3523
- positive(message) {
3524
- return this._addCheck({
3525
- kind: "min",
3526
- value: 0,
3527
- inclusive: false,
3528
- message: errorUtil.toString(message)
3529
- });
3530
- }
3531
- negative(message) {
3532
- return this._addCheck({
3533
- kind: "max",
3534
- value: 0,
3535
- inclusive: false,
3536
- message: errorUtil.toString(message)
3537
- });
3538
- }
3539
- nonpositive(message) {
3540
- return this._addCheck({
3541
- kind: "max",
3542
- value: 0,
3543
- inclusive: true,
3544
- message: errorUtil.toString(message)
3545
- });
3546
- }
3547
- nonnegative(message) {
3548
- return this._addCheck({
3549
- kind: "min",
3550
- value: 0,
3551
- inclusive: true,
3552
- message: errorUtil.toString(message)
3553
- });
3554
- }
3555
- multipleOf(value, message) {
3556
- return this._addCheck({
3557
- kind: "multipleOf",
3558
- value,
3559
- message: errorUtil.toString(message)
3560
- });
3561
- }
3562
- finite(message) {
3563
- return this._addCheck({
3564
- kind: "finite",
3565
- message: errorUtil.toString(message)
3566
- });
3567
- }
3568
- safe(message) {
3569
- return this._addCheck({
3570
- kind: "min",
3571
- inclusive: true,
3572
- value: Number.MIN_SAFE_INTEGER,
3573
- message: errorUtil.toString(message)
3574
- })._addCheck({
3575
- kind: "max",
3576
- inclusive: true,
3577
- value: Number.MAX_SAFE_INTEGER,
3578
- message: errorUtil.toString(message)
3579
- });
3580
- }
3581
- get minValue() {
3582
- let min = null;
3583
- for (const ch of this._def.checks) {
3584
- if (ch.kind === "min") {
3585
- if (min === null || ch.value > min)
3586
- min = ch.value;
3587
- }
3588
- }
3589
- return min;
3590
- }
3591
- get maxValue() {
3592
- let max = null;
3593
- for (const ch of this._def.checks) {
3594
- if (ch.kind === "max") {
3595
- if (max === null || ch.value < max)
3596
- max = ch.value;
3597
- }
3598
- }
3599
- return max;
3600
- }
3601
- get isInt() {
3602
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
3603
- }
3604
- get isFinite() {
3605
- let max = null, min = null;
3606
- for (const ch of this._def.checks) {
3607
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
3608
- return true;
3609
- } else if (ch.kind === "min") {
3610
- if (min === null || ch.value > min)
3611
- min = ch.value;
3612
- } else if (ch.kind === "max") {
3613
- if (max === null || ch.value < max)
3614
- max = ch.value;
3615
- }
3616
- }
3617
- return Number.isFinite(min) && Number.isFinite(max);
3618
- }
3619
- };
3620
- __name(_ZodNumber, "ZodNumber");
3621
- var ZodNumber = _ZodNumber;
3622
- ZodNumber.create = (params) => {
3623
- return new ZodNumber({
3624
- checks: [],
3625
- typeName: ZodFirstPartyTypeKind.ZodNumber,
3626
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
3627
- ...processCreateParams(params)
3628
- });
3629
- };
3630
- var _ZodBigInt = class _ZodBigInt extends ZodType {
3631
- constructor() {
3632
- super(...arguments);
3633
- this.min = this.gte;
3634
- this.max = this.lte;
3635
- }
3636
- _parse(input) {
3637
- if (this._def.coerce) {
3638
- input.data = BigInt(input.data);
3639
- }
3640
- const parsedType = this._getType(input);
3641
- if (parsedType !== ZodParsedType.bigint) {
3642
- const ctx2 = this._getOrReturnCtx(input);
3643
- addIssueToContext(ctx2, {
3644
- code: ZodIssueCode.invalid_type,
3645
- expected: ZodParsedType.bigint,
3646
- received: ctx2.parsedType
3647
- });
3648
- return INVALID;
3649
- }
3650
- let ctx = void 0;
3651
- const status = new ParseStatus();
3652
- for (const check of this._def.checks) {
3653
- if (check.kind === "min") {
3654
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
3655
- if (tooSmall) {
3656
- ctx = this._getOrReturnCtx(input, ctx);
3657
- addIssueToContext(ctx, {
3658
- code: ZodIssueCode.too_small,
3659
- type: "bigint",
3660
- minimum: check.value,
3661
- inclusive: check.inclusive,
3662
- message: check.message
3663
- });
3664
- status.dirty();
3665
- }
3666
- } else if (check.kind === "max") {
3667
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
3668
- if (tooBig) {
3669
- ctx = this._getOrReturnCtx(input, ctx);
3670
- addIssueToContext(ctx, {
3671
- code: ZodIssueCode.too_big,
3672
- type: "bigint",
3673
- maximum: check.value,
3674
- inclusive: check.inclusive,
3675
- message: check.message
3676
- });
3677
- status.dirty();
3678
- }
3679
- } else if (check.kind === "multipleOf") {
3680
- if (input.data % check.value !== BigInt(0)) {
3681
- ctx = this._getOrReturnCtx(input, ctx);
3682
- addIssueToContext(ctx, {
3683
- code: ZodIssueCode.not_multiple_of,
3684
- multipleOf: check.value,
3685
- message: check.message
3686
- });
3687
- status.dirty();
3688
- }
3689
- } else {
3690
- util.assertNever(check);
3691
- }
3692
- }
3693
- return { status: status.value, value: input.data };
3694
- }
3695
- gte(value, message) {
3696
- return this.setLimit("min", value, true, errorUtil.toString(message));
3697
- }
3698
- gt(value, message) {
3699
- return this.setLimit("min", value, false, errorUtil.toString(message));
3700
- }
3701
- lte(value, message) {
3702
- return this.setLimit("max", value, true, errorUtil.toString(message));
3703
- }
3704
- lt(value, message) {
3705
- return this.setLimit("max", value, false, errorUtil.toString(message));
3706
- }
3707
- setLimit(kind, value, inclusive, message) {
3708
- return new _ZodBigInt({
3709
- ...this._def,
3710
- checks: [
3711
- ...this._def.checks,
3712
- {
3713
- kind,
3714
- value,
3715
- inclusive,
3716
- message: errorUtil.toString(message)
3717
- }
3718
- ]
3719
- });
3720
- }
3721
- _addCheck(check) {
3722
- return new _ZodBigInt({
3723
- ...this._def,
3724
- checks: [...this._def.checks, check]
3725
- });
3726
- }
3727
- positive(message) {
3728
- return this._addCheck({
3729
- kind: "min",
3730
- value: BigInt(0),
3731
- inclusive: false,
3732
- message: errorUtil.toString(message)
3733
- });
3734
- }
3735
- negative(message) {
3736
- return this._addCheck({
3737
- kind: "max",
3738
- value: BigInt(0),
3739
- inclusive: false,
3740
- message: errorUtil.toString(message)
3741
- });
3742
- }
3743
- nonpositive(message) {
3744
- return this._addCheck({
3745
- kind: "max",
3746
- value: BigInt(0),
3747
- inclusive: true,
3748
- message: errorUtil.toString(message)
3749
- });
3750
- }
3751
- nonnegative(message) {
3752
- return this._addCheck({
3753
- kind: "min",
3754
- value: BigInt(0),
3755
- inclusive: true,
3756
- message: errorUtil.toString(message)
3757
- });
3758
- }
3759
- multipleOf(value, message) {
3760
- return this._addCheck({
3761
- kind: "multipleOf",
3762
- value,
3763
- message: errorUtil.toString(message)
3764
- });
3765
- }
3766
- get minValue() {
3767
- let min = null;
3768
- for (const ch of this._def.checks) {
3769
- if (ch.kind === "min") {
3770
- if (min === null || ch.value > min)
3771
- min = ch.value;
3772
- }
3773
- }
3774
- return min;
3775
- }
3776
- get maxValue() {
3777
- let max = null;
3778
- for (const ch of this._def.checks) {
3779
- if (ch.kind === "max") {
3780
- if (max === null || ch.value < max)
3781
- max = ch.value;
3782
- }
3783
- }
3784
- return max;
3785
- }
3786
- };
3787
- __name(_ZodBigInt, "ZodBigInt");
3788
- var ZodBigInt = _ZodBigInt;
3789
- ZodBigInt.create = (params) => {
3790
- var _a;
3791
- return new ZodBigInt({
3792
- checks: [],
3793
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
3794
- coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
3795
- ...processCreateParams(params)
3796
- });
3797
- };
3798
- var _ZodBoolean = class _ZodBoolean extends ZodType {
3799
- _parse(input) {
3800
- if (this._def.coerce) {
3801
- input.data = Boolean(input.data);
3802
- }
3803
- const parsedType = this._getType(input);
3804
- if (parsedType !== ZodParsedType.boolean) {
3805
- const ctx = this._getOrReturnCtx(input);
3806
- addIssueToContext(ctx, {
3807
- code: ZodIssueCode.invalid_type,
3808
- expected: ZodParsedType.boolean,
3809
- received: ctx.parsedType
3810
- });
3811
- return INVALID;
3812
- }
3813
- return OK(input.data);
3814
- }
3815
- };
3816
- __name(_ZodBoolean, "ZodBoolean");
3817
- var ZodBoolean = _ZodBoolean;
3818
- ZodBoolean.create = (params) => {
3819
- return new ZodBoolean({
3820
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
3821
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
3822
- ...processCreateParams(params)
3823
- });
3824
- };
3825
- var _ZodDate = class _ZodDate extends ZodType {
3826
- _parse(input) {
3827
- if (this._def.coerce) {
3828
- input.data = new Date(input.data);
3829
- }
3830
- const parsedType = this._getType(input);
3831
- if (parsedType !== ZodParsedType.date) {
3832
- const ctx2 = this._getOrReturnCtx(input);
3833
- addIssueToContext(ctx2, {
3834
- code: ZodIssueCode.invalid_type,
3835
- expected: ZodParsedType.date,
3836
- received: ctx2.parsedType
3837
- });
3838
- return INVALID;
3839
- }
3840
- if (isNaN(input.data.getTime())) {
3841
- const ctx2 = this._getOrReturnCtx(input);
3842
- addIssueToContext(ctx2, {
3843
- code: ZodIssueCode.invalid_date
3844
- });
3845
- return INVALID;
3846
- }
3847
- const status = new ParseStatus();
3848
- let ctx = void 0;
3849
- for (const check of this._def.checks) {
3850
- if (check.kind === "min") {
3851
- if (input.data.getTime() < check.value) {
3852
- ctx = this._getOrReturnCtx(input, ctx);
3853
- addIssueToContext(ctx, {
3854
- code: ZodIssueCode.too_small,
3855
- message: check.message,
3856
- inclusive: true,
3857
- exact: false,
3858
- minimum: check.value,
3859
- type: "date"
3860
- });
3861
- status.dirty();
3862
- }
3863
- } else if (check.kind === "max") {
3864
- if (input.data.getTime() > check.value) {
3865
- ctx = this._getOrReturnCtx(input, ctx);
3866
- addIssueToContext(ctx, {
3867
- code: ZodIssueCode.too_big,
3868
- message: check.message,
3869
- inclusive: true,
3870
- exact: false,
3871
- maximum: check.value,
3872
- type: "date"
3873
- });
3874
- status.dirty();
3875
- }
3876
- } else {
3877
- util.assertNever(check);
3878
- }
3879
- }
3880
- return {
3881
- status: status.value,
3882
- value: new Date(input.data.getTime())
3883
- };
3884
- }
3885
- _addCheck(check) {
3886
- return new _ZodDate({
3887
- ...this._def,
3888
- checks: [...this._def.checks, check]
3889
- });
3890
- }
3891
- min(minDate, message) {
3892
- return this._addCheck({
3893
- kind: "min",
3894
- value: minDate.getTime(),
3895
- message: errorUtil.toString(message)
3896
- });
3897
- }
3898
- max(maxDate, message) {
3899
- return this._addCheck({
3900
- kind: "max",
3901
- value: maxDate.getTime(),
3902
- message: errorUtil.toString(message)
3903
- });
3904
- }
3905
- get minDate() {
3906
- let min = null;
3907
- for (const ch of this._def.checks) {
3908
- if (ch.kind === "min") {
3909
- if (min === null || ch.value > min)
3910
- min = ch.value;
3911
- }
3912
- }
3913
- return min != null ? new Date(min) : null;
3914
- }
3915
- get maxDate() {
3916
- let max = null;
3917
- for (const ch of this._def.checks) {
3918
- if (ch.kind === "max") {
3919
- if (max === null || ch.value < max)
3920
- max = ch.value;
3921
- }
3922
- }
3923
- return max != null ? new Date(max) : null;
3924
- }
3925
- };
3926
- __name(_ZodDate, "ZodDate");
3927
- var ZodDate = _ZodDate;
3928
- ZodDate.create = (params) => {
3929
- return new ZodDate({
3930
- checks: [],
3931
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
3932
- typeName: ZodFirstPartyTypeKind.ZodDate,
3933
- ...processCreateParams(params)
3934
- });
3935
- };
3936
- var _ZodSymbol = class _ZodSymbol extends ZodType {
3937
- _parse(input) {
3938
- const parsedType = this._getType(input);
3939
- if (parsedType !== ZodParsedType.symbol) {
3940
- const ctx = this._getOrReturnCtx(input);
3941
- addIssueToContext(ctx, {
3942
- code: ZodIssueCode.invalid_type,
3943
- expected: ZodParsedType.symbol,
3944
- received: ctx.parsedType
3945
- });
3946
- return INVALID;
3947
- }
3948
- return OK(input.data);
3949
- }
3950
- };
3951
- __name(_ZodSymbol, "ZodSymbol");
3952
- var ZodSymbol = _ZodSymbol;
3953
- ZodSymbol.create = (params) => {
3954
- return new ZodSymbol({
3955
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
3956
- ...processCreateParams(params)
3957
- });
3958
- };
3959
- var _ZodUndefined = class _ZodUndefined extends ZodType {
3960
- _parse(input) {
3961
- const parsedType = this._getType(input);
3962
- if (parsedType !== ZodParsedType.undefined) {
3963
- const ctx = this._getOrReturnCtx(input);
3964
- addIssueToContext(ctx, {
3965
- code: ZodIssueCode.invalid_type,
3966
- expected: ZodParsedType.undefined,
3967
- received: ctx.parsedType
3968
- });
3969
- return INVALID;
3970
- }
3971
- return OK(input.data);
3972
- }
3973
- };
3974
- __name(_ZodUndefined, "ZodUndefined");
3975
- var ZodUndefined = _ZodUndefined;
3976
- ZodUndefined.create = (params) => {
3977
- return new ZodUndefined({
3978
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
3979
- ...processCreateParams(params)
3980
- });
3981
- };
3982
- var _ZodNull = class _ZodNull extends ZodType {
3983
- _parse(input) {
3984
- const parsedType = this._getType(input);
3985
- if (parsedType !== ZodParsedType.null) {
3986
- const ctx = this._getOrReturnCtx(input);
3987
- addIssueToContext(ctx, {
3988
- code: ZodIssueCode.invalid_type,
3989
- expected: ZodParsedType.null,
3990
- received: ctx.parsedType
3991
- });
3992
- return INVALID;
3993
- }
3994
- return OK(input.data);
3995
- }
3996
- };
3997
- __name(_ZodNull, "ZodNull");
3998
- var ZodNull = _ZodNull;
3999
- ZodNull.create = (params) => {
4000
- return new ZodNull({
4001
- typeName: ZodFirstPartyTypeKind.ZodNull,
4002
- ...processCreateParams(params)
4003
- });
4004
- };
4005
- var _ZodAny = class _ZodAny extends ZodType {
4006
- constructor() {
4007
- super(...arguments);
4008
- this._any = true;
4009
- }
4010
- _parse(input) {
4011
- return OK(input.data);
4012
- }
4013
- };
4014
- __name(_ZodAny, "ZodAny");
4015
- var ZodAny = _ZodAny;
4016
- ZodAny.create = (params) => {
4017
- return new ZodAny({
4018
- typeName: ZodFirstPartyTypeKind.ZodAny,
4019
- ...processCreateParams(params)
4020
- });
4021
- };
4022
- var _ZodUnknown = class _ZodUnknown extends ZodType {
4023
- constructor() {
4024
- super(...arguments);
4025
- this._unknown = true;
4026
- }
4027
- _parse(input) {
4028
- return OK(input.data);
4029
- }
4030
- };
4031
- __name(_ZodUnknown, "ZodUnknown");
4032
- var ZodUnknown = _ZodUnknown;
4033
- ZodUnknown.create = (params) => {
4034
- return new ZodUnknown({
4035
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
4036
- ...processCreateParams(params)
4037
- });
4038
- };
4039
- var _ZodNever = class _ZodNever extends ZodType {
4040
- _parse(input) {
4041
- const ctx = this._getOrReturnCtx(input);
4042
- addIssueToContext(ctx, {
4043
- code: ZodIssueCode.invalid_type,
4044
- expected: ZodParsedType.never,
4045
- received: ctx.parsedType
4046
- });
4047
- return INVALID;
4048
- }
4049
- };
4050
- __name(_ZodNever, "ZodNever");
4051
- var ZodNever = _ZodNever;
4052
- ZodNever.create = (params) => {
4053
- return new ZodNever({
4054
- typeName: ZodFirstPartyTypeKind.ZodNever,
4055
- ...processCreateParams(params)
4056
- });
4057
- };
4058
- var _ZodVoid = class _ZodVoid extends ZodType {
4059
- _parse(input) {
4060
- const parsedType = this._getType(input);
4061
- if (parsedType !== ZodParsedType.undefined) {
4062
- const ctx = this._getOrReturnCtx(input);
4063
- addIssueToContext(ctx, {
4064
- code: ZodIssueCode.invalid_type,
4065
- expected: ZodParsedType.void,
4066
- received: ctx.parsedType
4067
- });
4068
- return INVALID;
4069
- }
4070
- return OK(input.data);
4071
- }
4072
- };
4073
- __name(_ZodVoid, "ZodVoid");
4074
- var ZodVoid = _ZodVoid;
4075
- ZodVoid.create = (params) => {
4076
- return new ZodVoid({
4077
- typeName: ZodFirstPartyTypeKind.ZodVoid,
4078
- ...processCreateParams(params)
4079
- });
4080
- };
4081
- var _ZodArray = class _ZodArray extends ZodType {
4082
- _parse(input) {
4083
- const { ctx, status } = this._processInputParams(input);
4084
- const def = this._def;
4085
- if (ctx.parsedType !== ZodParsedType.array) {
4086
- addIssueToContext(ctx, {
4087
- code: ZodIssueCode.invalid_type,
4088
- expected: ZodParsedType.array,
4089
- received: ctx.parsedType
4090
- });
4091
- return INVALID;
4092
- }
4093
- if (def.exactLength !== null) {
4094
- const tooBig = ctx.data.length > def.exactLength.value;
4095
- const tooSmall = ctx.data.length < def.exactLength.value;
4096
- if (tooBig || tooSmall) {
4097
- addIssueToContext(ctx, {
4098
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
4099
- minimum: tooSmall ? def.exactLength.value : void 0,
4100
- maximum: tooBig ? def.exactLength.value : void 0,
4101
- type: "array",
4102
- inclusive: true,
4103
- exact: true,
4104
- message: def.exactLength.message
4105
- });
4106
- status.dirty();
4107
- }
4108
- }
4109
- if (def.minLength !== null) {
4110
- if (ctx.data.length < def.minLength.value) {
4111
- addIssueToContext(ctx, {
4112
- code: ZodIssueCode.too_small,
4113
- minimum: def.minLength.value,
4114
- type: "array",
4115
- inclusive: true,
4116
- exact: false,
4117
- message: def.minLength.message
4118
- });
4119
- status.dirty();
4120
- }
4121
- }
4122
- if (def.maxLength !== null) {
4123
- if (ctx.data.length > def.maxLength.value) {
4124
- addIssueToContext(ctx, {
4125
- code: ZodIssueCode.too_big,
4126
- maximum: def.maxLength.value,
4127
- type: "array",
4128
- inclusive: true,
4129
- exact: false,
4130
- message: def.maxLength.message
4131
- });
4132
- status.dirty();
4133
- }
4134
- }
4135
- if (ctx.common.async) {
4136
- return Promise.all([...ctx.data].map((item, i) => {
4137
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
4138
- })).then((result2) => {
4139
- return ParseStatus.mergeArray(status, result2);
4140
- });
4141
- }
4142
- const result = [...ctx.data].map((item, i) => {
4143
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
4144
- });
4145
- return ParseStatus.mergeArray(status, result);
4146
- }
4147
- get element() {
4148
- return this._def.type;
4149
- }
4150
- min(minLength, message) {
4151
- return new _ZodArray({
4152
- ...this._def,
4153
- minLength: { value: minLength, message: errorUtil.toString(message) }
4154
- });
4155
- }
4156
- max(maxLength, message) {
4157
- return new _ZodArray({
4158
- ...this._def,
4159
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
4160
- });
4161
- }
4162
- length(len, message) {
4163
- return new _ZodArray({
4164
- ...this._def,
4165
- exactLength: { value: len, message: errorUtil.toString(message) }
4166
- });
4167
- }
4168
- nonempty(message) {
4169
- return this.min(1, message);
4170
- }
4171
- };
4172
- __name(_ZodArray, "ZodArray");
4173
- var ZodArray = _ZodArray;
4174
- ZodArray.create = (schema, params) => {
4175
- return new ZodArray({
4176
- type: schema,
4177
- minLength: null,
4178
- maxLength: null,
4179
- exactLength: null,
4180
- typeName: ZodFirstPartyTypeKind.ZodArray,
4181
- ...processCreateParams(params)
4182
- });
4183
- };
4184
- function deepPartialify(schema) {
4185
- if (schema instanceof ZodObject) {
4186
- const newShape = {};
4187
- for (const key in schema.shape) {
4188
- const fieldSchema = schema.shape[key];
4189
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
4190
- }
4191
- return new ZodObject({
4192
- ...schema._def,
4193
- shape: () => newShape
4194
- });
4195
- } else if (schema instanceof ZodArray) {
4196
- return new ZodArray({
4197
- ...schema._def,
4198
- type: deepPartialify(schema.element)
4199
- });
4200
- } else if (schema instanceof ZodOptional) {
4201
- return ZodOptional.create(deepPartialify(schema.unwrap()));
4202
- } else if (schema instanceof ZodNullable) {
4203
- return ZodNullable.create(deepPartialify(schema.unwrap()));
4204
- } else if (schema instanceof ZodTuple) {
4205
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
4206
- } else {
4207
- return schema;
4208
- }
4209
- }
4210
- __name(deepPartialify, "deepPartialify");
4211
- var _ZodObject = class _ZodObject extends ZodType {
4212
- constructor() {
4213
- super(...arguments);
4214
- this._cached = null;
4215
- this.nonstrict = this.passthrough;
4216
- this.augment = this.extend;
4217
- }
4218
- _getCached() {
4219
- if (this._cached !== null)
4220
- return this._cached;
4221
- const shape = this._def.shape();
4222
- const keys = util.objectKeys(shape);
4223
- return this._cached = { shape, keys };
4224
- }
4225
- _parse(input) {
4226
- const parsedType = this._getType(input);
4227
- if (parsedType !== ZodParsedType.object) {
4228
- const ctx2 = this._getOrReturnCtx(input);
4229
- addIssueToContext(ctx2, {
4230
- code: ZodIssueCode.invalid_type,
4231
- expected: ZodParsedType.object,
4232
- received: ctx2.parsedType
4233
- });
4234
- return INVALID;
4235
- }
4236
- const { status, ctx } = this._processInputParams(input);
4237
- const { shape, keys: shapeKeys } = this._getCached();
4238
- const extraKeys = [];
4239
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
4240
- for (const key in ctx.data) {
4241
- if (!shapeKeys.includes(key)) {
4242
- extraKeys.push(key);
4243
- }
4244
- }
4245
- }
4246
- const pairs = [];
4247
- for (const key of shapeKeys) {
4248
- const keyValidator = shape[key];
4249
- const value = ctx.data[key];
4250
- pairs.push({
4251
- key: { status: "valid", value: key },
4252
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
4253
- alwaysSet: key in ctx.data
4254
- });
4255
- }
4256
- if (this._def.catchall instanceof ZodNever) {
4257
- const unknownKeys = this._def.unknownKeys;
4258
- if (unknownKeys === "passthrough") {
4259
- for (const key of extraKeys) {
4260
- pairs.push({
4261
- key: { status: "valid", value: key },
4262
- value: { status: "valid", value: ctx.data[key] }
4263
- });
4264
- }
4265
- } else if (unknownKeys === "strict") {
4266
- if (extraKeys.length > 0) {
4267
- addIssueToContext(ctx, {
4268
- code: ZodIssueCode.unrecognized_keys,
4269
- keys: extraKeys
4270
- });
4271
- status.dirty();
4272
- }
4273
- } else if (unknownKeys === "strip")
4274
- ;
4275
- else {
4276
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
4277
- }
4278
- } else {
4279
- const catchall = this._def.catchall;
4280
- for (const key of extraKeys) {
4281
- const value = ctx.data[key];
4282
- pairs.push({
4283
- key: { status: "valid", value: key },
4284
- value: catchall._parse(
4285
- new ParseInputLazyPath(ctx, value, ctx.path, key)
4286
- //, ctx.child(key), value, getParsedType(value)
4287
- ),
4288
- alwaysSet: key in ctx.data
4289
- });
4290
- }
4291
- }
4292
- if (ctx.common.async) {
4293
- return Promise.resolve().then(async () => {
4294
- const syncPairs = [];
4295
- for (const pair of pairs) {
4296
- const key = await pair.key;
4297
- syncPairs.push({
4298
- key,
4299
- value: await pair.value,
4300
- alwaysSet: pair.alwaysSet
4301
- });
4302
- }
4303
- return syncPairs;
4304
- }).then((syncPairs) => {
4305
- return ParseStatus.mergeObjectSync(status, syncPairs);
4306
- });
4307
- } else {
4308
- return ParseStatus.mergeObjectSync(status, pairs);
4309
- }
4310
- }
4311
- get shape() {
4312
- return this._def.shape();
4313
- }
4314
- strict(message) {
4315
- errorUtil.errToObj;
4316
- return new _ZodObject({
4317
- ...this._def,
4318
- unknownKeys: "strict",
4319
- ...message !== void 0 ? {
4320
- errorMap: (issue, ctx) => {
4321
- var _a, _b, _c, _d;
4322
- const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
4323
- if (issue.code === "unrecognized_keys")
4324
- return {
4325
- message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
4326
- };
4327
- return {
4328
- message: defaultError
4329
- };
4330
- }
4331
- } : {}
4332
- });
4333
- }
4334
- strip() {
4335
- return new _ZodObject({
4336
- ...this._def,
4337
- unknownKeys: "strip"
4338
- });
4339
- }
4340
- passthrough() {
4341
- return new _ZodObject({
4342
- ...this._def,
4343
- unknownKeys: "passthrough"
4344
- });
4345
- }
4346
- // const AugmentFactory =
4347
- // <Def extends ZodObjectDef>(def: Def) =>
4348
- // <Augmentation extends ZodRawShape>(
4349
- // augmentation: Augmentation
4350
- // ): ZodObject<
4351
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
4352
- // Def["unknownKeys"],
4353
- // Def["catchall"]
4354
- // > => {
4355
- // return new ZodObject({
4356
- // ...def,
4357
- // shape: () => ({
4358
- // ...def.shape(),
4359
- // ...augmentation,
4360
- // }),
4361
- // }) as any;
4362
- // };
4363
- extend(augmentation) {
4364
- return new _ZodObject({
4365
- ...this._def,
4366
- shape: () => ({
4367
- ...this._def.shape(),
4368
- ...augmentation
4369
- })
4370
- });
4371
- }
4372
- /**
4373
- * Prior to zod@1.0.12 there was a bug in the
4374
- * inferred type of merged objects. Please
4375
- * upgrade if you are experiencing issues.
4376
- */
4377
- merge(merging) {
4378
- const merged = new _ZodObject({
4379
- unknownKeys: merging._def.unknownKeys,
4380
- catchall: merging._def.catchall,
4381
- shape: () => ({
4382
- ...this._def.shape(),
4383
- ...merging._def.shape()
4384
- }),
4385
- typeName: ZodFirstPartyTypeKind.ZodObject
4386
- });
4387
- return merged;
4388
- }
4389
- // merge<
4390
- // Incoming extends AnyZodObject,
4391
- // Augmentation extends Incoming["shape"],
4392
- // NewOutput extends {
4393
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
4394
- // ? Augmentation[k]["_output"]
4395
- // : k extends keyof Output
4396
- // ? Output[k]
4397
- // : never;
4398
- // },
4399
- // NewInput extends {
4400
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
4401
- // ? Augmentation[k]["_input"]
4402
- // : k extends keyof Input
4403
- // ? Input[k]
4404
- // : never;
4405
- // }
4406
- // >(
4407
- // merging: Incoming
4408
- // ): ZodObject<
4409
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
4410
- // Incoming["_def"]["unknownKeys"],
4411
- // Incoming["_def"]["catchall"],
4412
- // NewOutput,
4413
- // NewInput
4414
- // > {
4415
- // const merged: any = new ZodObject({
4416
- // unknownKeys: merging._def.unknownKeys,
4417
- // catchall: merging._def.catchall,
4418
- // shape: () =>
4419
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
4420
- // typeName: ZodFirstPartyTypeKind.ZodObject,
4421
- // }) as any;
4422
- // return merged;
4423
- // }
4424
- setKey(key, schema) {
4425
- return this.augment({ [key]: schema });
4426
- }
4427
- // merge<Incoming extends AnyZodObject>(
4428
- // merging: Incoming
4429
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
4430
- // ZodObject<
4431
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
4432
- // Incoming["_def"]["unknownKeys"],
4433
- // Incoming["_def"]["catchall"]
4434
- // > {
4435
- // // const mergedShape = objectUtil.mergeShapes(
4436
- // // this._def.shape(),
4437
- // // merging._def.shape()
4438
- // // );
4439
- // const merged: any = new ZodObject({
4440
- // unknownKeys: merging._def.unknownKeys,
4441
- // catchall: merging._def.catchall,
4442
- // shape: () =>
4443
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
4444
- // typeName: ZodFirstPartyTypeKind.ZodObject,
4445
- // }) as any;
4446
- // return merged;
4447
- // }
4448
- catchall(index) {
4449
- return new _ZodObject({
4450
- ...this._def,
4451
- catchall: index
4452
- });
4453
- }
4454
- pick(mask) {
4455
- const shape = {};
4456
- util.objectKeys(mask).forEach((key) => {
4457
- if (mask[key] && this.shape[key]) {
4458
- shape[key] = this.shape[key];
4459
- }
4460
- });
4461
- return new _ZodObject({
4462
- ...this._def,
4463
- shape: () => shape
4464
- });
4465
- }
4466
- omit(mask) {
4467
- const shape = {};
4468
- util.objectKeys(this.shape).forEach((key) => {
4469
- if (!mask[key]) {
4470
- shape[key] = this.shape[key];
4471
- }
4472
- });
4473
- return new _ZodObject({
4474
- ...this._def,
4475
- shape: () => shape
4476
- });
4477
- }
4478
- /**
4479
- * @deprecated
4480
- */
4481
- deepPartial() {
4482
- return deepPartialify(this);
4483
- }
4484
- partial(mask) {
4485
- const newShape = {};
4486
- util.objectKeys(this.shape).forEach((key) => {
4487
- const fieldSchema = this.shape[key];
4488
- if (mask && !mask[key]) {
4489
- newShape[key] = fieldSchema;
4490
- } else {
4491
- newShape[key] = fieldSchema.optional();
4492
- }
4493
- });
4494
- return new _ZodObject({
4495
- ...this._def,
4496
- shape: () => newShape
4497
- });
4498
- }
4499
- required(mask) {
4500
- const newShape = {};
4501
- util.objectKeys(this.shape).forEach((key) => {
4502
- if (mask && !mask[key]) {
4503
- newShape[key] = this.shape[key];
4504
- } else {
4505
- const fieldSchema = this.shape[key];
4506
- let newField = fieldSchema;
4507
- while (newField instanceof ZodOptional) {
4508
- newField = newField._def.innerType;
4509
- }
4510
- newShape[key] = newField;
4511
- }
4512
- });
4513
- return new _ZodObject({
4514
- ...this._def,
4515
- shape: () => newShape
4516
- });
4517
- }
4518
- keyof() {
4519
- return createZodEnum(util.objectKeys(this.shape));
4520
- }
4521
- };
4522
- __name(_ZodObject, "ZodObject");
4523
- var ZodObject = _ZodObject;
4524
- ZodObject.create = (shape, params) => {
4525
- return new ZodObject({
4526
- shape: () => shape,
4527
- unknownKeys: "strip",
4528
- catchall: ZodNever.create(),
4529
- typeName: ZodFirstPartyTypeKind.ZodObject,
4530
- ...processCreateParams(params)
4531
- });
4532
- };
4533
- ZodObject.strictCreate = (shape, params) => {
4534
- return new ZodObject({
4535
- shape: () => shape,
4536
- unknownKeys: "strict",
4537
- catchall: ZodNever.create(),
4538
- typeName: ZodFirstPartyTypeKind.ZodObject,
4539
- ...processCreateParams(params)
4540
- });
4541
- };
4542
- ZodObject.lazycreate = (shape, params) => {
4543
- return new ZodObject({
4544
- shape,
4545
- unknownKeys: "strip",
4546
- catchall: ZodNever.create(),
4547
- typeName: ZodFirstPartyTypeKind.ZodObject,
4548
- ...processCreateParams(params)
4549
- });
4550
- };
4551
- var _ZodUnion = class _ZodUnion extends ZodType {
4552
- _parse(input) {
4553
- const { ctx } = this._processInputParams(input);
4554
- const options = this._def.options;
4555
- function handleResults(results) {
4556
- for (const result of results) {
4557
- if (result.result.status === "valid") {
4558
- return result.result;
4559
- }
4560
- }
4561
- for (const result of results) {
4562
- if (result.result.status === "dirty") {
4563
- ctx.common.issues.push(...result.ctx.common.issues);
4564
- return result.result;
4565
- }
4566
- }
4567
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
4568
- addIssueToContext(ctx, {
4569
- code: ZodIssueCode.invalid_union,
4570
- unionErrors
4571
- });
4572
- return INVALID;
4573
- }
4574
- __name(handleResults, "handleResults");
4575
- if (ctx.common.async) {
4576
- return Promise.all(options.map(async (option) => {
4577
- const childCtx = {
4578
- ...ctx,
4579
- common: {
4580
- ...ctx.common,
4581
- issues: []
4582
- },
4583
- parent: null
4584
- };
4585
- return {
4586
- result: await option._parseAsync({
4587
- data: ctx.data,
4588
- path: ctx.path,
4589
- parent: childCtx
4590
- }),
4591
- ctx: childCtx
4592
- };
4593
- })).then(handleResults);
4594
- } else {
4595
- let dirty = void 0;
4596
- const issues = [];
4597
- for (const option of options) {
4598
- const childCtx = {
4599
- ...ctx,
4600
- common: {
4601
- ...ctx.common,
4602
- issues: []
4603
- },
4604
- parent: null
4605
- };
4606
- const result = option._parseSync({
4607
- data: ctx.data,
4608
- path: ctx.path,
4609
- parent: childCtx
4610
- });
4611
- if (result.status === "valid") {
4612
- return result;
4613
- } else if (result.status === "dirty" && !dirty) {
4614
- dirty = { result, ctx: childCtx };
4615
- }
4616
- if (childCtx.common.issues.length) {
4617
- issues.push(childCtx.common.issues);
4618
- }
4619
- }
4620
- if (dirty) {
4621
- ctx.common.issues.push(...dirty.ctx.common.issues);
4622
- return dirty.result;
4623
- }
4624
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
4625
- addIssueToContext(ctx, {
4626
- code: ZodIssueCode.invalid_union,
4627
- unionErrors
4628
- });
4629
- return INVALID;
4630
- }
4631
- }
4632
- get options() {
4633
- return this._def.options;
4634
- }
4635
- };
4636
- __name(_ZodUnion, "ZodUnion");
4637
- var ZodUnion = _ZodUnion;
4638
- ZodUnion.create = (types, params) => {
4639
- return new ZodUnion({
4640
- options: types,
4641
- typeName: ZodFirstPartyTypeKind.ZodUnion,
4642
- ...processCreateParams(params)
4643
- });
4644
- };
4645
- var getDiscriminator = /* @__PURE__ */ __name((type) => {
4646
- if (type instanceof ZodLazy) {
4647
- return getDiscriminator(type.schema);
4648
- } else if (type instanceof ZodEffects) {
4649
- return getDiscriminator(type.innerType());
4650
- } else if (type instanceof ZodLiteral) {
4651
- return [type.value];
4652
- } else if (type instanceof ZodEnum) {
4653
- return type.options;
4654
- } else if (type instanceof ZodNativeEnum) {
4655
- return Object.keys(type.enum);
4656
- } else if (type instanceof ZodDefault) {
4657
- return getDiscriminator(type._def.innerType);
4658
- } else if (type instanceof ZodUndefined) {
4659
- return [void 0];
4660
- } else if (type instanceof ZodNull) {
4661
- return [null];
4662
- } else {
4663
- return null;
4664
- }
4665
- }, "getDiscriminator");
4666
- var _ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
4667
- _parse(input) {
4668
- const { ctx } = this._processInputParams(input);
4669
- if (ctx.parsedType !== ZodParsedType.object) {
4670
- addIssueToContext(ctx, {
4671
- code: ZodIssueCode.invalid_type,
4672
- expected: ZodParsedType.object,
4673
- received: ctx.parsedType
4674
- });
4675
- return INVALID;
4676
- }
4677
- const discriminator = this.discriminator;
4678
- const discriminatorValue = ctx.data[discriminator];
4679
- const option = this.optionsMap.get(discriminatorValue);
4680
- if (!option) {
4681
- addIssueToContext(ctx, {
4682
- code: ZodIssueCode.invalid_union_discriminator,
4683
- options: Array.from(this.optionsMap.keys()),
4684
- path: [discriminator]
4685
- });
4686
- return INVALID;
4687
- }
4688
- if (ctx.common.async) {
4689
- return option._parseAsync({
4690
- data: ctx.data,
4691
- path: ctx.path,
4692
- parent: ctx
4693
- });
4694
- } else {
4695
- return option._parseSync({
4696
- data: ctx.data,
4697
- path: ctx.path,
4698
- parent: ctx
4699
- });
4700
- }
4701
- }
4702
- get discriminator() {
4703
- return this._def.discriminator;
4704
- }
4705
- get options() {
4706
- return this._def.options;
4707
- }
4708
- get optionsMap() {
4709
- return this._def.optionsMap;
4710
- }
4711
- /**
4712
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
4713
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
4714
- * have a different value for each object in the union.
4715
- * @param discriminator the name of the discriminator property
4716
- * @param types an array of object schemas
4717
- * @param params
4718
- */
4719
- static create(discriminator, options, params) {
4720
- const optionsMap = /* @__PURE__ */ new Map();
4721
- for (const type of options) {
4722
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
4723
- if (!discriminatorValues) {
4724
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
4725
- }
4726
- for (const value of discriminatorValues) {
4727
- if (optionsMap.has(value)) {
4728
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
4729
- }
4730
- optionsMap.set(value, type);
4731
- }
4732
- }
4733
- return new _ZodDiscriminatedUnion({
4734
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
4735
- discriminator,
4736
- options,
4737
- optionsMap,
4738
- ...processCreateParams(params)
4739
- });
4740
- }
4741
- };
4742
- __name(_ZodDiscriminatedUnion, "ZodDiscriminatedUnion");
4743
- var ZodDiscriminatedUnion = _ZodDiscriminatedUnion;
4744
- function mergeValues(a, b) {
4745
- const aType = getParsedType(a);
4746
- const bType = getParsedType(b);
4747
- if (a === b) {
4748
- return { valid: true, data: a };
4749
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
4750
- const bKeys = util.objectKeys(b);
4751
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
4752
- const newObj = { ...a, ...b };
4753
- for (const key of sharedKeys) {
4754
- const sharedValue = mergeValues(a[key], b[key]);
4755
- if (!sharedValue.valid) {
4756
- return { valid: false };
4757
- }
4758
- newObj[key] = sharedValue.data;
4759
- }
4760
- return { valid: true, data: newObj };
4761
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
4762
- if (a.length !== b.length) {
4763
- return { valid: false };
4764
- }
4765
- const newArray = [];
4766
- for (let index = 0; index < a.length; index++) {
4767
- const itemA = a[index];
4768
- const itemB = b[index];
4769
- const sharedValue = mergeValues(itemA, itemB);
4770
- if (!sharedValue.valid) {
4771
- return { valid: false };
4772
- }
4773
- newArray.push(sharedValue.data);
4774
- }
4775
- return { valid: true, data: newArray };
4776
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
4777
- return { valid: true, data: a };
4778
- } else {
4779
- return { valid: false };
4780
- }
4781
- }
4782
- __name(mergeValues, "mergeValues");
4783
- var _ZodIntersection = class _ZodIntersection extends ZodType {
4784
- _parse(input) {
4785
- const { status, ctx } = this._processInputParams(input);
4786
- const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
4787
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
4788
- return INVALID;
4789
- }
4790
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
4791
- if (!merged.valid) {
4792
- addIssueToContext(ctx, {
4793
- code: ZodIssueCode.invalid_intersection_types
4794
- });
4795
- return INVALID;
4796
- }
4797
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
4798
- status.dirty();
4799
- }
4800
- return { status: status.value, value: merged.data };
4801
- }, "handleParsed");
4802
- if (ctx.common.async) {
4803
- return Promise.all([
4804
- this._def.left._parseAsync({
4805
- data: ctx.data,
4806
- path: ctx.path,
4807
- parent: ctx
4808
- }),
4809
- this._def.right._parseAsync({
4810
- data: ctx.data,
4811
- path: ctx.path,
4812
- parent: ctx
4813
- })
4814
- ]).then(([left, right]) => handleParsed(left, right));
4815
- } else {
4816
- return handleParsed(this._def.left._parseSync({
4817
- data: ctx.data,
4818
- path: ctx.path,
4819
- parent: ctx
4820
- }), this._def.right._parseSync({
4821
- data: ctx.data,
4822
- path: ctx.path,
4823
- parent: ctx
4824
- }));
4825
- }
4826
- }
4827
- };
4828
- __name(_ZodIntersection, "ZodIntersection");
4829
- var ZodIntersection = _ZodIntersection;
4830
- ZodIntersection.create = (left, right, params) => {
4831
- return new ZodIntersection({
4832
- left,
4833
- right,
4834
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
4835
- ...processCreateParams(params)
4836
- });
4837
- };
4838
- var _ZodTuple = class _ZodTuple extends ZodType {
4839
- _parse(input) {
4840
- const { status, ctx } = this._processInputParams(input);
4841
- if (ctx.parsedType !== ZodParsedType.array) {
4842
- addIssueToContext(ctx, {
4843
- code: ZodIssueCode.invalid_type,
4844
- expected: ZodParsedType.array,
4845
- received: ctx.parsedType
4846
- });
4847
- return INVALID;
4848
- }
4849
- if (ctx.data.length < this._def.items.length) {
4850
- addIssueToContext(ctx, {
4851
- code: ZodIssueCode.too_small,
4852
- minimum: this._def.items.length,
4853
- inclusive: true,
4854
- exact: false,
4855
- type: "array"
4856
- });
4857
- return INVALID;
4858
- }
4859
- const rest = this._def.rest;
4860
- if (!rest && ctx.data.length > this._def.items.length) {
4861
- addIssueToContext(ctx, {
4862
- code: ZodIssueCode.too_big,
4863
- maximum: this._def.items.length,
4864
- inclusive: true,
4865
- exact: false,
4866
- type: "array"
4867
- });
4868
- status.dirty();
4869
- }
4870
- const items = [...ctx.data].map((item, itemIndex) => {
4871
- const schema = this._def.items[itemIndex] || this._def.rest;
4872
- if (!schema)
4873
- return null;
4874
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
4875
- }).filter((x) => !!x);
4876
- if (ctx.common.async) {
4877
- return Promise.all(items).then((results) => {
4878
- return ParseStatus.mergeArray(status, results);
4879
- });
4880
- } else {
4881
- return ParseStatus.mergeArray(status, items);
4882
- }
4883
- }
4884
- get items() {
4885
- return this._def.items;
4886
- }
4887
- rest(rest) {
4888
- return new _ZodTuple({
4889
- ...this._def,
4890
- rest
4891
- });
4892
- }
4893
- };
4894
- __name(_ZodTuple, "ZodTuple");
4895
- var ZodTuple = _ZodTuple;
4896
- ZodTuple.create = (schemas, params) => {
4897
- if (!Array.isArray(schemas)) {
4898
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
4899
- }
4900
- return new ZodTuple({
4901
- items: schemas,
4902
- typeName: ZodFirstPartyTypeKind.ZodTuple,
4903
- rest: null,
4904
- ...processCreateParams(params)
4905
- });
4906
- };
4907
- var _ZodRecord = class _ZodRecord extends ZodType {
4908
- get keySchema() {
4909
- return this._def.keyType;
4910
- }
4911
- get valueSchema() {
4912
- return this._def.valueType;
4913
- }
4914
- _parse(input) {
4915
- const { status, ctx } = this._processInputParams(input);
4916
- if (ctx.parsedType !== ZodParsedType.object) {
4917
- addIssueToContext(ctx, {
4918
- code: ZodIssueCode.invalid_type,
4919
- expected: ZodParsedType.object,
4920
- received: ctx.parsedType
4921
- });
4922
- return INVALID;
4923
- }
4924
- const pairs = [];
4925
- const keyType = this._def.keyType;
4926
- const valueType = this._def.valueType;
4927
- for (const key in ctx.data) {
4928
- pairs.push({
4929
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
4930
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key))
4931
- });
4932
- }
4933
- if (ctx.common.async) {
4934
- return ParseStatus.mergeObjectAsync(status, pairs);
4935
- } else {
4936
- return ParseStatus.mergeObjectSync(status, pairs);
4937
- }
4938
- }
4939
- get element() {
4940
- return this._def.valueType;
4941
- }
4942
- static create(first, second, third) {
4943
- if (second instanceof ZodType) {
4944
- return new _ZodRecord({
4945
- keyType: first,
4946
- valueType: second,
4947
- typeName: ZodFirstPartyTypeKind.ZodRecord,
4948
- ...processCreateParams(third)
4949
- });
4950
- }
4951
- return new _ZodRecord({
4952
- keyType: ZodString.create(),
4953
- valueType: first,
4954
- typeName: ZodFirstPartyTypeKind.ZodRecord,
4955
- ...processCreateParams(second)
4956
- });
4957
- }
4958
- };
4959
- __name(_ZodRecord, "ZodRecord");
4960
- var ZodRecord = _ZodRecord;
4961
- var _ZodMap = class _ZodMap extends ZodType {
4962
- get keySchema() {
4963
- return this._def.keyType;
4964
- }
4965
- get valueSchema() {
4966
- return this._def.valueType;
4967
- }
4968
- _parse(input) {
4969
- const { status, ctx } = this._processInputParams(input);
4970
- if (ctx.parsedType !== ZodParsedType.map) {
4971
- addIssueToContext(ctx, {
4972
- code: ZodIssueCode.invalid_type,
4973
- expected: ZodParsedType.map,
4974
- received: ctx.parsedType
4975
- });
4976
- return INVALID;
4977
- }
4978
- const keyType = this._def.keyType;
4979
- const valueType = this._def.valueType;
4980
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
4981
- return {
4982
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
4983
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
4984
- };
4985
- });
4986
- if (ctx.common.async) {
4987
- const finalMap = /* @__PURE__ */ new Map();
4988
- return Promise.resolve().then(async () => {
4989
- for (const pair of pairs) {
4990
- const key = await pair.key;
4991
- const value = await pair.value;
4992
- if (key.status === "aborted" || value.status === "aborted") {
4993
- return INVALID;
4994
- }
4995
- if (key.status === "dirty" || value.status === "dirty") {
4996
- status.dirty();
4997
- }
4998
- finalMap.set(key.value, value.value);
4999
- }
5000
- return { status: status.value, value: finalMap };
5001
- });
5002
- } else {
5003
- const finalMap = /* @__PURE__ */ new Map();
5004
- for (const pair of pairs) {
5005
- const key = pair.key;
5006
- const value = pair.value;
5007
- if (key.status === "aborted" || value.status === "aborted") {
5008
- return INVALID;
5009
- }
5010
- if (key.status === "dirty" || value.status === "dirty") {
5011
- status.dirty();
5012
- }
5013
- finalMap.set(key.value, value.value);
5014
- }
5015
- return { status: status.value, value: finalMap };
5016
- }
5017
- }
5018
- };
5019
- __name(_ZodMap, "ZodMap");
5020
- var ZodMap = _ZodMap;
5021
- ZodMap.create = (keyType, valueType, params) => {
5022
- return new ZodMap({
5023
- valueType,
5024
- keyType,
5025
- typeName: ZodFirstPartyTypeKind.ZodMap,
5026
- ...processCreateParams(params)
5027
- });
5028
- };
5029
- var _ZodSet = class _ZodSet extends ZodType {
5030
- _parse(input) {
5031
- const { status, ctx } = this._processInputParams(input);
5032
- if (ctx.parsedType !== ZodParsedType.set) {
5033
- addIssueToContext(ctx, {
5034
- code: ZodIssueCode.invalid_type,
5035
- expected: ZodParsedType.set,
5036
- received: ctx.parsedType
5037
- });
5038
- return INVALID;
5039
- }
5040
- const def = this._def;
5041
- if (def.minSize !== null) {
5042
- if (ctx.data.size < def.minSize.value) {
5043
- addIssueToContext(ctx, {
5044
- code: ZodIssueCode.too_small,
5045
- minimum: def.minSize.value,
5046
- type: "set",
5047
- inclusive: true,
5048
- exact: false,
5049
- message: def.minSize.message
5050
- });
5051
- status.dirty();
5052
- }
5053
- }
5054
- if (def.maxSize !== null) {
5055
- if (ctx.data.size > def.maxSize.value) {
5056
- addIssueToContext(ctx, {
5057
- code: ZodIssueCode.too_big,
5058
- maximum: def.maxSize.value,
5059
- type: "set",
5060
- inclusive: true,
5061
- exact: false,
5062
- message: def.maxSize.message
5063
- });
5064
- status.dirty();
5065
- }
5066
- }
5067
- const valueType = this._def.valueType;
5068
- function finalizeSet(elements2) {
5069
- const parsedSet = /* @__PURE__ */ new Set();
5070
- for (const element of elements2) {
5071
- if (element.status === "aborted")
5072
- return INVALID;
5073
- if (element.status === "dirty")
5074
- status.dirty();
5075
- parsedSet.add(element.value);
5076
- }
5077
- return { status: status.value, value: parsedSet };
5078
- }
5079
- __name(finalizeSet, "finalizeSet");
5080
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
5081
- if (ctx.common.async) {
5082
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
5083
- } else {
5084
- return finalizeSet(elements);
5085
- }
5086
- }
5087
- min(minSize, message) {
5088
- return new _ZodSet({
5089
- ...this._def,
5090
- minSize: { value: minSize, message: errorUtil.toString(message) }
5091
- });
5092
- }
5093
- max(maxSize, message) {
5094
- return new _ZodSet({
5095
- ...this._def,
5096
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
5097
- });
5098
- }
5099
- size(size, message) {
5100
- return this.min(size, message).max(size, message);
5101
- }
5102
- nonempty(message) {
5103
- return this.min(1, message);
5104
- }
5105
- };
5106
- __name(_ZodSet, "ZodSet");
5107
- var ZodSet = _ZodSet;
5108
- ZodSet.create = (valueType, params) => {
5109
- return new ZodSet({
5110
- valueType,
5111
- minSize: null,
5112
- maxSize: null,
5113
- typeName: ZodFirstPartyTypeKind.ZodSet,
5114
- ...processCreateParams(params)
5115
- });
5116
- };
5117
- var _ZodFunction = class _ZodFunction extends ZodType {
5118
- constructor() {
5119
- super(...arguments);
5120
- this.validate = this.implement;
5121
- }
5122
- _parse(input) {
5123
- const { ctx } = this._processInputParams(input);
5124
- if (ctx.parsedType !== ZodParsedType.function) {
5125
- addIssueToContext(ctx, {
5126
- code: ZodIssueCode.invalid_type,
5127
- expected: ZodParsedType.function,
5128
- received: ctx.parsedType
5129
- });
5130
- return INVALID;
5131
- }
5132
- function makeArgsIssue(args, error) {
5133
- return makeIssue({
5134
- data: args,
5135
- path: ctx.path,
5136
- errorMaps: [
5137
- ctx.common.contextualErrorMap,
5138
- ctx.schemaErrorMap,
5139
- getErrorMap(),
5140
- errorMap
5141
- ].filter((x) => !!x),
5142
- issueData: {
5143
- code: ZodIssueCode.invalid_arguments,
5144
- argumentsError: error
5145
- }
5146
- });
5147
- }
5148
- __name(makeArgsIssue, "makeArgsIssue");
5149
- function makeReturnsIssue(returns, error) {
5150
- return makeIssue({
5151
- data: returns,
5152
- path: ctx.path,
5153
- errorMaps: [
5154
- ctx.common.contextualErrorMap,
5155
- ctx.schemaErrorMap,
5156
- getErrorMap(),
5157
- errorMap
5158
- ].filter((x) => !!x),
5159
- issueData: {
5160
- code: ZodIssueCode.invalid_return_type,
5161
- returnTypeError: error
5162
- }
5163
- });
5164
- }
5165
- __name(makeReturnsIssue, "makeReturnsIssue");
5166
- const params = { errorMap: ctx.common.contextualErrorMap };
5167
- const fn = ctx.data;
5168
- if (this._def.returns instanceof ZodPromise) {
5169
- const me = this;
5170
- return OK(async function(...args) {
5171
- const error = new ZodError([]);
5172
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
5173
- error.addIssue(makeArgsIssue(args, e));
5174
- throw error;
5175
- });
5176
- const result = await Reflect.apply(fn, this, parsedArgs);
5177
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
5178
- error.addIssue(makeReturnsIssue(result, e));
5179
- throw error;
5180
- });
5181
- return parsedReturns;
5182
- });
5183
- } else {
5184
- const me = this;
5185
- return OK(function(...args) {
5186
- const parsedArgs = me._def.args.safeParse(args, params);
5187
- if (!parsedArgs.success) {
5188
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
5189
- }
5190
- const result = Reflect.apply(fn, this, parsedArgs.data);
5191
- const parsedReturns = me._def.returns.safeParse(result, params);
5192
- if (!parsedReturns.success) {
5193
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
5194
- }
5195
- return parsedReturns.data;
5196
- });
5197
- }
5198
- }
5199
- parameters() {
5200
- return this._def.args;
5201
- }
5202
- returnType() {
5203
- return this._def.returns;
5204
- }
5205
- args(...items) {
5206
- return new _ZodFunction({
5207
- ...this._def,
5208
- args: ZodTuple.create(items).rest(ZodUnknown.create())
5209
- });
5210
- }
5211
- returns(returnType) {
5212
- return new _ZodFunction({
5213
- ...this._def,
5214
- returns: returnType
5215
- });
5216
- }
5217
- implement(func) {
5218
- const validatedFunc = this.parse(func);
5219
- return validatedFunc;
5220
- }
5221
- strictImplement(func) {
5222
- const validatedFunc = this.parse(func);
5223
- return validatedFunc;
5224
- }
5225
- static create(args, returns, params) {
5226
- return new _ZodFunction({
5227
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
5228
- returns: returns || ZodUnknown.create(),
5229
- typeName: ZodFirstPartyTypeKind.ZodFunction,
5230
- ...processCreateParams(params)
5231
- });
5232
- }
5233
- };
5234
- __name(_ZodFunction, "ZodFunction");
5235
- var ZodFunction = _ZodFunction;
5236
- var _ZodLazy = class _ZodLazy extends ZodType {
5237
- get schema() {
5238
- return this._def.getter();
5239
- }
5240
- _parse(input) {
5241
- const { ctx } = this._processInputParams(input);
5242
- const lazySchema = this._def.getter();
5243
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
5244
- }
5245
- };
5246
- __name(_ZodLazy, "ZodLazy");
5247
- var ZodLazy = _ZodLazy;
5248
- ZodLazy.create = (getter, params) => {
5249
- return new ZodLazy({
5250
- getter,
5251
- typeName: ZodFirstPartyTypeKind.ZodLazy,
5252
- ...processCreateParams(params)
5253
- });
5254
- };
5255
- var _ZodLiteral = class _ZodLiteral extends ZodType {
5256
- _parse(input) {
5257
- if (input.data !== this._def.value) {
5258
- const ctx = this._getOrReturnCtx(input);
5259
- addIssueToContext(ctx, {
5260
- received: ctx.data,
5261
- code: ZodIssueCode.invalid_literal,
5262
- expected: this._def.value
5263
- });
5264
- return INVALID;
5265
- }
5266
- return { status: "valid", value: input.data };
5267
- }
5268
- get value() {
5269
- return this._def.value;
5270
- }
5271
- };
5272
- __name(_ZodLiteral, "ZodLiteral");
5273
- var ZodLiteral = _ZodLiteral;
5274
- ZodLiteral.create = (value, params) => {
5275
- return new ZodLiteral({
5276
- value,
5277
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
5278
- ...processCreateParams(params)
5279
- });
5280
- };
5281
- function createZodEnum(values, params) {
5282
- return new ZodEnum({
5283
- values,
5284
- typeName: ZodFirstPartyTypeKind.ZodEnum,
5285
- ...processCreateParams(params)
5286
- });
5287
- }
5288
- __name(createZodEnum, "createZodEnum");
5289
- var _ZodEnum = class _ZodEnum extends ZodType {
5290
- _parse(input) {
5291
- if (typeof input.data !== "string") {
5292
- const ctx = this._getOrReturnCtx(input);
5293
- const expectedValues = this._def.values;
5294
- addIssueToContext(ctx, {
5295
- expected: util.joinValues(expectedValues),
5296
- received: ctx.parsedType,
5297
- code: ZodIssueCode.invalid_type
5298
- });
5299
- return INVALID;
5300
- }
5301
- if (this._def.values.indexOf(input.data) === -1) {
5302
- const ctx = this._getOrReturnCtx(input);
5303
- const expectedValues = this._def.values;
5304
- addIssueToContext(ctx, {
5305
- received: ctx.data,
5306
- code: ZodIssueCode.invalid_enum_value,
5307
- options: expectedValues
5308
- });
5309
- return INVALID;
5310
- }
5311
- return OK(input.data);
5312
- }
5313
- get options() {
5314
- return this._def.values;
5315
- }
5316
- get enum() {
5317
- const enumValues = {};
5318
- for (const val of this._def.values) {
5319
- enumValues[val] = val;
5320
- }
5321
- return enumValues;
5322
- }
5323
- get Values() {
5324
- const enumValues = {};
5325
- for (const val of this._def.values) {
5326
- enumValues[val] = val;
5327
- }
5328
- return enumValues;
5329
- }
5330
- get Enum() {
5331
- const enumValues = {};
5332
- for (const val of this._def.values) {
5333
- enumValues[val] = val;
5334
- }
5335
- return enumValues;
5336
- }
5337
- extract(values) {
5338
- return _ZodEnum.create(values);
5339
- }
5340
- exclude(values) {
5341
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
5342
- }
5343
- };
5344
- __name(_ZodEnum, "ZodEnum");
5345
- var ZodEnum = _ZodEnum;
5346
- ZodEnum.create = createZodEnum;
5347
- var _ZodNativeEnum = class _ZodNativeEnum extends ZodType {
5348
- _parse(input) {
5349
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
5350
- const ctx = this._getOrReturnCtx(input);
5351
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
5352
- const expectedValues = util.objectValues(nativeEnumValues);
5353
- addIssueToContext(ctx, {
5354
- expected: util.joinValues(expectedValues),
5355
- received: ctx.parsedType,
5356
- code: ZodIssueCode.invalid_type
5357
- });
5358
- return INVALID;
5359
- }
5360
- if (nativeEnumValues.indexOf(input.data) === -1) {
5361
- const expectedValues = util.objectValues(nativeEnumValues);
5362
- addIssueToContext(ctx, {
5363
- received: ctx.data,
5364
- code: ZodIssueCode.invalid_enum_value,
5365
- options: expectedValues
5366
- });
5367
- return INVALID;
5368
- }
5369
- return OK(input.data);
5370
- }
5371
- get enum() {
5372
- return this._def.values;
5373
- }
5374
- };
5375
- __name(_ZodNativeEnum, "ZodNativeEnum");
5376
- var ZodNativeEnum = _ZodNativeEnum;
5377
- ZodNativeEnum.create = (values, params) => {
5378
- return new ZodNativeEnum({
5379
- values,
5380
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
5381
- ...processCreateParams(params)
5382
- });
5383
- };
5384
- var _ZodPromise = class _ZodPromise extends ZodType {
5385
- unwrap() {
5386
- return this._def.type;
5387
- }
5388
- _parse(input) {
5389
- const { ctx } = this._processInputParams(input);
5390
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
5391
- addIssueToContext(ctx, {
5392
- code: ZodIssueCode.invalid_type,
5393
- expected: ZodParsedType.promise,
5394
- received: ctx.parsedType
5395
- });
5396
- return INVALID;
5397
- }
5398
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
5399
- return OK(promisified.then((data) => {
5400
- return this._def.type.parseAsync(data, {
5401
- path: ctx.path,
5402
- errorMap: ctx.common.contextualErrorMap
5403
- });
5404
- }));
5405
- }
5406
- };
5407
- __name(_ZodPromise, "ZodPromise");
5408
- var ZodPromise = _ZodPromise;
5409
- ZodPromise.create = (schema, params) => {
5410
- return new ZodPromise({
5411
- type: schema,
5412
- typeName: ZodFirstPartyTypeKind.ZodPromise,
5413
- ...processCreateParams(params)
5414
- });
5415
- };
5416
- var _ZodEffects = class _ZodEffects extends ZodType {
5417
- innerType() {
5418
- return this._def.schema;
5419
- }
5420
- sourceType() {
5421
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
5422
- }
5423
- _parse(input) {
5424
- const { status, ctx } = this._processInputParams(input);
5425
- const effect = this._def.effect || null;
5426
- const checkCtx = {
5427
- addIssue: (arg) => {
5428
- addIssueToContext(ctx, arg);
5429
- if (arg.fatal) {
5430
- status.abort();
5431
- } else {
5432
- status.dirty();
5433
- }
5434
- },
5435
- get path() {
5436
- return ctx.path;
5437
- }
5438
- };
5439
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
5440
- if (effect.type === "preprocess") {
5441
- const processed = effect.transform(ctx.data, checkCtx);
5442
- if (ctx.common.issues.length) {
5443
- return {
5444
- status: "dirty",
5445
- value: ctx.data
5446
- };
5447
- }
5448
- if (ctx.common.async) {
5449
- return Promise.resolve(processed).then((processed2) => {
5450
- return this._def.schema._parseAsync({
5451
- data: processed2,
5452
- path: ctx.path,
5453
- parent: ctx
5454
- });
5455
- });
5456
- } else {
5457
- return this._def.schema._parseSync({
5458
- data: processed,
5459
- path: ctx.path,
5460
- parent: ctx
5461
- });
5462
- }
5463
- }
5464
- if (effect.type === "refinement") {
5465
- const executeRefinement = /* @__PURE__ */ __name((acc) => {
5466
- const result = effect.refinement(acc, checkCtx);
5467
- if (ctx.common.async) {
5468
- return Promise.resolve(result);
5469
- }
5470
- if (result instanceof Promise) {
5471
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
5472
- }
5473
- return acc;
5474
- }, "executeRefinement");
5475
- if (ctx.common.async === false) {
5476
- const inner = this._def.schema._parseSync({
5477
- data: ctx.data,
5478
- path: ctx.path,
5479
- parent: ctx
5480
- });
5481
- if (inner.status === "aborted")
5482
- return INVALID;
5483
- if (inner.status === "dirty")
5484
- status.dirty();
5485
- executeRefinement(inner.value);
5486
- return { status: status.value, value: inner.value };
5487
- } else {
5488
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
5489
- if (inner.status === "aborted")
5490
- return INVALID;
5491
- if (inner.status === "dirty")
5492
- status.dirty();
5493
- return executeRefinement(inner.value).then(() => {
5494
- return { status: status.value, value: inner.value };
5495
- });
5496
- });
5497
- }
5498
- }
5499
- if (effect.type === "transform") {
5500
- if (ctx.common.async === false) {
5501
- const base = this._def.schema._parseSync({
5502
- data: ctx.data,
5503
- path: ctx.path,
5504
- parent: ctx
5505
- });
5506
- if (!isValid(base))
5507
- return base;
5508
- const result = effect.transform(base.value, checkCtx);
5509
- if (result instanceof Promise) {
5510
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
5511
- }
5512
- return { status: status.value, value: result };
5513
- } else {
5514
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
5515
- if (!isValid(base))
5516
- return base;
5517
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
5518
- });
5519
- }
5520
- }
5521
- util.assertNever(effect);
5522
- }
5523
- };
5524
- __name(_ZodEffects, "ZodEffects");
5525
- var ZodEffects = _ZodEffects;
5526
- ZodEffects.create = (schema, effect, params) => {
5527
- return new ZodEffects({
5528
- schema,
5529
- typeName: ZodFirstPartyTypeKind.ZodEffects,
5530
- effect,
5531
- ...processCreateParams(params)
5532
- });
5533
- };
5534
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
5535
- return new ZodEffects({
5536
- schema,
5537
- effect: { type: "preprocess", transform: preprocess },
5538
- typeName: ZodFirstPartyTypeKind.ZodEffects,
5539
- ...processCreateParams(params)
5540
- });
5541
- };
5542
- var _ZodOptional = class _ZodOptional extends ZodType {
5543
- _parse(input) {
5544
- const parsedType = this._getType(input);
5545
- if (parsedType === ZodParsedType.undefined) {
5546
- return OK(void 0);
5547
- }
5548
- return this._def.innerType._parse(input);
5549
- }
5550
- unwrap() {
5551
- return this._def.innerType;
5552
- }
5553
- };
5554
- __name(_ZodOptional, "ZodOptional");
5555
- var ZodOptional = _ZodOptional;
5556
- ZodOptional.create = (type, params) => {
5557
- return new ZodOptional({
5558
- innerType: type,
5559
- typeName: ZodFirstPartyTypeKind.ZodOptional,
5560
- ...processCreateParams(params)
5561
- });
5562
- };
5563
- var _ZodNullable = class _ZodNullable extends ZodType {
5564
- _parse(input) {
5565
- const parsedType = this._getType(input);
5566
- if (parsedType === ZodParsedType.null) {
5567
- return OK(null);
5568
- }
5569
- return this._def.innerType._parse(input);
5570
- }
5571
- unwrap() {
5572
- return this._def.innerType;
5573
- }
5574
- };
5575
- __name(_ZodNullable, "ZodNullable");
5576
- var ZodNullable = _ZodNullable;
5577
- ZodNullable.create = (type, params) => {
5578
- return new ZodNullable({
5579
- innerType: type,
5580
- typeName: ZodFirstPartyTypeKind.ZodNullable,
5581
- ...processCreateParams(params)
5582
- });
5583
- };
5584
- var _ZodDefault = class _ZodDefault extends ZodType {
5585
- _parse(input) {
5586
- const { ctx } = this._processInputParams(input);
5587
- let data = ctx.data;
5588
- if (ctx.parsedType === ZodParsedType.undefined) {
5589
- data = this._def.defaultValue();
5590
- }
5591
- return this._def.innerType._parse({
5592
- data,
5593
- path: ctx.path,
5594
- parent: ctx
5595
- });
5596
- }
5597
- removeDefault() {
5598
- return this._def.innerType;
5599
- }
5600
- };
5601
- __name(_ZodDefault, "ZodDefault");
5602
- var ZodDefault = _ZodDefault;
5603
- ZodDefault.create = (type, params) => {
5604
- return new ZodDefault({
5605
- innerType: type,
5606
- typeName: ZodFirstPartyTypeKind.ZodDefault,
5607
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
5608
- ...processCreateParams(params)
5609
- });
5610
- };
5611
- var _ZodCatch = class _ZodCatch extends ZodType {
5612
- _parse(input) {
5613
- const { ctx } = this._processInputParams(input);
5614
- const newCtx = {
5615
- ...ctx,
5616
- common: {
5617
- ...ctx.common,
5618
- issues: []
5619
- }
5620
- };
5621
- const result = this._def.innerType._parse({
5622
- data: newCtx.data,
5623
- path: newCtx.path,
5624
- parent: {
5625
- ...newCtx
5626
- }
5627
- });
5628
- if (isAsync(result)) {
5629
- return result.then((result2) => {
5630
- return {
5631
- status: "valid",
5632
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
5633
- get error() {
5634
- return new ZodError(newCtx.common.issues);
5635
- },
5636
- input: newCtx.data
5637
- })
5638
- };
5639
- });
5640
- } else {
5641
- return {
5642
- status: "valid",
5643
- value: result.status === "valid" ? result.value : this._def.catchValue({
5644
- get error() {
5645
- return new ZodError(newCtx.common.issues);
5646
- },
5647
- input: newCtx.data
5648
- })
5649
- };
5650
- }
5651
- }
5652
- removeCatch() {
5653
- return this._def.innerType;
5654
- }
5655
- };
5656
- __name(_ZodCatch, "ZodCatch");
5657
- var ZodCatch = _ZodCatch;
5658
- ZodCatch.create = (type, params) => {
5659
- return new ZodCatch({
5660
- innerType: type,
5661
- typeName: ZodFirstPartyTypeKind.ZodCatch,
5662
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
5663
- ...processCreateParams(params)
5664
- });
5665
- };
5666
- var _ZodNaN = class _ZodNaN extends ZodType {
5667
- _parse(input) {
5668
- const parsedType = this._getType(input);
5669
- if (parsedType !== ZodParsedType.nan) {
5670
- const ctx = this._getOrReturnCtx(input);
5671
- addIssueToContext(ctx, {
5672
- code: ZodIssueCode.invalid_type,
5673
- expected: ZodParsedType.nan,
5674
- received: ctx.parsedType
5675
- });
5676
- return INVALID;
5677
- }
5678
- return { status: "valid", value: input.data };
5679
- }
5680
- };
5681
- __name(_ZodNaN, "ZodNaN");
5682
- var ZodNaN = _ZodNaN;
5683
- ZodNaN.create = (params) => {
5684
- return new ZodNaN({
5685
- typeName: ZodFirstPartyTypeKind.ZodNaN,
5686
- ...processCreateParams(params)
5687
- });
5688
- };
5689
- var BRAND = Symbol("zod_brand");
5690
- var _ZodBranded = class _ZodBranded extends ZodType {
5691
- _parse(input) {
5692
- const { ctx } = this._processInputParams(input);
5693
- const data = ctx.data;
5694
- return this._def.type._parse({
5695
- data,
5696
- path: ctx.path,
5697
- parent: ctx
5698
- });
5699
- }
5700
- unwrap() {
5701
- return this._def.type;
5702
- }
5703
- };
5704
- __name(_ZodBranded, "ZodBranded");
5705
- var ZodBranded = _ZodBranded;
5706
- var _ZodPipeline = class _ZodPipeline extends ZodType {
5707
- _parse(input) {
5708
- const { status, ctx } = this._processInputParams(input);
5709
- if (ctx.common.async) {
5710
- const handleAsync = /* @__PURE__ */ __name(async () => {
5711
- const inResult = await this._def.in._parseAsync({
5712
- data: ctx.data,
5713
- path: ctx.path,
5714
- parent: ctx
5715
- });
5716
- if (inResult.status === "aborted")
5717
- return INVALID;
5718
- if (inResult.status === "dirty") {
5719
- status.dirty();
5720
- return DIRTY(inResult.value);
5721
- } else {
5722
- return this._def.out._parseAsync({
5723
- data: inResult.value,
5724
- path: ctx.path,
5725
- parent: ctx
5726
- });
5727
- }
5728
- }, "handleAsync");
5729
- return handleAsync();
5730
- } else {
5731
- const inResult = this._def.in._parseSync({
5732
- data: ctx.data,
5733
- path: ctx.path,
5734
- parent: ctx
5735
- });
5736
- if (inResult.status === "aborted")
5737
- return INVALID;
5738
- if (inResult.status === "dirty") {
5739
- status.dirty();
5740
- return {
5741
- status: "dirty",
5742
- value: inResult.value
5743
- };
5744
- } else {
5745
- return this._def.out._parseSync({
5746
- data: inResult.value,
5747
- path: ctx.path,
5748
- parent: ctx
5749
- });
5750
- }
5751
- }
5752
- }
5753
- static create(a, b) {
5754
- return new _ZodPipeline({
5755
- in: a,
5756
- out: b,
5757
- typeName: ZodFirstPartyTypeKind.ZodPipeline
5758
- });
5759
- }
5760
- };
5761
- __name(_ZodPipeline, "ZodPipeline");
5762
- var ZodPipeline = _ZodPipeline;
5763
- var _ZodReadonly = class _ZodReadonly extends ZodType {
5764
- _parse(input) {
5765
- const result = this._def.innerType._parse(input);
5766
- if (isValid(result)) {
5767
- result.value = Object.freeze(result.value);
5768
- }
5769
- return result;
5770
- }
5771
- };
5772
- __name(_ZodReadonly, "ZodReadonly");
5773
- var ZodReadonly = _ZodReadonly;
5774
- ZodReadonly.create = (type, params) => {
5775
- return new ZodReadonly({
5776
- innerType: type,
5777
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
5778
- ...processCreateParams(params)
5779
- });
5780
- };
5781
- var custom = /* @__PURE__ */ __name((check, params = {}, fatal) => {
5782
- if (check)
5783
- return ZodAny.create().superRefine((data, ctx) => {
5784
- var _a, _b;
5785
- if (!check(data)) {
5786
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
5787
- const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
5788
- const p2 = typeof p === "string" ? { message: p } : p;
5789
- ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
5790
- }
5791
- });
5792
- return ZodAny.create();
5793
- }, "custom");
5794
- var late = {
5795
- object: ZodObject.lazycreate
5796
- };
5797
- var ZodFirstPartyTypeKind;
5798
- (function(ZodFirstPartyTypeKind2) {
5799
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
5800
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
5801
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
5802
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
5803
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
5804
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
5805
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
5806
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
5807
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
5808
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
5809
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
5810
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
5811
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
5812
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
5813
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
5814
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
5815
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
5816
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
5817
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
5818
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
5819
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
5820
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
5821
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
5822
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
5823
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
5824
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
5825
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
5826
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
5827
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
5828
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
5829
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
5830
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
5831
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
5832
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
5833
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
5834
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
5835
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
5836
- var instanceOfType = /* @__PURE__ */ __name((cls, params = {
5837
- message: `Input not instance of ${cls.name}`
5838
- }) => custom((data) => data instanceof cls, params), "instanceOfType");
5839
- var stringType = ZodString.create;
5840
- var numberType = ZodNumber.create;
5841
- var nanType = ZodNaN.create;
5842
- var bigIntType = ZodBigInt.create;
5843
- var booleanType = ZodBoolean.create;
5844
- var dateType = ZodDate.create;
5845
- var symbolType = ZodSymbol.create;
5846
- var undefinedType = ZodUndefined.create;
5847
- var nullType = ZodNull.create;
5848
- var anyType = ZodAny.create;
5849
- var unknownType = ZodUnknown.create;
5850
- var neverType = ZodNever.create;
5851
- var voidType = ZodVoid.create;
5852
- var arrayType = ZodArray.create;
5853
- var objectType = ZodObject.create;
5854
- var strictObjectType = ZodObject.strictCreate;
5855
- var unionType = ZodUnion.create;
5856
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
5857
- var intersectionType = ZodIntersection.create;
5858
- var tupleType = ZodTuple.create;
5859
- var recordType = ZodRecord.create;
5860
- var mapType = ZodMap.create;
5861
- var setType = ZodSet.create;
5862
- var functionType = ZodFunction.create;
5863
- var lazyType = ZodLazy.create;
5864
- var literalType = ZodLiteral.create;
5865
- var enumType = ZodEnum.create;
5866
- var nativeEnumType = ZodNativeEnum.create;
5867
- var promiseType = ZodPromise.create;
5868
- var effectsType = ZodEffects.create;
5869
- var optionalType = ZodOptional.create;
5870
- var nullableType = ZodNullable.create;
5871
- var preprocessType = ZodEffects.createWithPreprocess;
5872
- var pipelineType = ZodPipeline.create;
5873
- var ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
5874
- var onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
5875
- var oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
5876
- var coerce = {
5877
- string: (arg) => ZodString.create({ ...arg, coerce: true }),
5878
- number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
5879
- boolean: (arg) => ZodBoolean.create({
5880
- ...arg,
5881
- coerce: true
5882
- }),
5883
- bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
5884
- date: (arg) => ZodDate.create({ ...arg, coerce: true })
5885
- };
5886
- var NEVER = INVALID;
5887
- var z = /* @__PURE__ */ Object.freeze({
5888
- __proto__: null,
5889
- defaultErrorMap: errorMap,
5890
- setErrorMap,
5891
- getErrorMap,
5892
- makeIssue,
5893
- EMPTY_PATH,
5894
- addIssueToContext,
5895
- ParseStatus,
5896
- INVALID,
5897
- DIRTY,
5898
- OK,
5899
- isAborted,
5900
- isDirty,
5901
- isValid,
5902
- isAsync,
5903
- get util() {
5904
- return util;
5905
- },
5906
- get objectUtil() {
5907
- return objectUtil;
5908
- },
5909
- ZodParsedType,
5910
- getParsedType,
5911
- ZodType,
5912
- ZodString,
5913
- ZodNumber,
5914
- ZodBigInt,
5915
- ZodBoolean,
5916
- ZodDate,
5917
- ZodSymbol,
5918
- ZodUndefined,
5919
- ZodNull,
5920
- ZodAny,
5921
- ZodUnknown,
5922
- ZodNever,
5923
- ZodVoid,
5924
- ZodArray,
5925
- ZodObject,
5926
- ZodUnion,
5927
- ZodDiscriminatedUnion,
5928
- ZodIntersection,
5929
- ZodTuple,
5930
- ZodRecord,
5931
- ZodMap,
5932
- ZodSet,
5933
- ZodFunction,
5934
- ZodLazy,
5935
- ZodLiteral,
5936
- ZodEnum,
5937
- ZodNativeEnum,
5938
- ZodPromise,
5939
- ZodEffects,
5940
- ZodTransformer: ZodEffects,
5941
- ZodOptional,
5942
- ZodNullable,
5943
- ZodDefault,
5944
- ZodCatch,
5945
- ZodNaN,
5946
- BRAND,
5947
- ZodBranded,
5948
- ZodPipeline,
5949
- ZodReadonly,
5950
- custom,
5951
- Schema: ZodType,
5952
- ZodSchema: ZodType,
5953
- late,
5954
- get ZodFirstPartyTypeKind() {
5955
- return ZodFirstPartyTypeKind;
5956
- },
5957
- coerce,
5958
- any: anyType,
5959
- array: arrayType,
5960
- bigint: bigIntType,
5961
- boolean: booleanType,
5962
- date: dateType,
5963
- discriminatedUnion: discriminatedUnionType,
5964
- effect: effectsType,
5965
- "enum": enumType,
5966
- "function": functionType,
5967
- "instanceof": instanceOfType,
5968
- intersection: intersectionType,
5969
- lazy: lazyType,
5970
- literal: literalType,
5971
- map: mapType,
5972
- nan: nanType,
5973
- nativeEnum: nativeEnumType,
5974
- never: neverType,
5975
- "null": nullType,
5976
- nullable: nullableType,
5977
- number: numberType,
5978
- object: objectType,
5979
- oboolean,
5980
- onumber,
5981
- optional: optionalType,
5982
- ostring,
5983
- pipeline: pipelineType,
5984
- preprocess: preprocessType,
5985
- promise: promiseType,
5986
- record: recordType,
5987
- set: setType,
5988
- strictObject: strictObjectType,
5989
- string: stringType,
5990
- symbol: symbolType,
5991
- transformer: effectsType,
5992
- tuple: tupleType,
5993
- "undefined": undefinedType,
5994
- union: unionType,
5995
- unknown: unknownType,
5996
- "void": voidType,
5997
- NEVER,
5998
- ZodIssueCode,
5999
- quotelessJson,
6000
- ZodError
6001
- });
6002
-
6003
- // ../shared/src/validation/segwitAddr.ts
6004
- var CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
6005
- var GENERATOR = [
6006
- 996825010,
6007
- 642813549,
6008
- 513874426,
6009
- 1027748829,
6010
- 705979059
6011
- ];
6012
- var Encoding;
6013
- (function(Encoding2) {
6014
- Encoding2["Bech32"] = "bech32";
6015
- Encoding2["Bech32m"] = "bech32m";
6016
- })(Encoding || (Encoding = {}));
6017
- var bech32 = {
6018
- getEncodingConst(enc) {
6019
- if (enc === "bech32")
6020
- return 1;
6021
- if (enc === "bech32m")
6022
- return 734539939;
6023
- return null;
6024
- },
6025
- polymod(values) {
6026
- let chk = 1;
6027
- for (let p = 0; p < values.length; p += 1) {
6028
- const top = chk >> 25;
6029
- chk = (chk & 33554431) << 5 ^ values[p];
6030
- for (let i = 0; i < 5; i += 1) {
6031
- if (top >> i & 1) {
6032
- chk ^= GENERATOR[i];
6033
- }
6034
- }
6035
- }
6036
- return chk;
6037
- },
6038
- hrpExpand(hrp) {
6039
- const ret = [];
6040
- let p;
6041
- for (p = 0; p < hrp.length; p += 1) {
6042
- ret.push(hrp.charCodeAt(p) >> 5);
6043
- }
6044
- ret.push(0);
6045
- for (p = 0; p < hrp.length; p += 1) {
6046
- ret.push(hrp.charCodeAt(p) & 31);
6047
- }
6048
- return ret;
6049
- },
6050
- verifyChecksum(hrp, data, enc) {
6051
- return this.polymod(this.hrpExpand(hrp).concat(data)) === this.getEncodingConst(enc);
6052
- },
6053
- createChecksum(hrp, data, enc) {
6054
- const values = this.hrpExpand(hrp).concat(data).concat([
6055
- 0,
6056
- 0,
6057
- 0,
6058
- 0,
6059
- 0,
6060
- 0
6061
- ]);
6062
- const mod = this.polymod(values) ^ this.getEncodingConst(enc);
6063
- const ret = [];
6064
- for (let p = 0; p < 6; p += 1) {
6065
- ret.push(mod >> 5 * (5 - p) & 31);
6066
- }
6067
- return ret;
6068
- },
6069
- encode(hrp, data, enc) {
6070
- const combined = data.concat(this.createChecksum(hrp, data, enc));
6071
- let ret = `${hrp}1`;
6072
- for (let p = 0; p < combined.length; p += 1) {
6073
- ret += CHARSET.charAt(combined[p]);
6074
- }
6075
- return ret;
6076
- },
6077
- decode(bechString, enc) {
6078
- let p;
6079
- let hasLower = false;
6080
- let hasUpper = false;
6081
- for (p = 0; p < bechString.length; p += 1) {
6082
- if (bechString.charCodeAt(p) < 33 || bechString.charCodeAt(p) > 126) {
6083
- return null;
6084
- }
6085
- if (bechString.charCodeAt(p) >= 97 && bechString.charCodeAt(p) <= 122) {
6086
- hasLower = true;
6087
- }
6088
- if (bechString.charCodeAt(p) >= 65 && bechString.charCodeAt(p) <= 90) {
6089
- hasUpper = true;
6090
- }
6091
- }
6092
- if (hasLower && hasUpper)
6093
- return null;
6094
- const lowercase = bechString.toLowerCase();
6095
- const pos = lowercase.lastIndexOf("1");
6096
- if (pos < 1 || pos + 7 > lowercase.length || lowercase.length > 90) {
6097
- return null;
6098
- }
6099
- const hrp = lowercase.substring(0, pos);
6100
- const data = [];
6101
- for (p = pos + 1; p < lowercase.length; p += 1) {
6102
- const d = CHARSET.indexOf(lowercase.charAt(p));
6103
- if (d === -1)
6104
- return null;
6105
- data.push(d);
6106
- }
6107
- if (!this.verifyChecksum(hrp, data, enc)) {
6108
- return null;
6109
- }
6110
- return {
6111
- hrp,
6112
- data: data.slice(0, data.length - 6)
6113
- };
6114
- }
6115
- };
6116
- var segwitAddress = {
6117
- convertbits(data, frombits, tobits, pad) {
6118
- let acc = 0;
6119
- let bits = 0;
6120
- const ret = [];
6121
- const maxv = (1 << tobits) - 1;
6122
- for (let p = 0; p < data.length; p += 1) {
6123
- const value = data[p];
6124
- if (value < 0 || value >> frombits !== 0) {
6125
- return null;
6126
- }
6127
- acc = acc << frombits | value;
6128
- bits += frombits;
6129
- while (bits >= tobits) {
6130
- bits -= tobits;
6131
- ret.push(acc >> bits & maxv);
6132
- }
6133
- }
6134
- if (pad) {
6135
- if (bits > 0) {
6136
- ret.push(acc << tobits - bits & maxv);
6137
- }
6138
- } else if (bits >= frombits || acc << tobits - bits & maxv) {
6139
- return null;
6140
- }
6141
- return ret;
6142
- },
6143
- decode(hrp, addr) {
6144
- let bech32m = false;
6145
- let dec = bech32.decode(addr, "bech32");
6146
- if (dec === null) {
6147
- dec = bech32.decode(addr, "bech32m");
6148
- bech32m = true;
6149
- }
6150
- if (dec === null || dec.hrp !== hrp || dec.data.length < 1 || dec.data[0] > 16) {
6151
- return null;
6152
- }
6153
- const res = this.convertbits(dec.data.slice(1), 5, 8, false);
6154
- if (res === null || res.length < 2 || res.length > 40) {
6155
- return null;
6156
- }
6157
- if (dec.data[0] === 0 && res.length !== 20 && res.length !== 32) {
6158
- return null;
6159
- }
6160
- if (dec.data[0] === 0 && bech32m) {
6161
- return null;
6162
- }
6163
- if (dec.data[0] !== 0 && !bech32m) {
6164
- return null;
6165
- }
6166
- return {
6167
- version: dec.data[0],
6168
- program: res
6169
- };
6170
- },
6171
- encode(hrp, version, program) {
6172
- let enc = "bech32";
6173
- if (version > 0) {
6174
- enc = "bech32m";
6175
- }
6176
- const ret = bech32.encode(
6177
- hrp,
6178
- // @ts-expect-error can be null
6179
- [
6180
- version
6181
- ].concat(this.convertbits(program, 8, 5, true)),
6182
- enc
6183
- );
6184
- if (this.decode(hrp, ret) === null) {
6185
- return null;
6186
- }
6187
- return ret;
6188
- }
6189
- };
6190
- var isValidSegwitAddress = /* @__PURE__ */ __name((address) => {
6191
- const hrp = /^(bc|tb|bcrt)1/.exec(address)?.[1];
6192
- if (!hrp)
6193
- return false;
6194
- return segwitAddress.decode(hrp, address) !== null;
6195
- }, "isValidSegwitAddress");
6196
-
6197
- // ../shared/src/validation/addressValidation.ts
6198
- var assertArraylikeEqual = /* @__PURE__ */ __name((a, b) => {
6199
- assert(a.length === b.length, "arraylike lengths must be equal");
6200
- for (let i = 0; i < a.length; i += 1) {
6201
- assert(a[i] === b[i], "arraylike elements must be equal");
6202
- }
6203
- }, "assertArraylikeEqual");
6204
- var validateP2PKHOrP2SHAddress = /* @__PURE__ */ __name((address, network) => {
6205
- try {
6206
- const decoded = base58Decode(address);
6207
- assert(decoded.length === 25, "decoded address must be 25 bytes long");
6208
- if (network === "mainnet") {
6209
- assert(decoded[0] === 0 || decoded[0] === 5, "decoded address must start with 0x00 or 0x05");
6210
- } else {
6211
- assert(decoded[0] === 111 || decoded[0] === 196, "decoded address must start with 0x6f or 0xc4");
6212
- }
6213
- const checksum = decoded.slice(-4);
6214
- const doubleHash = ethers.getBytes(ethers.sha256(ethers.sha256(decoded.slice(0, 21))));
6215
- assertArraylikeEqual(checksum, doubleHash.slice(0, 4));
6216
- return true;
6217
- } catch (error) {
6218
- return false;
6219
- }
6220
- }, "validateP2PKHOrP2SHAddress");
6221
- var validateSegwitAddress = /* @__PURE__ */ __name((address, network) => {
6222
- try {
6223
- assert(
6224
- // On mainnet, the address must start with "bc1"
6225
- network === "mainnet" && address.startsWith("bc1") || // on testnet it must start with "tb1"
6226
- network === "testnet" && address.startsWith("tb1") || // on regtest it must start with "bcrt1"
6227
- network === "regtest" && address.startsWith("bcrt1"),
6228
- "address must start with bc1, tb1 or bcrt1"
6229
- );
6230
- return isValidSegwitAddress(address);
6231
- } catch {
6232
- return false;
6233
- }
6234
- }, "validateSegwitAddress");
6235
- var validateBitcoinAddress = /* @__PURE__ */ __name((address, network) => validateP2PKHOrP2SHAddress(address, network) || validateSegwitAddress(address, network), "validateBitcoinAddress");
6236
- var validateBitcoinMainnetAddress = /* @__PURE__ */ __name((address) => validateBitcoinAddress(address, "mainnet"), "validateBitcoinMainnetAddress");
6237
- var validateBitcoinTestnetAddress = /* @__PURE__ */ __name((address) => validateBitcoinAddress(address, "testnet"), "validateBitcoinTestnetAddress");
6238
- var validateBitcoinRegtestAddress = /* @__PURE__ */ __name((address) => validateBitcoinAddress(address, "regtest"), "validateBitcoinRegtestAddress");
6239
-
6240
- // ../shared/src/parsers.ts
6241
- var errorMap2 = /* @__PURE__ */ __name((_issue, context) => ({
6242
- message: `received: ${JSON.stringify(context.data)}`
6243
- }), "errorMap");
6244
- var string = z.string({
6245
- errorMap: errorMap2
6246
- });
6247
- z.number({
6248
- errorMap: errorMap2
6249
- });
6250
- var numericString = string.regex(/^[0-9]+$/);
6251
- var hexString = z.custom((val) => typeof val === "string" && /^0x[0-9a-f]+$/i.test(val));
6252
- numericString.transform((arg) => `0x${BigInt(arg).toString(16)}`);
6253
- string.regex(/^[0-9a-f]+$/);
6254
- var btcAddress = /* @__PURE__ */ __name((env) => {
6255
- const network = env ?? process.env.CHAINFLIP_NETWORK;
6256
- if (network === "mainnet")
6257
- return string.regex(/^(1|3|bc1)/).refine(validateBitcoinMainnetAddress);
6258
- return z.union([
6259
- string.regex(/^(m|n|2|tb1)/).refine(validateBitcoinTestnetAddress),
6260
- string.regex(/^bcrt1/).refine(validateBitcoinRegtestAddress)
6261
- ]);
6262
- }, "btcAddress");
6263
- var dotAddress = z.union([
6264
- string,
6265
- hexString
6266
- ]).transform((arg) => {
6267
- try {
6268
- if (arg.startsWith("0x")) {
6269
- return encodeAddress(hexToU8a(arg));
6270
- }
6271
- decodeAddress(arg);
6272
- return arg;
6273
- } catch {
6274
- return null;
6275
- }
6276
- }).refine(isString);
6277
- var ethereumAddress = hexString.refine((address) => ethers.isAddress(address));
6278
- numericString.transform((arg) => BigInt(arg));
6279
- var u128 = z.union([
6280
- numericString,
6281
- hexString
6282
- ]).transform((arg) => BigInt(arg));
6283
- var unsignedInteger = z.union([
6284
- u128,
6285
- z.number().transform((n) => BigInt(n))
6286
- ]);
6287
- z.object({
6288
- __kind: z.enum([
6289
- "Usdc",
6290
- "Flip",
6291
- "Dot",
6292
- "Eth",
6293
- "Btc"
6294
- ])
6295
- }).transform(({ __kind }) => __kind.toUpperCase());
6296
- var chainflipChain = z.nativeEnum(Chains);
6297
- var chainflipAsset = z.nativeEnum(Assets);
6298
- z.nativeEnum(ChainflipNetworks);
6299
- z.union([
6300
- z.object({
6301
- __kind: z.literal("CcmPrincipal"),
6302
- value: unsignedInteger
6303
- }).transform(({ value: ccmId }) => ({
6304
- type: "PRINCIPAL",
6305
- ccmId
6306
- })),
6307
- z.object({
6308
- __kind: z.literal("CcmGas"),
6309
- value: unsignedInteger
6310
- }).transform(({ value: ccmId }) => ({
6311
- type: "GAS",
6312
- ccmId
6313
- })),
6314
- z.object({
6315
- __kind: z.literal("Swap")
6316
- }).transform(() => ({
6317
- type: "SWAP"
6318
- }))
6319
- ]);
6320
-
6321
- // ../shared/src/schemas.ts
6322
- z.object({
6323
- srcAsset: chainflipAsset,
6324
- destAsset: chainflipAsset,
6325
- amount: numericString
6326
- });
6327
- var ccmMetadataSchema = z.object({
6328
- gasBudget: numericString,
6329
- message: hexString
6330
- });
6331
- z.object({
6332
- srcAsset: chainflipAsset,
6333
- destAsset: chainflipAsset,
6334
- srcChain: chainflipChain,
6335
- destChain: chainflipChain,
6336
- destAddress: z.string(),
6337
- amount: numericString,
6338
- ccmMetadata: ccmMetadataSchema.optional(),
6339
- broker: z.object({
6340
- url: z.string(),
6341
- commissionBps: z.number()
6342
- }).optional()
6343
- }).transform(({ amount, ...rest }) => ({
6344
- ...rest,
6345
- expectedDepositAmount: amount
6346
- }));
6347
-
6348
- // ../shared/src/vault/schemas.ts
6349
2173
  var bytesToHex = /* @__PURE__ */ __name((arr) => `0x${[
6350
2174
  ...arr
6351
2175
  ].map((v) => v.toString(16).padStart(2, "0")).join("")}`, "bytesToHex");
@@ -6661,7 +2485,7 @@ var _SwapSDK = class _SwapSDK {
6661
2485
  transformer: esm_default,
6662
2486
  links: [
6663
2487
  httpBatchLink({
6664
- url: `${this.baseUrl}/trpc`
2488
+ url: new URL("/trpc", this.baseUrl)
6665
2489
  })
6666
2490
  ]
6667
2491
  });
@@ -6679,10 +2503,18 @@ var _SwapSDK = class _SwapSDK {
6679
2503
  return ApiService_default.getQuote(this.baseUrl, quoteRequest, options);
6680
2504
  }
6681
2505
  async requestDepositAddress(depositAddressRequest) {
6682
- const response = await this.trpc.openSwapDepositChannel.mutate({
6683
- ...depositAddressRequest,
6684
- broker: this.brokerConfig
6685
- });
2506
+ let response;
2507
+ if (this.brokerConfig !== void 0) {
2508
+ const { requestSwapDepositAddress } = await import('./broker-FONIQXKG.mjs');
2509
+ const result = await requestSwapDepositAddress(depositAddressRequest, this.brokerConfig);
2510
+ response = {
2511
+ id: `${result.issuedBlock}-${depositAddressRequest.srcChain}-${result.channelId}`,
2512
+ depositAddress: result.address,
2513
+ sourceChainExpiryBlock: result.sourceChainExpiryBlock
2514
+ };
2515
+ } else {
2516
+ response = await this.trpc.openSwapDepositChannel.mutate(depositAddressRequest);
2517
+ }
6686
2518
  return {
6687
2519
  ...depositAddressRequest,
6688
2520
  depositChannelId: response.id,