@tahanabavi/typefetch 1.4.1 → 1.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
2
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
4
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
7
  var __export = (target, all) => {
6
8
  for (var name in all)
@@ -14,6 +16,14 @@ var __copyProps = (to, from, except, desc) => {
14
16
  }
15
17
  return to;
16
18
  };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
17
27
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
28
 
19
29
  // src/index.ts
@@ -23,4070 +33,34 @@ __export(index_exports, {
23
33
  RichError: () => RichError,
24
34
  authMiddleware: () => authMiddleware,
25
35
  cacheMiddleware: () => cacheMiddleware,
36
+ encryptionMiddleware: () => encryptionMiddleware,
26
37
  loggingMiddleware: () => loggingMiddleware,
27
38
  makeRequestSchema: () => makeRequestSchema,
39
+ processDeep: () => processDeep,
28
40
  retryMiddleware: () => retryMiddleware
29
41
  });
30
42
  module.exports = __toCommonJS(index_exports);
31
43
 
32
- // node_modules/zod/v3/external.js
33
- var external_exports = {};
34
- __export(external_exports, {
35
- BRAND: () => BRAND,
36
- DIRTY: () => DIRTY,
37
- EMPTY_PATH: () => EMPTY_PATH,
38
- INVALID: () => INVALID,
39
- NEVER: () => NEVER,
40
- OK: () => OK,
41
- ParseStatus: () => ParseStatus,
42
- Schema: () => ZodType,
43
- ZodAny: () => ZodAny,
44
- ZodArray: () => ZodArray,
45
- ZodBigInt: () => ZodBigInt,
46
- ZodBoolean: () => ZodBoolean,
47
- ZodBranded: () => ZodBranded,
48
- ZodCatch: () => ZodCatch,
49
- ZodDate: () => ZodDate,
50
- ZodDefault: () => ZodDefault,
51
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
52
- ZodEffects: () => ZodEffects,
53
- ZodEnum: () => ZodEnum,
54
- ZodError: () => ZodError,
55
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
56
- ZodFunction: () => ZodFunction,
57
- ZodIntersection: () => ZodIntersection,
58
- ZodIssueCode: () => ZodIssueCode,
59
- ZodLazy: () => ZodLazy,
60
- ZodLiteral: () => ZodLiteral,
61
- ZodMap: () => ZodMap,
62
- ZodNaN: () => ZodNaN,
63
- ZodNativeEnum: () => ZodNativeEnum,
64
- ZodNever: () => ZodNever,
65
- ZodNull: () => ZodNull,
66
- ZodNullable: () => ZodNullable,
67
- ZodNumber: () => ZodNumber,
68
- ZodObject: () => ZodObject,
69
- ZodOptional: () => ZodOptional,
70
- ZodParsedType: () => ZodParsedType,
71
- ZodPipeline: () => ZodPipeline,
72
- ZodPromise: () => ZodPromise,
73
- ZodReadonly: () => ZodReadonly,
74
- ZodRecord: () => ZodRecord,
75
- ZodSchema: () => ZodType,
76
- ZodSet: () => ZodSet,
77
- ZodString: () => ZodString,
78
- ZodSymbol: () => ZodSymbol,
79
- ZodTransformer: () => ZodEffects,
80
- ZodTuple: () => ZodTuple,
81
- ZodType: () => ZodType,
82
- ZodUndefined: () => ZodUndefined,
83
- ZodUnion: () => ZodUnion,
84
- ZodUnknown: () => ZodUnknown,
85
- ZodVoid: () => ZodVoid,
86
- addIssueToContext: () => addIssueToContext,
87
- any: () => anyType,
88
- array: () => arrayType,
89
- bigint: () => bigIntType,
90
- boolean: () => booleanType,
91
- coerce: () => coerce,
92
- custom: () => custom,
93
- date: () => dateType,
94
- datetimeRegex: () => datetimeRegex,
95
- defaultErrorMap: () => en_default,
96
- discriminatedUnion: () => discriminatedUnionType,
97
- effect: () => effectsType,
98
- enum: () => enumType,
99
- function: () => functionType,
100
- getErrorMap: () => getErrorMap,
101
- getParsedType: () => getParsedType,
102
- instanceof: () => instanceOfType,
103
- intersection: () => intersectionType,
104
- isAborted: () => isAborted,
105
- isAsync: () => isAsync,
106
- isDirty: () => isDirty,
107
- isValid: () => isValid,
108
- late: () => late,
109
- lazy: () => lazyType,
110
- literal: () => literalType,
111
- makeIssue: () => makeIssue,
112
- map: () => mapType,
113
- nan: () => nanType,
114
- nativeEnum: () => nativeEnumType,
115
- never: () => neverType,
116
- null: () => nullType,
117
- nullable: () => nullableType,
118
- number: () => numberType,
119
- object: () => objectType,
120
- objectUtil: () => objectUtil,
121
- oboolean: () => oboolean,
122
- onumber: () => onumber,
123
- optional: () => optionalType,
124
- ostring: () => ostring,
125
- pipeline: () => pipelineType,
126
- preprocess: () => preprocessType,
127
- promise: () => promiseType,
128
- quotelessJson: () => quotelessJson,
129
- record: () => recordType,
130
- set: () => setType,
131
- setErrorMap: () => setErrorMap,
132
- strictObject: () => strictObjectType,
133
- string: () => stringType,
134
- symbol: () => symbolType,
135
- transformer: () => effectsType,
136
- tuple: () => tupleType,
137
- undefined: () => undefinedType,
138
- union: () => unionType,
139
- unknown: () => unknownType,
140
- util: () => util,
141
- void: () => voidType
142
- });
143
-
144
- // node_modules/zod/v3/helpers/util.js
145
- var util;
146
- (function(util2) {
147
- util2.assertEqual = (_) => {
148
- };
149
- function assertIs(_arg) {
150
- }
151
- util2.assertIs = assertIs;
152
- function assertNever(_x) {
153
- throw new Error();
154
- }
155
- util2.assertNever = assertNever;
156
- util2.arrayToEnum = (items) => {
157
- const obj = {};
158
- for (const item of items) {
159
- obj[item] = item;
160
- }
161
- return obj;
162
- };
163
- util2.getValidEnumValues = (obj) => {
164
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
165
- const filtered = {};
166
- for (const k of validKeys) {
167
- filtered[k] = obj[k];
168
- }
169
- return util2.objectValues(filtered);
170
- };
171
- util2.objectValues = (obj) => {
172
- return util2.objectKeys(obj).map(function(e) {
173
- return obj[e];
174
- });
175
- };
176
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
177
- const keys = [];
178
- for (const key in object) {
179
- if (Object.prototype.hasOwnProperty.call(object, key)) {
180
- keys.push(key);
181
- }
182
- }
183
- return keys;
184
- };
185
- util2.find = (arr, checker) => {
186
- for (const item of arr) {
187
- if (checker(item))
188
- return item;
189
- }
190
- return void 0;
191
- };
192
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
193
- function joinValues(array, separator = " | ") {
194
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
195
- }
196
- util2.joinValues = joinValues;
197
- util2.jsonStringifyReplacer = (_, value) => {
198
- if (typeof value === "bigint") {
199
- return value.toString();
200
- }
201
- return value;
202
- };
203
- })(util || (util = {}));
204
- var objectUtil;
205
- (function(objectUtil2) {
206
- objectUtil2.mergeShapes = (first, second) => {
207
- return {
208
- ...first,
209
- ...second
210
- // second overwrites first
211
- };
212
- };
213
- })(objectUtil || (objectUtil = {}));
214
- var ZodParsedType = util.arrayToEnum([
215
- "string",
216
- "nan",
217
- "number",
218
- "integer",
219
- "float",
220
- "boolean",
221
- "date",
222
- "bigint",
223
- "symbol",
224
- "function",
225
- "undefined",
226
- "null",
227
- "array",
228
- "object",
229
- "unknown",
230
- "promise",
231
- "void",
232
- "never",
233
- "map",
234
- "set"
235
- ]);
236
- var getParsedType = (data) => {
237
- const t = typeof data;
238
- switch (t) {
239
- case "undefined":
240
- return ZodParsedType.undefined;
241
- case "string":
242
- return ZodParsedType.string;
243
- case "number":
244
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
245
- case "boolean":
246
- return ZodParsedType.boolean;
247
- case "function":
248
- return ZodParsedType.function;
249
- case "bigint":
250
- return ZodParsedType.bigint;
251
- case "symbol":
252
- return ZodParsedType.symbol;
253
- case "object":
254
- if (Array.isArray(data)) {
255
- return ZodParsedType.array;
256
- }
257
- if (data === null) {
258
- return ZodParsedType.null;
259
- }
260
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
261
- return ZodParsedType.promise;
262
- }
263
- if (typeof Map !== "undefined" && data instanceof Map) {
264
- return ZodParsedType.map;
265
- }
266
- if (typeof Set !== "undefined" && data instanceof Set) {
267
- return ZodParsedType.set;
268
- }
269
- if (typeof Date !== "undefined" && data instanceof Date) {
270
- return ZodParsedType.date;
271
- }
272
- return ZodParsedType.object;
273
- default:
274
- return ZodParsedType.unknown;
275
- }
276
- };
277
-
278
- // node_modules/zod/v3/ZodError.js
279
- var ZodIssueCode = util.arrayToEnum([
280
- "invalid_type",
281
- "invalid_literal",
282
- "custom",
283
- "invalid_union",
284
- "invalid_union_discriminator",
285
- "invalid_enum_value",
286
- "unrecognized_keys",
287
- "invalid_arguments",
288
- "invalid_return_type",
289
- "invalid_date",
290
- "invalid_string",
291
- "too_small",
292
- "too_big",
293
- "invalid_intersection_types",
294
- "not_multiple_of",
295
- "not_finite"
296
- ]);
297
- var quotelessJson = (obj) => {
298
- const json = JSON.stringify(obj, null, 2);
299
- return json.replace(/"([^"]+)":/g, "$1:");
300
- };
301
- var ZodError = class _ZodError extends Error {
302
- get errors() {
303
- return this.issues;
304
- }
305
- constructor(issues) {
306
- super();
307
- this.issues = [];
308
- this.addIssue = (sub) => {
309
- this.issues = [...this.issues, sub];
310
- };
311
- this.addIssues = (subs = []) => {
312
- this.issues = [...this.issues, ...subs];
313
- };
314
- const actualProto = new.target.prototype;
315
- if (Object.setPrototypeOf) {
316
- Object.setPrototypeOf(this, actualProto);
317
- } else {
318
- this.__proto__ = actualProto;
319
- }
320
- this.name = "ZodError";
321
- this.issues = issues;
322
- }
323
- format(_mapper) {
324
- const mapper = _mapper || function(issue) {
325
- return issue.message;
326
- };
327
- const fieldErrors = { _errors: [] };
328
- const processError = (error) => {
329
- for (const issue of error.issues) {
330
- if (issue.code === "invalid_union") {
331
- issue.unionErrors.map(processError);
332
- } else if (issue.code === "invalid_return_type") {
333
- processError(issue.returnTypeError);
334
- } else if (issue.code === "invalid_arguments") {
335
- processError(issue.argumentsError);
336
- } else if (issue.path.length === 0) {
337
- fieldErrors._errors.push(mapper(issue));
338
- } else {
339
- let curr = fieldErrors;
340
- let i = 0;
341
- while (i < issue.path.length) {
342
- const el = issue.path[i];
343
- const terminal = i === issue.path.length - 1;
344
- if (!terminal) {
345
- curr[el] = curr[el] || { _errors: [] };
346
- } else {
347
- curr[el] = curr[el] || { _errors: [] };
348
- curr[el]._errors.push(mapper(issue));
349
- }
350
- curr = curr[el];
351
- i++;
352
- }
353
- }
354
- }
355
- };
356
- processError(this);
357
- return fieldErrors;
358
- }
359
- static assert(value) {
360
- if (!(value instanceof _ZodError)) {
361
- throw new Error(`Not a ZodError: ${value}`);
362
- }
363
- }
364
- toString() {
365
- return this.message;
366
- }
367
- get message() {
368
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
369
- }
370
- get isEmpty() {
371
- return this.issues.length === 0;
372
- }
373
- flatten(mapper = (issue) => issue.message) {
374
- const fieldErrors = {};
375
- const formErrors = [];
376
- for (const sub of this.issues) {
377
- if (sub.path.length > 0) {
378
- const firstEl = sub.path[0];
379
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
380
- fieldErrors[firstEl].push(mapper(sub));
381
- } else {
382
- formErrors.push(mapper(sub));
383
- }
384
- }
385
- return { formErrors, fieldErrors };
386
- }
387
- get formErrors() {
388
- return this.flatten();
389
- }
390
- };
391
- ZodError.create = (issues) => {
392
- const error = new ZodError(issues);
393
- return error;
394
- };
395
-
396
- // node_modules/zod/v3/locales/en.js
397
- var errorMap = (issue, _ctx) => {
398
- let message;
399
- switch (issue.code) {
400
- case ZodIssueCode.invalid_type:
401
- if (issue.received === ZodParsedType.undefined) {
402
- message = "Required";
403
- } else {
404
- message = `Expected ${issue.expected}, received ${issue.received}`;
405
- }
406
- break;
407
- case ZodIssueCode.invalid_literal:
408
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
409
- break;
410
- case ZodIssueCode.unrecognized_keys:
411
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
412
- break;
413
- case ZodIssueCode.invalid_union:
414
- message = `Invalid input`;
415
- break;
416
- case ZodIssueCode.invalid_union_discriminator:
417
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
418
- break;
419
- case ZodIssueCode.invalid_enum_value:
420
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
421
- break;
422
- case ZodIssueCode.invalid_arguments:
423
- message = `Invalid function arguments`;
424
- break;
425
- case ZodIssueCode.invalid_return_type:
426
- message = `Invalid function return type`;
427
- break;
428
- case ZodIssueCode.invalid_date:
429
- message = `Invalid date`;
430
- break;
431
- case ZodIssueCode.invalid_string:
432
- if (typeof issue.validation === "object") {
433
- if ("includes" in issue.validation) {
434
- message = `Invalid input: must include "${issue.validation.includes}"`;
435
- if (typeof issue.validation.position === "number") {
436
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
437
- }
438
- } else if ("startsWith" in issue.validation) {
439
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
440
- } else if ("endsWith" in issue.validation) {
441
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
442
- } else {
443
- util.assertNever(issue.validation);
444
- }
445
- } else if (issue.validation !== "regex") {
446
- message = `Invalid ${issue.validation}`;
447
- } else {
448
- message = "Invalid";
449
- }
450
- break;
451
- case ZodIssueCode.too_small:
452
- if (issue.type === "array")
453
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
454
- else if (issue.type === "string")
455
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
456
- else if (issue.type === "number")
457
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
458
- else if (issue.type === "bigint")
459
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
460
- else if (issue.type === "date")
461
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
462
- else
463
- message = "Invalid input";
464
- break;
465
- case ZodIssueCode.too_big:
466
- if (issue.type === "array")
467
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
468
- else if (issue.type === "string")
469
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
470
- else if (issue.type === "number")
471
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
472
- else if (issue.type === "bigint")
473
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
474
- else if (issue.type === "date")
475
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
476
- else
477
- message = "Invalid input";
478
- break;
479
- case ZodIssueCode.custom:
480
- message = `Invalid input`;
481
- break;
482
- case ZodIssueCode.invalid_intersection_types:
483
- message = `Intersection results could not be merged`;
484
- break;
485
- case ZodIssueCode.not_multiple_of:
486
- message = `Number must be a multiple of ${issue.multipleOf}`;
487
- break;
488
- case ZodIssueCode.not_finite:
489
- message = "Number must be finite";
490
- break;
491
- default:
492
- message = _ctx.defaultError;
493
- util.assertNever(issue);
494
- }
495
- return { message };
496
- };
497
- var en_default = errorMap;
498
-
499
- // node_modules/zod/v3/errors.js
500
- var overrideErrorMap = en_default;
501
- function setErrorMap(map) {
502
- overrideErrorMap = map;
503
- }
504
- function getErrorMap() {
505
- return overrideErrorMap;
506
- }
507
-
508
- // node_modules/zod/v3/helpers/parseUtil.js
509
- var makeIssue = (params) => {
510
- const { data, path, errorMaps, issueData } = params;
511
- const fullPath = [...path, ...issueData.path || []];
512
- const fullIssue = {
513
- ...issueData,
514
- path: fullPath
515
- };
516
- if (issueData.message !== void 0) {
517
- return {
518
- ...issueData,
519
- path: fullPath,
520
- message: issueData.message
521
- };
522
- }
523
- let errorMessage = "";
524
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
525
- for (const map of maps) {
526
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
527
- }
528
- return {
529
- ...issueData,
530
- path: fullPath,
531
- message: errorMessage
532
- };
533
- };
534
- var EMPTY_PATH = [];
535
- function addIssueToContext(ctx, issueData) {
536
- const overrideMap = getErrorMap();
537
- const issue = makeIssue({
538
- issueData,
539
- data: ctx.data,
540
- path: ctx.path,
541
- errorMaps: [
542
- ctx.common.contextualErrorMap,
543
- // contextual error map is first priority
544
- ctx.schemaErrorMap,
545
- // then schema-bound map if available
546
- overrideMap,
547
- // then global override map
548
- overrideMap === en_default ? void 0 : en_default
549
- // then global default map
550
- ].filter((x) => !!x)
551
- });
552
- ctx.common.issues.push(issue);
553
- }
554
- var ParseStatus = class _ParseStatus {
555
- constructor() {
556
- this.value = "valid";
557
- }
558
- dirty() {
559
- if (this.value === "valid")
560
- this.value = "dirty";
561
- }
562
- abort() {
563
- if (this.value !== "aborted")
564
- this.value = "aborted";
565
- }
566
- static mergeArray(status, results) {
567
- const arrayValue = [];
568
- for (const s of results) {
569
- if (s.status === "aborted")
570
- return INVALID;
571
- if (s.status === "dirty")
572
- status.dirty();
573
- arrayValue.push(s.value);
574
- }
575
- return { status: status.value, value: arrayValue };
576
- }
577
- static async mergeObjectAsync(status, pairs) {
578
- const syncPairs = [];
579
- for (const pair of pairs) {
580
- const key = await pair.key;
581
- const value = await pair.value;
582
- syncPairs.push({
583
- key,
584
- value
585
- });
586
- }
587
- return _ParseStatus.mergeObjectSync(status, syncPairs);
588
- }
589
- static mergeObjectSync(status, pairs) {
590
- const finalObject = {};
591
- for (const pair of pairs) {
592
- const { key, value } = pair;
593
- if (key.status === "aborted")
594
- return INVALID;
595
- if (value.status === "aborted")
596
- return INVALID;
597
- if (key.status === "dirty")
598
- status.dirty();
599
- if (value.status === "dirty")
600
- status.dirty();
601
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
602
- finalObject[key.value] = value.value;
603
- }
604
- }
605
- return { status: status.value, value: finalObject };
606
- }
607
- };
608
- var INVALID = Object.freeze({
609
- status: "aborted"
610
- });
611
- var DIRTY = (value) => ({ status: "dirty", value });
612
- var OK = (value) => ({ status: "valid", value });
613
- var isAborted = (x) => x.status === "aborted";
614
- var isDirty = (x) => x.status === "dirty";
615
- var isValid = (x) => x.status === "valid";
616
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
617
-
618
- // node_modules/zod/v3/helpers/errorUtil.js
619
- var errorUtil;
620
- (function(errorUtil2) {
621
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
622
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
623
- })(errorUtil || (errorUtil = {}));
624
-
625
- // node_modules/zod/v3/types.js
626
- var ParseInputLazyPath = class {
627
- constructor(parent, value, path, key) {
628
- this._cachedPath = [];
629
- this.parent = parent;
630
- this.data = value;
631
- this._path = path;
632
- this._key = key;
633
- }
634
- get path() {
635
- if (!this._cachedPath.length) {
636
- if (Array.isArray(this._key)) {
637
- this._cachedPath.push(...this._path, ...this._key);
638
- } else {
639
- this._cachedPath.push(...this._path, this._key);
640
- }
641
- }
642
- return this._cachedPath;
643
- }
644
- };
645
- var handleResult = (ctx, result) => {
646
- if (isValid(result)) {
647
- return { success: true, data: result.value };
648
- } else {
649
- if (!ctx.common.issues.length) {
650
- throw new Error("Validation failed but no issues detected.");
651
- }
652
- return {
653
- success: false,
654
- get error() {
655
- if (this._error)
656
- return this._error;
657
- const error = new ZodError(ctx.common.issues);
658
- this._error = error;
659
- return this._error;
660
- }
661
- };
662
- }
663
- };
664
- function processCreateParams(params) {
665
- if (!params)
666
- return {};
667
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
668
- if (errorMap2 && (invalid_type_error || required_error)) {
669
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
670
- }
671
- if (errorMap2)
672
- return { errorMap: errorMap2, description };
673
- const customMap = (iss, ctx) => {
674
- const { message } = params;
675
- if (iss.code === "invalid_enum_value") {
676
- return { message: message ?? ctx.defaultError };
677
- }
678
- if (typeof ctx.data === "undefined") {
679
- return { message: message ?? required_error ?? ctx.defaultError };
680
- }
681
- if (iss.code !== "invalid_type")
682
- return { message: ctx.defaultError };
683
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
684
- };
685
- return { errorMap: customMap, description };
686
- }
687
- var ZodType = class {
688
- get description() {
689
- return this._def.description;
690
- }
691
- _getType(input) {
692
- return getParsedType(input.data);
693
- }
694
- _getOrReturnCtx(input, ctx) {
695
- return ctx || {
696
- common: input.parent.common,
697
- data: input.data,
698
- parsedType: getParsedType(input.data),
699
- schemaErrorMap: this._def.errorMap,
700
- path: input.path,
701
- parent: input.parent
702
- };
703
- }
704
- _processInputParams(input) {
705
- return {
706
- status: new ParseStatus(),
707
- ctx: {
708
- common: input.parent.common,
709
- data: input.data,
710
- parsedType: getParsedType(input.data),
711
- schemaErrorMap: this._def.errorMap,
712
- path: input.path,
713
- parent: input.parent
714
- }
715
- };
716
- }
717
- _parseSync(input) {
718
- const result = this._parse(input);
719
- if (isAsync(result)) {
720
- throw new Error("Synchronous parse encountered promise.");
721
- }
722
- return result;
723
- }
724
- _parseAsync(input) {
725
- const result = this._parse(input);
726
- return Promise.resolve(result);
727
- }
728
- parse(data, params) {
729
- const result = this.safeParse(data, params);
730
- if (result.success)
731
- return result.data;
732
- throw result.error;
733
- }
734
- safeParse(data, params) {
735
- const ctx = {
736
- common: {
737
- issues: [],
738
- async: params?.async ?? false,
739
- contextualErrorMap: params?.errorMap
740
- },
741
- path: params?.path || [],
742
- schemaErrorMap: this._def.errorMap,
743
- parent: null,
744
- data,
745
- parsedType: getParsedType(data)
746
- };
747
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
748
- return handleResult(ctx, result);
749
- }
750
- "~validate"(data) {
751
- const ctx = {
752
- common: {
753
- issues: [],
754
- async: !!this["~standard"].async
755
- },
756
- path: [],
757
- schemaErrorMap: this._def.errorMap,
758
- parent: null,
759
- data,
760
- parsedType: getParsedType(data)
761
- };
762
- if (!this["~standard"].async) {
763
- try {
764
- const result = this._parseSync({ data, path: [], parent: ctx });
765
- return isValid(result) ? {
766
- value: result.value
767
- } : {
768
- issues: ctx.common.issues
769
- };
770
- } catch (err) {
771
- if (err?.message?.toLowerCase()?.includes("encountered")) {
772
- this["~standard"].async = true;
773
- }
774
- ctx.common = {
775
- issues: [],
776
- async: true
777
- };
778
- }
779
- }
780
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
781
- value: result.value
782
- } : {
783
- issues: ctx.common.issues
784
- });
785
- }
786
- async parseAsync(data, params) {
787
- const result = await this.safeParseAsync(data, params);
788
- if (result.success)
789
- return result.data;
790
- throw result.error;
791
- }
792
- async safeParseAsync(data, params) {
793
- const ctx = {
794
- common: {
795
- issues: [],
796
- contextualErrorMap: params?.errorMap,
797
- async: true
798
- },
799
- path: params?.path || [],
800
- schemaErrorMap: this._def.errorMap,
801
- parent: null,
802
- data,
803
- parsedType: getParsedType(data)
804
- };
805
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
806
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
807
- return handleResult(ctx, result);
808
- }
809
- refine(check, message) {
810
- const getIssueProperties = (val) => {
811
- if (typeof message === "string" || typeof message === "undefined") {
812
- return { message };
813
- } else if (typeof message === "function") {
814
- return message(val);
815
- } else {
816
- return message;
817
- }
818
- };
819
- return this._refinement((val, ctx) => {
820
- const result = check(val);
821
- const setError = () => ctx.addIssue({
822
- code: ZodIssueCode.custom,
823
- ...getIssueProperties(val)
824
- });
825
- if (typeof Promise !== "undefined" && result instanceof Promise) {
826
- return result.then((data) => {
827
- if (!data) {
828
- setError();
829
- return false;
830
- } else {
831
- return true;
832
- }
833
- });
834
- }
835
- if (!result) {
836
- setError();
837
- return false;
838
- } else {
839
- return true;
840
- }
841
- });
842
- }
843
- refinement(check, refinementData) {
844
- return this._refinement((val, ctx) => {
845
- if (!check(val)) {
846
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
847
- return false;
848
- } else {
849
- return true;
850
- }
851
- });
852
- }
853
- _refinement(refinement) {
854
- return new ZodEffects({
855
- schema: this,
856
- typeName: ZodFirstPartyTypeKind.ZodEffects,
857
- effect: { type: "refinement", refinement }
858
- });
859
- }
860
- superRefine(refinement) {
861
- return this._refinement(refinement);
862
- }
863
- constructor(def) {
864
- this.spa = this.safeParseAsync;
865
- this._def = def;
866
- this.parse = this.parse.bind(this);
867
- this.safeParse = this.safeParse.bind(this);
868
- this.parseAsync = this.parseAsync.bind(this);
869
- this.safeParseAsync = this.safeParseAsync.bind(this);
870
- this.spa = this.spa.bind(this);
871
- this.refine = this.refine.bind(this);
872
- this.refinement = this.refinement.bind(this);
873
- this.superRefine = this.superRefine.bind(this);
874
- this.optional = this.optional.bind(this);
875
- this.nullable = this.nullable.bind(this);
876
- this.nullish = this.nullish.bind(this);
877
- this.array = this.array.bind(this);
878
- this.promise = this.promise.bind(this);
879
- this.or = this.or.bind(this);
880
- this.and = this.and.bind(this);
881
- this.transform = this.transform.bind(this);
882
- this.brand = this.brand.bind(this);
883
- this.default = this.default.bind(this);
884
- this.catch = this.catch.bind(this);
885
- this.describe = this.describe.bind(this);
886
- this.pipe = this.pipe.bind(this);
887
- this.readonly = this.readonly.bind(this);
888
- this.isNullable = this.isNullable.bind(this);
889
- this.isOptional = this.isOptional.bind(this);
890
- this["~standard"] = {
891
- version: 1,
892
- vendor: "zod",
893
- validate: (data) => this["~validate"](data)
894
- };
895
- }
896
- optional() {
897
- return ZodOptional.create(this, this._def);
898
- }
899
- nullable() {
900
- return ZodNullable.create(this, this._def);
901
- }
902
- nullish() {
903
- return this.nullable().optional();
904
- }
905
- array() {
906
- return ZodArray.create(this);
907
- }
908
- promise() {
909
- return ZodPromise.create(this, this._def);
910
- }
911
- or(option) {
912
- return ZodUnion.create([this, option], this._def);
913
- }
914
- and(incoming) {
915
- return ZodIntersection.create(this, incoming, this._def);
916
- }
917
- transform(transform) {
918
- return new ZodEffects({
919
- ...processCreateParams(this._def),
920
- schema: this,
921
- typeName: ZodFirstPartyTypeKind.ZodEffects,
922
- effect: { type: "transform", transform }
923
- });
924
- }
925
- default(def) {
926
- const defaultValueFunc = typeof def === "function" ? def : () => def;
927
- return new ZodDefault({
928
- ...processCreateParams(this._def),
929
- innerType: this,
930
- defaultValue: defaultValueFunc,
931
- typeName: ZodFirstPartyTypeKind.ZodDefault
932
- });
933
- }
934
- brand() {
935
- return new ZodBranded({
936
- typeName: ZodFirstPartyTypeKind.ZodBranded,
937
- type: this,
938
- ...processCreateParams(this._def)
939
- });
940
- }
941
- catch(def) {
942
- const catchValueFunc = typeof def === "function" ? def : () => def;
943
- return new ZodCatch({
944
- ...processCreateParams(this._def),
945
- innerType: this,
946
- catchValue: catchValueFunc,
947
- typeName: ZodFirstPartyTypeKind.ZodCatch
948
- });
949
- }
950
- describe(description) {
951
- const This = this.constructor;
952
- return new This({
953
- ...this._def,
954
- description
955
- });
956
- }
957
- pipe(target) {
958
- return ZodPipeline.create(this, target);
959
- }
960
- readonly() {
961
- return ZodReadonly.create(this);
962
- }
963
- isOptional() {
964
- return this.safeParse(void 0).success;
965
- }
966
- isNullable() {
967
- return this.safeParse(null).success;
968
- }
969
- };
970
- var cuidRegex = /^c[^\s-]{8,}$/i;
971
- var cuid2Regex = /^[0-9a-z]+$/;
972
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
973
- 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;
974
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
975
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
976
- var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
977
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
978
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
979
- var emojiRegex;
980
- var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
981
- var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
982
- var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
983
- var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
984
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
985
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
986
- var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
987
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
988
- function timeRegexSource(args) {
989
- let secondsRegexSource = `[0-5]\\d`;
990
- if (args.precision) {
991
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
992
- } else if (args.precision == null) {
993
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
994
- }
995
- const secondsQuantifier = args.precision ? "+" : "?";
996
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
997
- }
998
- function timeRegex(args) {
999
- return new RegExp(`^${timeRegexSource(args)}$`);
1000
- }
1001
- function datetimeRegex(args) {
1002
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1003
- const opts = [];
1004
- opts.push(args.local ? `Z?` : `Z`);
1005
- if (args.offset)
1006
- opts.push(`([+-]\\d{2}:?\\d{2})`);
1007
- regex = `${regex}(${opts.join("|")})`;
1008
- return new RegExp(`^${regex}$`);
1009
- }
1010
- function isValidIP(ip, version) {
1011
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1012
- return true;
1013
- }
1014
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1015
- return true;
1016
- }
1017
- return false;
1018
- }
1019
- function isValidJWT(jwt, alg) {
1020
- if (!jwtRegex.test(jwt))
1021
- return false;
1022
- try {
1023
- const [header] = jwt.split(".");
1024
- if (!header)
1025
- return false;
1026
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1027
- const decoded = JSON.parse(atob(base64));
1028
- if (typeof decoded !== "object" || decoded === null)
1029
- return false;
1030
- if ("typ" in decoded && decoded?.typ !== "JWT")
1031
- return false;
1032
- if (!decoded.alg)
1033
- return false;
1034
- if (alg && decoded.alg !== alg)
1035
- return false;
1036
- return true;
1037
- } catch {
1038
- return false;
1039
- }
1040
- }
1041
- function isValidCidr(ip, version) {
1042
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1043
- return true;
1044
- }
1045
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1046
- return true;
1047
- }
1048
- return false;
1049
- }
1050
- var ZodString = class _ZodString extends ZodType {
1051
- _parse(input) {
1052
- if (this._def.coerce) {
1053
- input.data = String(input.data);
1054
- }
1055
- const parsedType = this._getType(input);
1056
- if (parsedType !== ZodParsedType.string) {
1057
- const ctx2 = this._getOrReturnCtx(input);
1058
- addIssueToContext(ctx2, {
1059
- code: ZodIssueCode.invalid_type,
1060
- expected: ZodParsedType.string,
1061
- received: ctx2.parsedType
1062
- });
1063
- return INVALID;
1064
- }
1065
- const status = new ParseStatus();
1066
- let ctx = void 0;
1067
- for (const check of this._def.checks) {
1068
- if (check.kind === "min") {
1069
- if (input.data.length < check.value) {
1070
- ctx = this._getOrReturnCtx(input, ctx);
1071
- addIssueToContext(ctx, {
1072
- code: ZodIssueCode.too_small,
1073
- minimum: check.value,
1074
- type: "string",
1075
- inclusive: true,
1076
- exact: false,
1077
- message: check.message
1078
- });
1079
- status.dirty();
1080
- }
1081
- } else if (check.kind === "max") {
1082
- if (input.data.length > check.value) {
1083
- ctx = this._getOrReturnCtx(input, ctx);
1084
- addIssueToContext(ctx, {
1085
- code: ZodIssueCode.too_big,
1086
- maximum: check.value,
1087
- type: "string",
1088
- inclusive: true,
1089
- exact: false,
1090
- message: check.message
1091
- });
1092
- status.dirty();
1093
- }
1094
- } else if (check.kind === "length") {
1095
- const tooBig = input.data.length > check.value;
1096
- const tooSmall = input.data.length < check.value;
1097
- if (tooBig || tooSmall) {
1098
- ctx = this._getOrReturnCtx(input, ctx);
1099
- if (tooBig) {
1100
- addIssueToContext(ctx, {
1101
- code: ZodIssueCode.too_big,
1102
- maximum: check.value,
1103
- type: "string",
1104
- inclusive: true,
1105
- exact: true,
1106
- message: check.message
1107
- });
1108
- } else if (tooSmall) {
1109
- addIssueToContext(ctx, {
1110
- code: ZodIssueCode.too_small,
1111
- minimum: check.value,
1112
- type: "string",
1113
- inclusive: true,
1114
- exact: true,
1115
- message: check.message
1116
- });
1117
- }
1118
- status.dirty();
1119
- }
1120
- } else if (check.kind === "email") {
1121
- if (!emailRegex.test(input.data)) {
1122
- ctx = this._getOrReturnCtx(input, ctx);
1123
- addIssueToContext(ctx, {
1124
- validation: "email",
1125
- code: ZodIssueCode.invalid_string,
1126
- message: check.message
1127
- });
1128
- status.dirty();
1129
- }
1130
- } else if (check.kind === "emoji") {
1131
- if (!emojiRegex) {
1132
- emojiRegex = new RegExp(_emojiRegex, "u");
1133
- }
1134
- if (!emojiRegex.test(input.data)) {
1135
- ctx = this._getOrReturnCtx(input, ctx);
1136
- addIssueToContext(ctx, {
1137
- validation: "emoji",
1138
- code: ZodIssueCode.invalid_string,
1139
- message: check.message
1140
- });
1141
- status.dirty();
1142
- }
1143
- } else if (check.kind === "uuid") {
1144
- if (!uuidRegex.test(input.data)) {
1145
- ctx = this._getOrReturnCtx(input, ctx);
1146
- addIssueToContext(ctx, {
1147
- validation: "uuid",
1148
- code: ZodIssueCode.invalid_string,
1149
- message: check.message
1150
- });
1151
- status.dirty();
1152
- }
1153
- } else if (check.kind === "nanoid") {
1154
- if (!nanoidRegex.test(input.data)) {
1155
- ctx = this._getOrReturnCtx(input, ctx);
1156
- addIssueToContext(ctx, {
1157
- validation: "nanoid",
1158
- code: ZodIssueCode.invalid_string,
1159
- message: check.message
1160
- });
1161
- status.dirty();
1162
- }
1163
- } else if (check.kind === "cuid") {
1164
- if (!cuidRegex.test(input.data)) {
1165
- ctx = this._getOrReturnCtx(input, ctx);
1166
- addIssueToContext(ctx, {
1167
- validation: "cuid",
1168
- code: ZodIssueCode.invalid_string,
1169
- message: check.message
1170
- });
1171
- status.dirty();
1172
- }
1173
- } else if (check.kind === "cuid2") {
1174
- if (!cuid2Regex.test(input.data)) {
1175
- ctx = this._getOrReturnCtx(input, ctx);
1176
- addIssueToContext(ctx, {
1177
- validation: "cuid2",
1178
- code: ZodIssueCode.invalid_string,
1179
- message: check.message
1180
- });
1181
- status.dirty();
1182
- }
1183
- } else if (check.kind === "ulid") {
1184
- if (!ulidRegex.test(input.data)) {
1185
- ctx = this._getOrReturnCtx(input, ctx);
1186
- addIssueToContext(ctx, {
1187
- validation: "ulid",
1188
- code: ZodIssueCode.invalid_string,
1189
- message: check.message
1190
- });
1191
- status.dirty();
1192
- }
1193
- } else if (check.kind === "url") {
1194
- try {
1195
- new URL(input.data);
1196
- } catch {
1197
- ctx = this._getOrReturnCtx(input, ctx);
1198
- addIssueToContext(ctx, {
1199
- validation: "url",
1200
- code: ZodIssueCode.invalid_string,
1201
- message: check.message
1202
- });
1203
- status.dirty();
1204
- }
1205
- } else if (check.kind === "regex") {
1206
- check.regex.lastIndex = 0;
1207
- const testResult = check.regex.test(input.data);
1208
- if (!testResult) {
1209
- ctx = this._getOrReturnCtx(input, ctx);
1210
- addIssueToContext(ctx, {
1211
- validation: "regex",
1212
- code: ZodIssueCode.invalid_string,
1213
- message: check.message
1214
- });
1215
- status.dirty();
1216
- }
1217
- } else if (check.kind === "trim") {
1218
- input.data = input.data.trim();
1219
- } else if (check.kind === "includes") {
1220
- if (!input.data.includes(check.value, check.position)) {
1221
- ctx = this._getOrReturnCtx(input, ctx);
1222
- addIssueToContext(ctx, {
1223
- code: ZodIssueCode.invalid_string,
1224
- validation: { includes: check.value, position: check.position },
1225
- message: check.message
1226
- });
1227
- status.dirty();
1228
- }
1229
- } else if (check.kind === "toLowerCase") {
1230
- input.data = input.data.toLowerCase();
1231
- } else if (check.kind === "toUpperCase") {
1232
- input.data = input.data.toUpperCase();
1233
- } else if (check.kind === "startsWith") {
1234
- if (!input.data.startsWith(check.value)) {
1235
- ctx = this._getOrReturnCtx(input, ctx);
1236
- addIssueToContext(ctx, {
1237
- code: ZodIssueCode.invalid_string,
1238
- validation: { startsWith: check.value },
1239
- message: check.message
1240
- });
1241
- status.dirty();
1242
- }
1243
- } else if (check.kind === "endsWith") {
1244
- if (!input.data.endsWith(check.value)) {
1245
- ctx = this._getOrReturnCtx(input, ctx);
1246
- addIssueToContext(ctx, {
1247
- code: ZodIssueCode.invalid_string,
1248
- validation: { endsWith: check.value },
1249
- message: check.message
1250
- });
1251
- status.dirty();
1252
- }
1253
- } else if (check.kind === "datetime") {
1254
- const regex = datetimeRegex(check);
1255
- if (!regex.test(input.data)) {
1256
- ctx = this._getOrReturnCtx(input, ctx);
1257
- addIssueToContext(ctx, {
1258
- code: ZodIssueCode.invalid_string,
1259
- validation: "datetime",
1260
- message: check.message
1261
- });
1262
- status.dirty();
1263
- }
1264
- } else if (check.kind === "date") {
1265
- const regex = dateRegex;
1266
- if (!regex.test(input.data)) {
1267
- ctx = this._getOrReturnCtx(input, ctx);
1268
- addIssueToContext(ctx, {
1269
- code: ZodIssueCode.invalid_string,
1270
- validation: "date",
1271
- message: check.message
1272
- });
1273
- status.dirty();
1274
- }
1275
- } else if (check.kind === "time") {
1276
- const regex = timeRegex(check);
1277
- if (!regex.test(input.data)) {
1278
- ctx = this._getOrReturnCtx(input, ctx);
1279
- addIssueToContext(ctx, {
1280
- code: ZodIssueCode.invalid_string,
1281
- validation: "time",
1282
- message: check.message
1283
- });
1284
- status.dirty();
1285
- }
1286
- } else if (check.kind === "duration") {
1287
- if (!durationRegex.test(input.data)) {
1288
- ctx = this._getOrReturnCtx(input, ctx);
1289
- addIssueToContext(ctx, {
1290
- validation: "duration",
1291
- code: ZodIssueCode.invalid_string,
1292
- message: check.message
1293
- });
1294
- status.dirty();
1295
- }
1296
- } else if (check.kind === "ip") {
1297
- if (!isValidIP(input.data, check.version)) {
1298
- ctx = this._getOrReturnCtx(input, ctx);
1299
- addIssueToContext(ctx, {
1300
- validation: "ip",
1301
- code: ZodIssueCode.invalid_string,
1302
- message: check.message
1303
- });
1304
- status.dirty();
1305
- }
1306
- } else if (check.kind === "jwt") {
1307
- if (!isValidJWT(input.data, check.alg)) {
1308
- ctx = this._getOrReturnCtx(input, ctx);
1309
- addIssueToContext(ctx, {
1310
- validation: "jwt",
1311
- code: ZodIssueCode.invalid_string,
1312
- message: check.message
1313
- });
1314
- status.dirty();
1315
- }
1316
- } else if (check.kind === "cidr") {
1317
- if (!isValidCidr(input.data, check.version)) {
1318
- ctx = this._getOrReturnCtx(input, ctx);
1319
- addIssueToContext(ctx, {
1320
- validation: "cidr",
1321
- code: ZodIssueCode.invalid_string,
1322
- message: check.message
1323
- });
1324
- status.dirty();
1325
- }
1326
- } else if (check.kind === "base64") {
1327
- if (!base64Regex.test(input.data)) {
1328
- ctx = this._getOrReturnCtx(input, ctx);
1329
- addIssueToContext(ctx, {
1330
- validation: "base64",
1331
- code: ZodIssueCode.invalid_string,
1332
- message: check.message
1333
- });
1334
- status.dirty();
1335
- }
1336
- } else if (check.kind === "base64url") {
1337
- if (!base64urlRegex.test(input.data)) {
1338
- ctx = this._getOrReturnCtx(input, ctx);
1339
- addIssueToContext(ctx, {
1340
- validation: "base64url",
1341
- code: ZodIssueCode.invalid_string,
1342
- message: check.message
1343
- });
1344
- status.dirty();
1345
- }
1346
- } else {
1347
- util.assertNever(check);
1348
- }
1349
- }
1350
- return { status: status.value, value: input.data };
1351
- }
1352
- _regex(regex, validation, message) {
1353
- return this.refinement((data) => regex.test(data), {
1354
- validation,
1355
- code: ZodIssueCode.invalid_string,
1356
- ...errorUtil.errToObj(message)
1357
- });
1358
- }
1359
- _addCheck(check) {
1360
- return new _ZodString({
1361
- ...this._def,
1362
- checks: [...this._def.checks, check]
1363
- });
1364
- }
1365
- email(message) {
1366
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1367
- }
1368
- url(message) {
1369
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1370
- }
1371
- emoji(message) {
1372
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1373
- }
1374
- uuid(message) {
1375
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1376
- }
1377
- nanoid(message) {
1378
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1379
- }
1380
- cuid(message) {
1381
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1382
- }
1383
- cuid2(message) {
1384
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1385
- }
1386
- ulid(message) {
1387
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1388
- }
1389
- base64(message) {
1390
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1391
- }
1392
- base64url(message) {
1393
- return this._addCheck({
1394
- kind: "base64url",
1395
- ...errorUtil.errToObj(message)
1396
- });
1397
- }
1398
- jwt(options) {
1399
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1400
- }
1401
- ip(options) {
1402
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1403
- }
1404
- cidr(options) {
1405
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1406
- }
1407
- datetime(options) {
1408
- if (typeof options === "string") {
1409
- return this._addCheck({
1410
- kind: "datetime",
1411
- precision: null,
1412
- offset: false,
1413
- local: false,
1414
- message: options
1415
- });
1416
- }
1417
- return this._addCheck({
1418
- kind: "datetime",
1419
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1420
- offset: options?.offset ?? false,
1421
- local: options?.local ?? false,
1422
- ...errorUtil.errToObj(options?.message)
1423
- });
1424
- }
1425
- date(message) {
1426
- return this._addCheck({ kind: "date", message });
1427
- }
1428
- time(options) {
1429
- if (typeof options === "string") {
1430
- return this._addCheck({
1431
- kind: "time",
1432
- precision: null,
1433
- message: options
1434
- });
1435
- }
1436
- return this._addCheck({
1437
- kind: "time",
1438
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1439
- ...errorUtil.errToObj(options?.message)
1440
- });
1441
- }
1442
- duration(message) {
1443
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1444
- }
1445
- regex(regex, message) {
1446
- return this._addCheck({
1447
- kind: "regex",
1448
- regex,
1449
- ...errorUtil.errToObj(message)
1450
- });
1451
- }
1452
- includes(value, options) {
1453
- return this._addCheck({
1454
- kind: "includes",
1455
- value,
1456
- position: options?.position,
1457
- ...errorUtil.errToObj(options?.message)
1458
- });
1459
- }
1460
- startsWith(value, message) {
1461
- return this._addCheck({
1462
- kind: "startsWith",
1463
- value,
1464
- ...errorUtil.errToObj(message)
1465
- });
1466
- }
1467
- endsWith(value, message) {
1468
- return this._addCheck({
1469
- kind: "endsWith",
1470
- value,
1471
- ...errorUtil.errToObj(message)
1472
- });
1473
- }
1474
- min(minLength, message) {
1475
- return this._addCheck({
1476
- kind: "min",
1477
- value: minLength,
1478
- ...errorUtil.errToObj(message)
1479
- });
1480
- }
1481
- max(maxLength, message) {
1482
- return this._addCheck({
1483
- kind: "max",
1484
- value: maxLength,
1485
- ...errorUtil.errToObj(message)
1486
- });
1487
- }
1488
- length(len, message) {
1489
- return this._addCheck({
1490
- kind: "length",
1491
- value: len,
1492
- ...errorUtil.errToObj(message)
1493
- });
1494
- }
1495
- /**
1496
- * Equivalent to `.min(1)`
1497
- */
1498
- nonempty(message) {
1499
- return this.min(1, errorUtil.errToObj(message));
1500
- }
1501
- trim() {
1502
- return new _ZodString({
1503
- ...this._def,
1504
- checks: [...this._def.checks, { kind: "trim" }]
1505
- });
1506
- }
1507
- toLowerCase() {
1508
- return new _ZodString({
1509
- ...this._def,
1510
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1511
- });
1512
- }
1513
- toUpperCase() {
1514
- return new _ZodString({
1515
- ...this._def,
1516
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1517
- });
1518
- }
1519
- get isDatetime() {
1520
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1521
- }
1522
- get isDate() {
1523
- return !!this._def.checks.find((ch) => ch.kind === "date");
1524
- }
1525
- get isTime() {
1526
- return !!this._def.checks.find((ch) => ch.kind === "time");
1527
- }
1528
- get isDuration() {
1529
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1530
- }
1531
- get isEmail() {
1532
- return !!this._def.checks.find((ch) => ch.kind === "email");
1533
- }
1534
- get isURL() {
1535
- return !!this._def.checks.find((ch) => ch.kind === "url");
1536
- }
1537
- get isEmoji() {
1538
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1539
- }
1540
- get isUUID() {
1541
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1542
- }
1543
- get isNANOID() {
1544
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1545
- }
1546
- get isCUID() {
1547
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1548
- }
1549
- get isCUID2() {
1550
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1551
- }
1552
- get isULID() {
1553
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1554
- }
1555
- get isIP() {
1556
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1557
- }
1558
- get isCIDR() {
1559
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1560
- }
1561
- get isBase64() {
1562
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1563
- }
1564
- get isBase64url() {
1565
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1566
- }
1567
- get minLength() {
1568
- let min = null;
1569
- for (const ch of this._def.checks) {
1570
- if (ch.kind === "min") {
1571
- if (min === null || ch.value > min)
1572
- min = ch.value;
1573
- }
1574
- }
1575
- return min;
1576
- }
1577
- get maxLength() {
1578
- let max = null;
1579
- for (const ch of this._def.checks) {
1580
- if (ch.kind === "max") {
1581
- if (max === null || ch.value < max)
1582
- max = ch.value;
1583
- }
1584
- }
1585
- return max;
1586
- }
1587
- };
1588
- ZodString.create = (params) => {
1589
- return new ZodString({
1590
- checks: [],
1591
- typeName: ZodFirstPartyTypeKind.ZodString,
1592
- coerce: params?.coerce ?? false,
1593
- ...processCreateParams(params)
1594
- });
1595
- };
1596
- function floatSafeRemainder(val, step) {
1597
- const valDecCount = (val.toString().split(".")[1] || "").length;
1598
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1599
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1600
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1601
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1602
- return valInt % stepInt / 10 ** decCount;
1603
- }
1604
- var ZodNumber = class _ZodNumber extends ZodType {
1605
- constructor() {
1606
- super(...arguments);
1607
- this.min = this.gte;
1608
- this.max = this.lte;
1609
- this.step = this.multipleOf;
1610
- }
1611
- _parse(input) {
1612
- if (this._def.coerce) {
1613
- input.data = Number(input.data);
1614
- }
1615
- const parsedType = this._getType(input);
1616
- if (parsedType !== ZodParsedType.number) {
1617
- const ctx2 = this._getOrReturnCtx(input);
1618
- addIssueToContext(ctx2, {
1619
- code: ZodIssueCode.invalid_type,
1620
- expected: ZodParsedType.number,
1621
- received: ctx2.parsedType
1622
- });
1623
- return INVALID;
1624
- }
1625
- let ctx = void 0;
1626
- const status = new ParseStatus();
1627
- for (const check of this._def.checks) {
1628
- if (check.kind === "int") {
1629
- if (!util.isInteger(input.data)) {
1630
- ctx = this._getOrReturnCtx(input, ctx);
1631
- addIssueToContext(ctx, {
1632
- code: ZodIssueCode.invalid_type,
1633
- expected: "integer",
1634
- received: "float",
1635
- message: check.message
1636
- });
1637
- status.dirty();
1638
- }
1639
- } else if (check.kind === "min") {
1640
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1641
- if (tooSmall) {
1642
- ctx = this._getOrReturnCtx(input, ctx);
1643
- addIssueToContext(ctx, {
1644
- code: ZodIssueCode.too_small,
1645
- minimum: check.value,
1646
- type: "number",
1647
- inclusive: check.inclusive,
1648
- exact: false,
1649
- message: check.message
1650
- });
1651
- status.dirty();
1652
- }
1653
- } else if (check.kind === "max") {
1654
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1655
- if (tooBig) {
1656
- ctx = this._getOrReturnCtx(input, ctx);
1657
- addIssueToContext(ctx, {
1658
- code: ZodIssueCode.too_big,
1659
- maximum: check.value,
1660
- type: "number",
1661
- inclusive: check.inclusive,
1662
- exact: false,
1663
- message: check.message
1664
- });
1665
- status.dirty();
1666
- }
1667
- } else if (check.kind === "multipleOf") {
1668
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1669
- ctx = this._getOrReturnCtx(input, ctx);
1670
- addIssueToContext(ctx, {
1671
- code: ZodIssueCode.not_multiple_of,
1672
- multipleOf: check.value,
1673
- message: check.message
1674
- });
1675
- status.dirty();
1676
- }
1677
- } else if (check.kind === "finite") {
1678
- if (!Number.isFinite(input.data)) {
1679
- ctx = this._getOrReturnCtx(input, ctx);
1680
- addIssueToContext(ctx, {
1681
- code: ZodIssueCode.not_finite,
1682
- message: check.message
1683
- });
1684
- status.dirty();
1685
- }
1686
- } else {
1687
- util.assertNever(check);
1688
- }
1689
- }
1690
- return { status: status.value, value: input.data };
1691
- }
1692
- gte(value, message) {
1693
- return this.setLimit("min", value, true, errorUtil.toString(message));
1694
- }
1695
- gt(value, message) {
1696
- return this.setLimit("min", value, false, errorUtil.toString(message));
1697
- }
1698
- lte(value, message) {
1699
- return this.setLimit("max", value, true, errorUtil.toString(message));
1700
- }
1701
- lt(value, message) {
1702
- return this.setLimit("max", value, false, errorUtil.toString(message));
1703
- }
1704
- setLimit(kind, value, inclusive, message) {
1705
- return new _ZodNumber({
1706
- ...this._def,
1707
- checks: [
1708
- ...this._def.checks,
1709
- {
1710
- kind,
1711
- value,
1712
- inclusive,
1713
- message: errorUtil.toString(message)
1714
- }
1715
- ]
1716
- });
1717
- }
1718
- _addCheck(check) {
1719
- return new _ZodNumber({
1720
- ...this._def,
1721
- checks: [...this._def.checks, check]
1722
- });
1723
- }
1724
- int(message) {
1725
- return this._addCheck({
1726
- kind: "int",
1727
- message: errorUtil.toString(message)
1728
- });
1729
- }
1730
- positive(message) {
1731
- return this._addCheck({
1732
- kind: "min",
1733
- value: 0,
1734
- inclusive: false,
1735
- message: errorUtil.toString(message)
1736
- });
1737
- }
1738
- negative(message) {
1739
- return this._addCheck({
1740
- kind: "max",
1741
- value: 0,
1742
- inclusive: false,
1743
- message: errorUtil.toString(message)
1744
- });
1745
- }
1746
- nonpositive(message) {
1747
- return this._addCheck({
1748
- kind: "max",
1749
- value: 0,
1750
- inclusive: true,
1751
- message: errorUtil.toString(message)
1752
- });
1753
- }
1754
- nonnegative(message) {
1755
- return this._addCheck({
1756
- kind: "min",
1757
- value: 0,
1758
- inclusive: true,
1759
- message: errorUtil.toString(message)
1760
- });
1761
- }
1762
- multipleOf(value, message) {
1763
- return this._addCheck({
1764
- kind: "multipleOf",
1765
- value,
1766
- message: errorUtil.toString(message)
1767
- });
1768
- }
1769
- finite(message) {
1770
- return this._addCheck({
1771
- kind: "finite",
1772
- message: errorUtil.toString(message)
1773
- });
1774
- }
1775
- safe(message) {
1776
- return this._addCheck({
1777
- kind: "min",
1778
- inclusive: true,
1779
- value: Number.MIN_SAFE_INTEGER,
1780
- message: errorUtil.toString(message)
1781
- })._addCheck({
1782
- kind: "max",
1783
- inclusive: true,
1784
- value: Number.MAX_SAFE_INTEGER,
1785
- message: errorUtil.toString(message)
1786
- });
1787
- }
1788
- get minValue() {
1789
- let min = null;
1790
- for (const ch of this._def.checks) {
1791
- if (ch.kind === "min") {
1792
- if (min === null || ch.value > min)
1793
- min = ch.value;
1794
- }
1795
- }
1796
- return min;
1797
- }
1798
- get maxValue() {
1799
- let max = null;
1800
- for (const ch of this._def.checks) {
1801
- if (ch.kind === "max") {
1802
- if (max === null || ch.value < max)
1803
- max = ch.value;
1804
- }
1805
- }
1806
- return max;
1807
- }
1808
- get isInt() {
1809
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1810
- }
1811
- get isFinite() {
1812
- let max = null;
1813
- let min = null;
1814
- for (const ch of this._def.checks) {
1815
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1816
- return true;
1817
- } else if (ch.kind === "min") {
1818
- if (min === null || ch.value > min)
1819
- min = ch.value;
1820
- } else if (ch.kind === "max") {
1821
- if (max === null || ch.value < max)
1822
- max = ch.value;
1823
- }
1824
- }
1825
- return Number.isFinite(min) && Number.isFinite(max);
1826
- }
1827
- };
1828
- ZodNumber.create = (params) => {
1829
- return new ZodNumber({
1830
- checks: [],
1831
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1832
- coerce: params?.coerce || false,
1833
- ...processCreateParams(params)
1834
- });
1835
- };
1836
- var ZodBigInt = class _ZodBigInt extends ZodType {
1837
- constructor() {
1838
- super(...arguments);
1839
- this.min = this.gte;
1840
- this.max = this.lte;
1841
- }
1842
- _parse(input) {
1843
- if (this._def.coerce) {
1844
- try {
1845
- input.data = BigInt(input.data);
1846
- } catch {
1847
- return this._getInvalidInput(input);
1848
- }
1849
- }
1850
- const parsedType = this._getType(input);
1851
- if (parsedType !== ZodParsedType.bigint) {
1852
- return this._getInvalidInput(input);
1853
- }
1854
- let ctx = void 0;
1855
- const status = new ParseStatus();
1856
- for (const check of this._def.checks) {
1857
- if (check.kind === "min") {
1858
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1859
- if (tooSmall) {
1860
- ctx = this._getOrReturnCtx(input, ctx);
1861
- addIssueToContext(ctx, {
1862
- code: ZodIssueCode.too_small,
1863
- type: "bigint",
1864
- minimum: check.value,
1865
- inclusive: check.inclusive,
1866
- message: check.message
1867
- });
1868
- status.dirty();
1869
- }
1870
- } else if (check.kind === "max") {
1871
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1872
- if (tooBig) {
1873
- ctx = this._getOrReturnCtx(input, ctx);
1874
- addIssueToContext(ctx, {
1875
- code: ZodIssueCode.too_big,
1876
- type: "bigint",
1877
- maximum: check.value,
1878
- inclusive: check.inclusive,
1879
- message: check.message
1880
- });
1881
- status.dirty();
1882
- }
1883
- } else if (check.kind === "multipleOf") {
1884
- if (input.data % check.value !== BigInt(0)) {
1885
- ctx = this._getOrReturnCtx(input, ctx);
1886
- addIssueToContext(ctx, {
1887
- code: ZodIssueCode.not_multiple_of,
1888
- multipleOf: check.value,
1889
- message: check.message
1890
- });
1891
- status.dirty();
1892
- }
1893
- } else {
1894
- util.assertNever(check);
1895
- }
1896
- }
1897
- return { status: status.value, value: input.data };
1898
- }
1899
- _getInvalidInput(input) {
1900
- const ctx = this._getOrReturnCtx(input);
1901
- addIssueToContext(ctx, {
1902
- code: ZodIssueCode.invalid_type,
1903
- expected: ZodParsedType.bigint,
1904
- received: ctx.parsedType
1905
- });
1906
- return INVALID;
1907
- }
1908
- gte(value, message) {
1909
- return this.setLimit("min", value, true, errorUtil.toString(message));
1910
- }
1911
- gt(value, message) {
1912
- return this.setLimit("min", value, false, errorUtil.toString(message));
1913
- }
1914
- lte(value, message) {
1915
- return this.setLimit("max", value, true, errorUtil.toString(message));
1916
- }
1917
- lt(value, message) {
1918
- return this.setLimit("max", value, false, errorUtil.toString(message));
1919
- }
1920
- setLimit(kind, value, inclusive, message) {
1921
- return new _ZodBigInt({
1922
- ...this._def,
1923
- checks: [
1924
- ...this._def.checks,
1925
- {
1926
- kind,
1927
- value,
1928
- inclusive,
1929
- message: errorUtil.toString(message)
1930
- }
1931
- ]
1932
- });
1933
- }
1934
- _addCheck(check) {
1935
- return new _ZodBigInt({
1936
- ...this._def,
1937
- checks: [...this._def.checks, check]
1938
- });
1939
- }
1940
- positive(message) {
1941
- return this._addCheck({
1942
- kind: "min",
1943
- value: BigInt(0),
1944
- inclusive: false,
1945
- message: errorUtil.toString(message)
1946
- });
1947
- }
1948
- negative(message) {
1949
- return this._addCheck({
1950
- kind: "max",
1951
- value: BigInt(0),
1952
- inclusive: false,
1953
- message: errorUtil.toString(message)
1954
- });
1955
- }
1956
- nonpositive(message) {
1957
- return this._addCheck({
1958
- kind: "max",
1959
- value: BigInt(0),
1960
- inclusive: true,
1961
- message: errorUtil.toString(message)
1962
- });
1963
- }
1964
- nonnegative(message) {
1965
- return this._addCheck({
1966
- kind: "min",
1967
- value: BigInt(0),
1968
- inclusive: true,
1969
- message: errorUtil.toString(message)
1970
- });
1971
- }
1972
- multipleOf(value, message) {
1973
- return this._addCheck({
1974
- kind: "multipleOf",
1975
- value,
1976
- message: errorUtil.toString(message)
1977
- });
1978
- }
1979
- get minValue() {
1980
- let min = null;
1981
- for (const ch of this._def.checks) {
1982
- if (ch.kind === "min") {
1983
- if (min === null || ch.value > min)
1984
- min = ch.value;
1985
- }
1986
- }
1987
- return min;
1988
- }
1989
- get maxValue() {
1990
- let max = null;
1991
- for (const ch of this._def.checks) {
1992
- if (ch.kind === "max") {
1993
- if (max === null || ch.value < max)
1994
- max = ch.value;
1995
- }
1996
- }
1997
- return max;
1998
- }
1999
- };
2000
- ZodBigInt.create = (params) => {
2001
- return new ZodBigInt({
2002
- checks: [],
2003
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
2004
- coerce: params?.coerce ?? false,
2005
- ...processCreateParams(params)
2006
- });
2007
- };
2008
- var ZodBoolean = class extends ZodType {
2009
- _parse(input) {
2010
- if (this._def.coerce) {
2011
- input.data = Boolean(input.data);
2012
- }
2013
- const parsedType = this._getType(input);
2014
- if (parsedType !== ZodParsedType.boolean) {
2015
- const ctx = this._getOrReturnCtx(input);
2016
- addIssueToContext(ctx, {
2017
- code: ZodIssueCode.invalid_type,
2018
- expected: ZodParsedType.boolean,
2019
- received: ctx.parsedType
2020
- });
2021
- return INVALID;
2022
- }
2023
- return OK(input.data);
2024
- }
2025
- };
2026
- ZodBoolean.create = (params) => {
2027
- return new ZodBoolean({
2028
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2029
- coerce: params?.coerce || false,
2030
- ...processCreateParams(params)
2031
- });
2032
- };
2033
- var ZodDate = class _ZodDate extends ZodType {
2034
- _parse(input) {
2035
- if (this._def.coerce) {
2036
- input.data = new Date(input.data);
2037
- }
2038
- const parsedType = this._getType(input);
2039
- if (parsedType !== ZodParsedType.date) {
2040
- const ctx2 = this._getOrReturnCtx(input);
2041
- addIssueToContext(ctx2, {
2042
- code: ZodIssueCode.invalid_type,
2043
- expected: ZodParsedType.date,
2044
- received: ctx2.parsedType
2045
- });
2046
- return INVALID;
2047
- }
2048
- if (Number.isNaN(input.data.getTime())) {
2049
- const ctx2 = this._getOrReturnCtx(input);
2050
- addIssueToContext(ctx2, {
2051
- code: ZodIssueCode.invalid_date
2052
- });
2053
- return INVALID;
2054
- }
2055
- const status = new ParseStatus();
2056
- let ctx = void 0;
2057
- for (const check of this._def.checks) {
2058
- if (check.kind === "min") {
2059
- if (input.data.getTime() < check.value) {
2060
- ctx = this._getOrReturnCtx(input, ctx);
2061
- addIssueToContext(ctx, {
2062
- code: ZodIssueCode.too_small,
2063
- message: check.message,
2064
- inclusive: true,
2065
- exact: false,
2066
- minimum: check.value,
2067
- type: "date"
2068
- });
2069
- status.dirty();
2070
- }
2071
- } else if (check.kind === "max") {
2072
- if (input.data.getTime() > check.value) {
2073
- ctx = this._getOrReturnCtx(input, ctx);
2074
- addIssueToContext(ctx, {
2075
- code: ZodIssueCode.too_big,
2076
- message: check.message,
2077
- inclusive: true,
2078
- exact: false,
2079
- maximum: check.value,
2080
- type: "date"
2081
- });
2082
- status.dirty();
2083
- }
2084
- } else {
2085
- util.assertNever(check);
2086
- }
2087
- }
2088
- return {
2089
- status: status.value,
2090
- value: new Date(input.data.getTime())
2091
- };
2092
- }
2093
- _addCheck(check) {
2094
- return new _ZodDate({
2095
- ...this._def,
2096
- checks: [...this._def.checks, check]
2097
- });
2098
- }
2099
- min(minDate, message) {
2100
- return this._addCheck({
2101
- kind: "min",
2102
- value: minDate.getTime(),
2103
- message: errorUtil.toString(message)
2104
- });
2105
- }
2106
- max(maxDate, message) {
2107
- return this._addCheck({
2108
- kind: "max",
2109
- value: maxDate.getTime(),
2110
- message: errorUtil.toString(message)
2111
- });
2112
- }
2113
- get minDate() {
2114
- let min = null;
2115
- for (const ch of this._def.checks) {
2116
- if (ch.kind === "min") {
2117
- if (min === null || ch.value > min)
2118
- min = ch.value;
2119
- }
2120
- }
2121
- return min != null ? new Date(min) : null;
2122
- }
2123
- get maxDate() {
2124
- let max = null;
2125
- for (const ch of this._def.checks) {
2126
- if (ch.kind === "max") {
2127
- if (max === null || ch.value < max)
2128
- max = ch.value;
2129
- }
2130
- }
2131
- return max != null ? new Date(max) : null;
2132
- }
2133
- };
2134
- ZodDate.create = (params) => {
2135
- return new ZodDate({
2136
- checks: [],
2137
- coerce: params?.coerce || false,
2138
- typeName: ZodFirstPartyTypeKind.ZodDate,
2139
- ...processCreateParams(params)
2140
- });
2141
- };
2142
- var ZodSymbol = class extends ZodType {
2143
- _parse(input) {
2144
- const parsedType = this._getType(input);
2145
- if (parsedType !== ZodParsedType.symbol) {
2146
- const ctx = this._getOrReturnCtx(input);
2147
- addIssueToContext(ctx, {
2148
- code: ZodIssueCode.invalid_type,
2149
- expected: ZodParsedType.symbol,
2150
- received: ctx.parsedType
2151
- });
2152
- return INVALID;
2153
- }
2154
- return OK(input.data);
2155
- }
2156
- };
2157
- ZodSymbol.create = (params) => {
2158
- return new ZodSymbol({
2159
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2160
- ...processCreateParams(params)
2161
- });
2162
- };
2163
- var ZodUndefined = class extends ZodType {
2164
- _parse(input) {
2165
- const parsedType = this._getType(input);
2166
- if (parsedType !== ZodParsedType.undefined) {
2167
- const ctx = this._getOrReturnCtx(input);
2168
- addIssueToContext(ctx, {
2169
- code: ZodIssueCode.invalid_type,
2170
- expected: ZodParsedType.undefined,
2171
- received: ctx.parsedType
2172
- });
2173
- return INVALID;
2174
- }
2175
- return OK(input.data);
2176
- }
2177
- };
2178
- ZodUndefined.create = (params) => {
2179
- return new ZodUndefined({
2180
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2181
- ...processCreateParams(params)
2182
- });
2183
- };
2184
- var ZodNull = class extends ZodType {
2185
- _parse(input) {
2186
- const parsedType = this._getType(input);
2187
- if (parsedType !== ZodParsedType.null) {
2188
- const ctx = this._getOrReturnCtx(input);
2189
- addIssueToContext(ctx, {
2190
- code: ZodIssueCode.invalid_type,
2191
- expected: ZodParsedType.null,
2192
- received: ctx.parsedType
2193
- });
2194
- return INVALID;
2195
- }
2196
- return OK(input.data);
2197
- }
2198
- };
2199
- ZodNull.create = (params) => {
2200
- return new ZodNull({
2201
- typeName: ZodFirstPartyTypeKind.ZodNull,
2202
- ...processCreateParams(params)
2203
- });
2204
- };
2205
- var ZodAny = class extends ZodType {
2206
- constructor() {
2207
- super(...arguments);
2208
- this._any = true;
2209
- }
2210
- _parse(input) {
2211
- return OK(input.data);
2212
- }
2213
- };
2214
- ZodAny.create = (params) => {
2215
- return new ZodAny({
2216
- typeName: ZodFirstPartyTypeKind.ZodAny,
2217
- ...processCreateParams(params)
2218
- });
2219
- };
2220
- var ZodUnknown = class extends ZodType {
2221
- constructor() {
2222
- super(...arguments);
2223
- this._unknown = true;
2224
- }
2225
- _parse(input) {
2226
- return OK(input.data);
2227
- }
2228
- };
2229
- ZodUnknown.create = (params) => {
2230
- return new ZodUnknown({
2231
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2232
- ...processCreateParams(params)
2233
- });
2234
- };
2235
- var ZodNever = class extends ZodType {
2236
- _parse(input) {
2237
- const ctx = this._getOrReturnCtx(input);
2238
- addIssueToContext(ctx, {
2239
- code: ZodIssueCode.invalid_type,
2240
- expected: ZodParsedType.never,
2241
- received: ctx.parsedType
2242
- });
2243
- return INVALID;
2244
- }
2245
- };
2246
- ZodNever.create = (params) => {
2247
- return new ZodNever({
2248
- typeName: ZodFirstPartyTypeKind.ZodNever,
2249
- ...processCreateParams(params)
2250
- });
2251
- };
2252
- var ZodVoid = class extends ZodType {
2253
- _parse(input) {
2254
- const parsedType = this._getType(input);
2255
- if (parsedType !== ZodParsedType.undefined) {
2256
- const ctx = this._getOrReturnCtx(input);
2257
- addIssueToContext(ctx, {
2258
- code: ZodIssueCode.invalid_type,
2259
- expected: ZodParsedType.void,
2260
- received: ctx.parsedType
2261
- });
2262
- return INVALID;
2263
- }
2264
- return OK(input.data);
2265
- }
2266
- };
2267
- ZodVoid.create = (params) => {
2268
- return new ZodVoid({
2269
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2270
- ...processCreateParams(params)
2271
- });
2272
- };
2273
- var ZodArray = class _ZodArray extends ZodType {
2274
- _parse(input) {
2275
- const { ctx, status } = this._processInputParams(input);
2276
- const def = this._def;
2277
- if (ctx.parsedType !== ZodParsedType.array) {
2278
- addIssueToContext(ctx, {
2279
- code: ZodIssueCode.invalid_type,
2280
- expected: ZodParsedType.array,
2281
- received: ctx.parsedType
2282
- });
2283
- return INVALID;
2284
- }
2285
- if (def.exactLength !== null) {
2286
- const tooBig = ctx.data.length > def.exactLength.value;
2287
- const tooSmall = ctx.data.length < def.exactLength.value;
2288
- if (tooBig || tooSmall) {
2289
- addIssueToContext(ctx, {
2290
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2291
- minimum: tooSmall ? def.exactLength.value : void 0,
2292
- maximum: tooBig ? def.exactLength.value : void 0,
2293
- type: "array",
2294
- inclusive: true,
2295
- exact: true,
2296
- message: def.exactLength.message
2297
- });
2298
- status.dirty();
2299
- }
2300
- }
2301
- if (def.minLength !== null) {
2302
- if (ctx.data.length < def.minLength.value) {
2303
- addIssueToContext(ctx, {
2304
- code: ZodIssueCode.too_small,
2305
- minimum: def.minLength.value,
2306
- type: "array",
2307
- inclusive: true,
2308
- exact: false,
2309
- message: def.minLength.message
2310
- });
2311
- status.dirty();
2312
- }
2313
- }
2314
- if (def.maxLength !== null) {
2315
- if (ctx.data.length > def.maxLength.value) {
2316
- addIssueToContext(ctx, {
2317
- code: ZodIssueCode.too_big,
2318
- maximum: def.maxLength.value,
2319
- type: "array",
2320
- inclusive: true,
2321
- exact: false,
2322
- message: def.maxLength.message
2323
- });
2324
- status.dirty();
2325
- }
2326
- }
2327
- if (ctx.common.async) {
2328
- return Promise.all([...ctx.data].map((item, i) => {
2329
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2330
- })).then((result2) => {
2331
- return ParseStatus.mergeArray(status, result2);
2332
- });
2333
- }
2334
- const result = [...ctx.data].map((item, i) => {
2335
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2336
- });
2337
- return ParseStatus.mergeArray(status, result);
2338
- }
2339
- get element() {
2340
- return this._def.type;
2341
- }
2342
- min(minLength, message) {
2343
- return new _ZodArray({
2344
- ...this._def,
2345
- minLength: { value: minLength, message: errorUtil.toString(message) }
2346
- });
2347
- }
2348
- max(maxLength, message) {
2349
- return new _ZodArray({
2350
- ...this._def,
2351
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
2352
- });
2353
- }
2354
- length(len, message) {
2355
- return new _ZodArray({
2356
- ...this._def,
2357
- exactLength: { value: len, message: errorUtil.toString(message) }
2358
- });
2359
- }
2360
- nonempty(message) {
2361
- return this.min(1, message);
2362
- }
2363
- };
2364
- ZodArray.create = (schema, params) => {
2365
- return new ZodArray({
2366
- type: schema,
2367
- minLength: null,
2368
- maxLength: null,
2369
- exactLength: null,
2370
- typeName: ZodFirstPartyTypeKind.ZodArray,
2371
- ...processCreateParams(params)
2372
- });
2373
- };
2374
- function deepPartialify(schema) {
2375
- if (schema instanceof ZodObject) {
2376
- const newShape = {};
2377
- for (const key in schema.shape) {
2378
- const fieldSchema = schema.shape[key];
2379
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2380
- }
2381
- return new ZodObject({
2382
- ...schema._def,
2383
- shape: () => newShape
2384
- });
2385
- } else if (schema instanceof ZodArray) {
2386
- return new ZodArray({
2387
- ...schema._def,
2388
- type: deepPartialify(schema.element)
2389
- });
2390
- } else if (schema instanceof ZodOptional) {
2391
- return ZodOptional.create(deepPartialify(schema.unwrap()));
2392
- } else if (schema instanceof ZodNullable) {
2393
- return ZodNullable.create(deepPartialify(schema.unwrap()));
2394
- } else if (schema instanceof ZodTuple) {
2395
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2396
- } else {
2397
- return schema;
2398
- }
2399
- }
2400
- var ZodObject = class _ZodObject extends ZodType {
2401
- constructor() {
2402
- super(...arguments);
2403
- this._cached = null;
2404
- this.nonstrict = this.passthrough;
2405
- this.augment = this.extend;
2406
- }
2407
- _getCached() {
2408
- if (this._cached !== null)
2409
- return this._cached;
2410
- const shape = this._def.shape();
2411
- const keys = util.objectKeys(shape);
2412
- this._cached = { shape, keys };
2413
- return this._cached;
2414
- }
2415
- _parse(input) {
2416
- const parsedType = this._getType(input);
2417
- if (parsedType !== ZodParsedType.object) {
2418
- const ctx2 = this._getOrReturnCtx(input);
2419
- addIssueToContext(ctx2, {
2420
- code: ZodIssueCode.invalid_type,
2421
- expected: ZodParsedType.object,
2422
- received: ctx2.parsedType
2423
- });
2424
- return INVALID;
2425
- }
2426
- const { status, ctx } = this._processInputParams(input);
2427
- const { shape, keys: shapeKeys } = this._getCached();
2428
- const extraKeys = [];
2429
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2430
- for (const key in ctx.data) {
2431
- if (!shapeKeys.includes(key)) {
2432
- extraKeys.push(key);
2433
- }
2434
- }
2435
- }
2436
- const pairs = [];
2437
- for (const key of shapeKeys) {
2438
- const keyValidator = shape[key];
2439
- const value = ctx.data[key];
2440
- pairs.push({
2441
- key: { status: "valid", value: key },
2442
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2443
- alwaysSet: key in ctx.data
2444
- });
2445
- }
2446
- if (this._def.catchall instanceof ZodNever) {
2447
- const unknownKeys = this._def.unknownKeys;
2448
- if (unknownKeys === "passthrough") {
2449
- for (const key of extraKeys) {
2450
- pairs.push({
2451
- key: { status: "valid", value: key },
2452
- value: { status: "valid", value: ctx.data[key] }
2453
- });
2454
- }
2455
- } else if (unknownKeys === "strict") {
2456
- if (extraKeys.length > 0) {
2457
- addIssueToContext(ctx, {
2458
- code: ZodIssueCode.unrecognized_keys,
2459
- keys: extraKeys
2460
- });
2461
- status.dirty();
2462
- }
2463
- } else if (unknownKeys === "strip") {
2464
- } else {
2465
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2466
- }
2467
- } else {
2468
- const catchall = this._def.catchall;
2469
- for (const key of extraKeys) {
2470
- const value = ctx.data[key];
2471
- pairs.push({
2472
- key: { status: "valid", value: key },
2473
- value: catchall._parse(
2474
- new ParseInputLazyPath(ctx, value, ctx.path, key)
2475
- //, ctx.child(key), value, getParsedType(value)
2476
- ),
2477
- alwaysSet: key in ctx.data
2478
- });
2479
- }
2480
- }
2481
- if (ctx.common.async) {
2482
- return Promise.resolve().then(async () => {
2483
- const syncPairs = [];
2484
- for (const pair of pairs) {
2485
- const key = await pair.key;
2486
- const value = await pair.value;
2487
- syncPairs.push({
2488
- key,
2489
- value,
2490
- alwaysSet: pair.alwaysSet
2491
- });
2492
- }
2493
- return syncPairs;
2494
- }).then((syncPairs) => {
2495
- return ParseStatus.mergeObjectSync(status, syncPairs);
2496
- });
2497
- } else {
2498
- return ParseStatus.mergeObjectSync(status, pairs);
2499
- }
2500
- }
2501
- get shape() {
2502
- return this._def.shape();
2503
- }
2504
- strict(message) {
2505
- errorUtil.errToObj;
2506
- return new _ZodObject({
2507
- ...this._def,
2508
- unknownKeys: "strict",
2509
- ...message !== void 0 ? {
2510
- errorMap: (issue, ctx) => {
2511
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2512
- if (issue.code === "unrecognized_keys")
2513
- return {
2514
- message: errorUtil.errToObj(message).message ?? defaultError
2515
- };
2516
- return {
2517
- message: defaultError
2518
- };
2519
- }
2520
- } : {}
2521
- });
2522
- }
2523
- strip() {
2524
- return new _ZodObject({
2525
- ...this._def,
2526
- unknownKeys: "strip"
2527
- });
2528
- }
2529
- passthrough() {
2530
- return new _ZodObject({
2531
- ...this._def,
2532
- unknownKeys: "passthrough"
2533
- });
2534
- }
2535
- // const AugmentFactory =
2536
- // <Def extends ZodObjectDef>(def: Def) =>
2537
- // <Augmentation extends ZodRawShape>(
2538
- // augmentation: Augmentation
2539
- // ): ZodObject<
2540
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2541
- // Def["unknownKeys"],
2542
- // Def["catchall"]
2543
- // > => {
2544
- // return new ZodObject({
2545
- // ...def,
2546
- // shape: () => ({
2547
- // ...def.shape(),
2548
- // ...augmentation,
2549
- // }),
2550
- // }) as any;
2551
- // };
2552
- extend(augmentation) {
2553
- return new _ZodObject({
2554
- ...this._def,
2555
- shape: () => ({
2556
- ...this._def.shape(),
2557
- ...augmentation
2558
- })
2559
- });
2560
- }
2561
- /**
2562
- * Prior to zod@1.0.12 there was a bug in the
2563
- * inferred type of merged objects. Please
2564
- * upgrade if you are experiencing issues.
2565
- */
2566
- merge(merging) {
2567
- const merged = new _ZodObject({
2568
- unknownKeys: merging._def.unknownKeys,
2569
- catchall: merging._def.catchall,
2570
- shape: () => ({
2571
- ...this._def.shape(),
2572
- ...merging._def.shape()
2573
- }),
2574
- typeName: ZodFirstPartyTypeKind.ZodObject
2575
- });
2576
- return merged;
2577
- }
2578
- // merge<
2579
- // Incoming extends AnyZodObject,
2580
- // Augmentation extends Incoming["shape"],
2581
- // NewOutput extends {
2582
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2583
- // ? Augmentation[k]["_output"]
2584
- // : k extends keyof Output
2585
- // ? Output[k]
2586
- // : never;
2587
- // },
2588
- // NewInput extends {
2589
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2590
- // ? Augmentation[k]["_input"]
2591
- // : k extends keyof Input
2592
- // ? Input[k]
2593
- // : never;
2594
- // }
2595
- // >(
2596
- // merging: Incoming
2597
- // ): ZodObject<
2598
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2599
- // Incoming["_def"]["unknownKeys"],
2600
- // Incoming["_def"]["catchall"],
2601
- // NewOutput,
2602
- // NewInput
2603
- // > {
2604
- // const merged: any = new ZodObject({
2605
- // unknownKeys: merging._def.unknownKeys,
2606
- // catchall: merging._def.catchall,
2607
- // shape: () =>
2608
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2609
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2610
- // }) as any;
2611
- // return merged;
2612
- // }
2613
- setKey(key, schema) {
2614
- return this.augment({ [key]: schema });
2615
- }
2616
- // merge<Incoming extends AnyZodObject>(
2617
- // merging: Incoming
2618
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2619
- // ZodObject<
2620
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2621
- // Incoming["_def"]["unknownKeys"],
2622
- // Incoming["_def"]["catchall"]
2623
- // > {
2624
- // // const mergedShape = objectUtil.mergeShapes(
2625
- // // this._def.shape(),
2626
- // // merging._def.shape()
2627
- // // );
2628
- // const merged: any = new ZodObject({
2629
- // unknownKeys: merging._def.unknownKeys,
2630
- // catchall: merging._def.catchall,
2631
- // shape: () =>
2632
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2633
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2634
- // }) as any;
2635
- // return merged;
2636
- // }
2637
- catchall(index) {
2638
- return new _ZodObject({
2639
- ...this._def,
2640
- catchall: index
2641
- });
2642
- }
2643
- pick(mask) {
2644
- const shape = {};
2645
- for (const key of util.objectKeys(mask)) {
2646
- if (mask[key] && this.shape[key]) {
2647
- shape[key] = this.shape[key];
2648
- }
2649
- }
2650
- return new _ZodObject({
2651
- ...this._def,
2652
- shape: () => shape
2653
- });
2654
- }
2655
- omit(mask) {
2656
- const shape = {};
2657
- for (const key of util.objectKeys(this.shape)) {
2658
- if (!mask[key]) {
2659
- shape[key] = this.shape[key];
2660
- }
2661
- }
2662
- return new _ZodObject({
2663
- ...this._def,
2664
- shape: () => shape
2665
- });
2666
- }
2667
- /**
2668
- * @deprecated
2669
- */
2670
- deepPartial() {
2671
- return deepPartialify(this);
2672
- }
2673
- partial(mask) {
2674
- const newShape = {};
2675
- for (const key of util.objectKeys(this.shape)) {
2676
- const fieldSchema = this.shape[key];
2677
- if (mask && !mask[key]) {
2678
- newShape[key] = fieldSchema;
2679
- } else {
2680
- newShape[key] = fieldSchema.optional();
2681
- }
2682
- }
2683
- return new _ZodObject({
2684
- ...this._def,
2685
- shape: () => newShape
2686
- });
2687
- }
2688
- required(mask) {
2689
- const newShape = {};
2690
- for (const key of util.objectKeys(this.shape)) {
2691
- if (mask && !mask[key]) {
2692
- newShape[key] = this.shape[key];
2693
- } else {
2694
- const fieldSchema = this.shape[key];
2695
- let newField = fieldSchema;
2696
- while (newField instanceof ZodOptional) {
2697
- newField = newField._def.innerType;
2698
- }
2699
- newShape[key] = newField;
2700
- }
2701
- }
2702
- return new _ZodObject({
2703
- ...this._def,
2704
- shape: () => newShape
2705
- });
2706
- }
2707
- keyof() {
2708
- return createZodEnum(util.objectKeys(this.shape));
2709
- }
2710
- };
2711
- ZodObject.create = (shape, params) => {
2712
- return new ZodObject({
2713
- shape: () => shape,
2714
- unknownKeys: "strip",
2715
- catchall: ZodNever.create(),
2716
- typeName: ZodFirstPartyTypeKind.ZodObject,
2717
- ...processCreateParams(params)
2718
- });
2719
- };
2720
- ZodObject.strictCreate = (shape, params) => {
2721
- return new ZodObject({
2722
- shape: () => shape,
2723
- unknownKeys: "strict",
2724
- catchall: ZodNever.create(),
2725
- typeName: ZodFirstPartyTypeKind.ZodObject,
2726
- ...processCreateParams(params)
2727
- });
2728
- };
2729
- ZodObject.lazycreate = (shape, params) => {
2730
- return new ZodObject({
2731
- shape,
2732
- unknownKeys: "strip",
2733
- catchall: ZodNever.create(),
2734
- typeName: ZodFirstPartyTypeKind.ZodObject,
2735
- ...processCreateParams(params)
2736
- });
2737
- };
2738
- var ZodUnion = class extends ZodType {
2739
- _parse(input) {
2740
- const { ctx } = this._processInputParams(input);
2741
- const options = this._def.options;
2742
- function handleResults(results) {
2743
- for (const result of results) {
2744
- if (result.result.status === "valid") {
2745
- return result.result;
2746
- }
2747
- }
2748
- for (const result of results) {
2749
- if (result.result.status === "dirty") {
2750
- ctx.common.issues.push(...result.ctx.common.issues);
2751
- return result.result;
2752
- }
2753
- }
2754
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2755
- addIssueToContext(ctx, {
2756
- code: ZodIssueCode.invalid_union,
2757
- unionErrors
2758
- });
2759
- return INVALID;
2760
- }
2761
- if (ctx.common.async) {
2762
- return Promise.all(options.map(async (option) => {
2763
- const childCtx = {
2764
- ...ctx,
2765
- common: {
2766
- ...ctx.common,
2767
- issues: []
2768
- },
2769
- parent: null
2770
- };
2771
- return {
2772
- result: await option._parseAsync({
2773
- data: ctx.data,
2774
- path: ctx.path,
2775
- parent: childCtx
2776
- }),
2777
- ctx: childCtx
2778
- };
2779
- })).then(handleResults);
2780
- } else {
2781
- let dirty = void 0;
2782
- const issues = [];
2783
- for (const option of options) {
2784
- const childCtx = {
2785
- ...ctx,
2786
- common: {
2787
- ...ctx.common,
2788
- issues: []
2789
- },
2790
- parent: null
2791
- };
2792
- const result = option._parseSync({
2793
- data: ctx.data,
2794
- path: ctx.path,
2795
- parent: childCtx
2796
- });
2797
- if (result.status === "valid") {
2798
- return result;
2799
- } else if (result.status === "dirty" && !dirty) {
2800
- dirty = { result, ctx: childCtx };
2801
- }
2802
- if (childCtx.common.issues.length) {
2803
- issues.push(childCtx.common.issues);
2804
- }
2805
- }
2806
- if (dirty) {
2807
- ctx.common.issues.push(...dirty.ctx.common.issues);
2808
- return dirty.result;
2809
- }
2810
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
2811
- addIssueToContext(ctx, {
2812
- code: ZodIssueCode.invalid_union,
2813
- unionErrors
2814
- });
2815
- return INVALID;
2816
- }
2817
- }
2818
- get options() {
2819
- return this._def.options;
2820
- }
2821
- };
2822
- ZodUnion.create = (types, params) => {
2823
- return new ZodUnion({
2824
- options: types,
2825
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2826
- ...processCreateParams(params)
2827
- });
2828
- };
2829
- var getDiscriminator = (type) => {
2830
- if (type instanceof ZodLazy) {
2831
- return getDiscriminator(type.schema);
2832
- } else if (type instanceof ZodEffects) {
2833
- return getDiscriminator(type.innerType());
2834
- } else if (type instanceof ZodLiteral) {
2835
- return [type.value];
2836
- } else if (type instanceof ZodEnum) {
2837
- return type.options;
2838
- } else if (type instanceof ZodNativeEnum) {
2839
- return util.objectValues(type.enum);
2840
- } else if (type instanceof ZodDefault) {
2841
- return getDiscriminator(type._def.innerType);
2842
- } else if (type instanceof ZodUndefined) {
2843
- return [void 0];
2844
- } else if (type instanceof ZodNull) {
2845
- return [null];
2846
- } else if (type instanceof ZodOptional) {
2847
- return [void 0, ...getDiscriminator(type.unwrap())];
2848
- } else if (type instanceof ZodNullable) {
2849
- return [null, ...getDiscriminator(type.unwrap())];
2850
- } else if (type instanceof ZodBranded) {
2851
- return getDiscriminator(type.unwrap());
2852
- } else if (type instanceof ZodReadonly) {
2853
- return getDiscriminator(type.unwrap());
2854
- } else if (type instanceof ZodCatch) {
2855
- return getDiscriminator(type._def.innerType);
2856
- } else {
2857
- return [];
2858
- }
2859
- };
2860
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2861
- _parse(input) {
2862
- const { ctx } = this._processInputParams(input);
2863
- if (ctx.parsedType !== ZodParsedType.object) {
2864
- addIssueToContext(ctx, {
2865
- code: ZodIssueCode.invalid_type,
2866
- expected: ZodParsedType.object,
2867
- received: ctx.parsedType
2868
- });
2869
- return INVALID;
2870
- }
2871
- const discriminator = this.discriminator;
2872
- const discriminatorValue = ctx.data[discriminator];
2873
- const option = this.optionsMap.get(discriminatorValue);
2874
- if (!option) {
2875
- addIssueToContext(ctx, {
2876
- code: ZodIssueCode.invalid_union_discriminator,
2877
- options: Array.from(this.optionsMap.keys()),
2878
- path: [discriminator]
2879
- });
2880
- return INVALID;
2881
- }
2882
- if (ctx.common.async) {
2883
- return option._parseAsync({
2884
- data: ctx.data,
2885
- path: ctx.path,
2886
- parent: ctx
2887
- });
2888
- } else {
2889
- return option._parseSync({
2890
- data: ctx.data,
2891
- path: ctx.path,
2892
- parent: ctx
2893
- });
2894
- }
2895
- }
2896
- get discriminator() {
2897
- return this._def.discriminator;
2898
- }
2899
- get options() {
2900
- return this._def.options;
2901
- }
2902
- get optionsMap() {
2903
- return this._def.optionsMap;
2904
- }
2905
- /**
2906
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2907
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2908
- * have a different value for each object in the union.
2909
- * @param discriminator the name of the discriminator property
2910
- * @param types an array of object schemas
2911
- * @param params
2912
- */
2913
- static create(discriminator, options, params) {
2914
- const optionsMap = /* @__PURE__ */ new Map();
2915
- for (const type of options) {
2916
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2917
- if (!discriminatorValues.length) {
2918
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2919
- }
2920
- for (const value of discriminatorValues) {
2921
- if (optionsMap.has(value)) {
2922
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2923
- }
2924
- optionsMap.set(value, type);
2925
- }
2926
- }
2927
- return new _ZodDiscriminatedUnion({
2928
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2929
- discriminator,
2930
- options,
2931
- optionsMap,
2932
- ...processCreateParams(params)
2933
- });
2934
- }
2935
- };
2936
- function mergeValues(a, b) {
2937
- const aType = getParsedType(a);
2938
- const bType = getParsedType(b);
2939
- if (a === b) {
2940
- return { valid: true, data: a };
2941
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2942
- const bKeys = util.objectKeys(b);
2943
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2944
- const newObj = { ...a, ...b };
2945
- for (const key of sharedKeys) {
2946
- const sharedValue = mergeValues(a[key], b[key]);
2947
- if (!sharedValue.valid) {
2948
- return { valid: false };
2949
- }
2950
- newObj[key] = sharedValue.data;
2951
- }
2952
- return { valid: true, data: newObj };
2953
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2954
- if (a.length !== b.length) {
2955
- return { valid: false };
2956
- }
2957
- const newArray = [];
2958
- for (let index = 0; index < a.length; index++) {
2959
- const itemA = a[index];
2960
- const itemB = b[index];
2961
- const sharedValue = mergeValues(itemA, itemB);
2962
- if (!sharedValue.valid) {
2963
- return { valid: false };
2964
- }
2965
- newArray.push(sharedValue.data);
2966
- }
2967
- return { valid: true, data: newArray };
2968
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2969
- return { valid: true, data: a };
2970
- } else {
2971
- return { valid: false };
2972
- }
2973
- }
2974
- var ZodIntersection = class extends ZodType {
2975
- _parse(input) {
2976
- const { status, ctx } = this._processInputParams(input);
2977
- const handleParsed = (parsedLeft, parsedRight) => {
2978
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2979
- return INVALID;
2980
- }
2981
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2982
- if (!merged.valid) {
2983
- addIssueToContext(ctx, {
2984
- code: ZodIssueCode.invalid_intersection_types
2985
- });
2986
- return INVALID;
2987
- }
2988
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2989
- status.dirty();
2990
- }
2991
- return { status: status.value, value: merged.data };
2992
- };
2993
- if (ctx.common.async) {
2994
- return Promise.all([
2995
- this._def.left._parseAsync({
2996
- data: ctx.data,
2997
- path: ctx.path,
2998
- parent: ctx
2999
- }),
3000
- this._def.right._parseAsync({
3001
- data: ctx.data,
3002
- path: ctx.path,
3003
- parent: ctx
3004
- })
3005
- ]).then(([left, right]) => handleParsed(left, right));
3006
- } else {
3007
- return handleParsed(this._def.left._parseSync({
3008
- data: ctx.data,
3009
- path: ctx.path,
3010
- parent: ctx
3011
- }), this._def.right._parseSync({
3012
- data: ctx.data,
3013
- path: ctx.path,
3014
- parent: ctx
3015
- }));
3016
- }
3017
- }
3018
- };
3019
- ZodIntersection.create = (left, right, params) => {
3020
- return new ZodIntersection({
3021
- left,
3022
- right,
3023
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
3024
- ...processCreateParams(params)
3025
- });
3026
- };
3027
- var ZodTuple = class _ZodTuple extends ZodType {
3028
- _parse(input) {
3029
- const { status, ctx } = this._processInputParams(input);
3030
- if (ctx.parsedType !== ZodParsedType.array) {
3031
- addIssueToContext(ctx, {
3032
- code: ZodIssueCode.invalid_type,
3033
- expected: ZodParsedType.array,
3034
- received: ctx.parsedType
3035
- });
3036
- return INVALID;
3037
- }
3038
- if (ctx.data.length < this._def.items.length) {
3039
- addIssueToContext(ctx, {
3040
- code: ZodIssueCode.too_small,
3041
- minimum: this._def.items.length,
3042
- inclusive: true,
3043
- exact: false,
3044
- type: "array"
3045
- });
3046
- return INVALID;
3047
- }
3048
- const rest = this._def.rest;
3049
- if (!rest && ctx.data.length > this._def.items.length) {
3050
- addIssueToContext(ctx, {
3051
- code: ZodIssueCode.too_big,
3052
- maximum: this._def.items.length,
3053
- inclusive: true,
3054
- exact: false,
3055
- type: "array"
3056
- });
3057
- status.dirty();
3058
- }
3059
- const items = [...ctx.data].map((item, itemIndex) => {
3060
- const schema = this._def.items[itemIndex] || this._def.rest;
3061
- if (!schema)
3062
- return null;
3063
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3064
- }).filter((x) => !!x);
3065
- if (ctx.common.async) {
3066
- return Promise.all(items).then((results) => {
3067
- return ParseStatus.mergeArray(status, results);
3068
- });
3069
- } else {
3070
- return ParseStatus.mergeArray(status, items);
3071
- }
3072
- }
3073
- get items() {
3074
- return this._def.items;
3075
- }
3076
- rest(rest) {
3077
- return new _ZodTuple({
3078
- ...this._def,
3079
- rest
3080
- });
3081
- }
3082
- };
3083
- ZodTuple.create = (schemas, params) => {
3084
- if (!Array.isArray(schemas)) {
3085
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3086
- }
3087
- return new ZodTuple({
3088
- items: schemas,
3089
- typeName: ZodFirstPartyTypeKind.ZodTuple,
3090
- rest: null,
3091
- ...processCreateParams(params)
3092
- });
3093
- };
3094
- var ZodRecord = class _ZodRecord extends ZodType {
3095
- get keySchema() {
3096
- return this._def.keyType;
3097
- }
3098
- get valueSchema() {
3099
- return this._def.valueType;
3100
- }
3101
- _parse(input) {
3102
- const { status, ctx } = this._processInputParams(input);
3103
- if (ctx.parsedType !== ZodParsedType.object) {
3104
- addIssueToContext(ctx, {
3105
- code: ZodIssueCode.invalid_type,
3106
- expected: ZodParsedType.object,
3107
- received: ctx.parsedType
3108
- });
3109
- return INVALID;
3110
- }
3111
- const pairs = [];
3112
- const keyType = this._def.keyType;
3113
- const valueType = this._def.valueType;
3114
- for (const key in ctx.data) {
3115
- pairs.push({
3116
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3117
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3118
- alwaysSet: key in ctx.data
3119
- });
3120
- }
3121
- if (ctx.common.async) {
3122
- return ParseStatus.mergeObjectAsync(status, pairs);
3123
- } else {
3124
- return ParseStatus.mergeObjectSync(status, pairs);
3125
- }
3126
- }
3127
- get element() {
3128
- return this._def.valueType;
3129
- }
3130
- static create(first, second, third) {
3131
- if (second instanceof ZodType) {
3132
- return new _ZodRecord({
3133
- keyType: first,
3134
- valueType: second,
3135
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3136
- ...processCreateParams(third)
3137
- });
3138
- }
3139
- return new _ZodRecord({
3140
- keyType: ZodString.create(),
3141
- valueType: first,
3142
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3143
- ...processCreateParams(second)
3144
- });
3145
- }
3146
- };
3147
- var ZodMap = class extends ZodType {
3148
- get keySchema() {
3149
- return this._def.keyType;
3150
- }
3151
- get valueSchema() {
3152
- return this._def.valueType;
3153
- }
3154
- _parse(input) {
3155
- const { status, ctx } = this._processInputParams(input);
3156
- if (ctx.parsedType !== ZodParsedType.map) {
3157
- addIssueToContext(ctx, {
3158
- code: ZodIssueCode.invalid_type,
3159
- expected: ZodParsedType.map,
3160
- received: ctx.parsedType
3161
- });
3162
- return INVALID;
3163
- }
3164
- const keyType = this._def.keyType;
3165
- const valueType = this._def.valueType;
3166
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3167
- return {
3168
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3169
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3170
- };
3171
- });
3172
- if (ctx.common.async) {
3173
- const finalMap = /* @__PURE__ */ new Map();
3174
- return Promise.resolve().then(async () => {
3175
- for (const pair of pairs) {
3176
- const key = await pair.key;
3177
- const value = await pair.value;
3178
- if (key.status === "aborted" || value.status === "aborted") {
3179
- return INVALID;
3180
- }
3181
- if (key.status === "dirty" || value.status === "dirty") {
3182
- status.dirty();
3183
- }
3184
- finalMap.set(key.value, value.value);
3185
- }
3186
- return { status: status.value, value: finalMap };
3187
- });
3188
- } else {
3189
- const finalMap = /* @__PURE__ */ new Map();
3190
- for (const pair of pairs) {
3191
- const key = pair.key;
3192
- const value = pair.value;
3193
- if (key.status === "aborted" || value.status === "aborted") {
3194
- return INVALID;
3195
- }
3196
- if (key.status === "dirty" || value.status === "dirty") {
3197
- status.dirty();
3198
- }
3199
- finalMap.set(key.value, value.value);
3200
- }
3201
- return { status: status.value, value: finalMap };
3202
- }
3203
- }
3204
- };
3205
- ZodMap.create = (keyType, valueType, params) => {
3206
- return new ZodMap({
3207
- valueType,
3208
- keyType,
3209
- typeName: ZodFirstPartyTypeKind.ZodMap,
3210
- ...processCreateParams(params)
3211
- });
3212
- };
3213
- var ZodSet = class _ZodSet extends ZodType {
3214
- _parse(input) {
3215
- const { status, ctx } = this._processInputParams(input);
3216
- if (ctx.parsedType !== ZodParsedType.set) {
3217
- addIssueToContext(ctx, {
3218
- code: ZodIssueCode.invalid_type,
3219
- expected: ZodParsedType.set,
3220
- received: ctx.parsedType
3221
- });
3222
- return INVALID;
3223
- }
3224
- const def = this._def;
3225
- if (def.minSize !== null) {
3226
- if (ctx.data.size < def.minSize.value) {
3227
- addIssueToContext(ctx, {
3228
- code: ZodIssueCode.too_small,
3229
- minimum: def.minSize.value,
3230
- type: "set",
3231
- inclusive: true,
3232
- exact: false,
3233
- message: def.minSize.message
3234
- });
3235
- status.dirty();
3236
- }
3237
- }
3238
- if (def.maxSize !== null) {
3239
- if (ctx.data.size > def.maxSize.value) {
3240
- addIssueToContext(ctx, {
3241
- code: ZodIssueCode.too_big,
3242
- maximum: def.maxSize.value,
3243
- type: "set",
3244
- inclusive: true,
3245
- exact: false,
3246
- message: def.maxSize.message
3247
- });
3248
- status.dirty();
3249
- }
3250
- }
3251
- const valueType = this._def.valueType;
3252
- function finalizeSet(elements2) {
3253
- const parsedSet = /* @__PURE__ */ new Set();
3254
- for (const element of elements2) {
3255
- if (element.status === "aborted")
3256
- return INVALID;
3257
- if (element.status === "dirty")
3258
- status.dirty();
3259
- parsedSet.add(element.value);
3260
- }
3261
- return { status: status.value, value: parsedSet };
3262
- }
3263
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3264
- if (ctx.common.async) {
3265
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3266
- } else {
3267
- return finalizeSet(elements);
3268
- }
3269
- }
3270
- min(minSize, message) {
3271
- return new _ZodSet({
3272
- ...this._def,
3273
- minSize: { value: minSize, message: errorUtil.toString(message) }
3274
- });
3275
- }
3276
- max(maxSize, message) {
3277
- return new _ZodSet({
3278
- ...this._def,
3279
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
3280
- });
3281
- }
3282
- size(size, message) {
3283
- return this.min(size, message).max(size, message);
3284
- }
3285
- nonempty(message) {
3286
- return this.min(1, message);
3287
- }
3288
- };
3289
- ZodSet.create = (valueType, params) => {
3290
- return new ZodSet({
3291
- valueType,
3292
- minSize: null,
3293
- maxSize: null,
3294
- typeName: ZodFirstPartyTypeKind.ZodSet,
3295
- ...processCreateParams(params)
3296
- });
3297
- };
3298
- var ZodFunction = class _ZodFunction extends ZodType {
3299
- constructor() {
3300
- super(...arguments);
3301
- this.validate = this.implement;
3302
- }
3303
- _parse(input) {
3304
- const { ctx } = this._processInputParams(input);
3305
- if (ctx.parsedType !== ZodParsedType.function) {
3306
- addIssueToContext(ctx, {
3307
- code: ZodIssueCode.invalid_type,
3308
- expected: ZodParsedType.function,
3309
- received: ctx.parsedType
3310
- });
3311
- return INVALID;
3312
- }
3313
- function makeArgsIssue(args, error) {
3314
- return makeIssue({
3315
- data: args,
3316
- path: ctx.path,
3317
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3318
- issueData: {
3319
- code: ZodIssueCode.invalid_arguments,
3320
- argumentsError: error
3321
- }
3322
- });
3323
- }
3324
- function makeReturnsIssue(returns, error) {
3325
- return makeIssue({
3326
- data: returns,
3327
- path: ctx.path,
3328
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3329
- issueData: {
3330
- code: ZodIssueCode.invalid_return_type,
3331
- returnTypeError: error
3332
- }
3333
- });
3334
- }
3335
- const params = { errorMap: ctx.common.contextualErrorMap };
3336
- const fn = ctx.data;
3337
- if (this._def.returns instanceof ZodPromise) {
3338
- const me = this;
3339
- return OK(async function(...args) {
3340
- const error = new ZodError([]);
3341
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3342
- error.addIssue(makeArgsIssue(args, e));
3343
- throw error;
3344
- });
3345
- const result = await Reflect.apply(fn, this, parsedArgs);
3346
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3347
- error.addIssue(makeReturnsIssue(result, e));
3348
- throw error;
3349
- });
3350
- return parsedReturns;
3351
- });
3352
- } else {
3353
- const me = this;
3354
- return OK(function(...args) {
3355
- const parsedArgs = me._def.args.safeParse(args, params);
3356
- if (!parsedArgs.success) {
3357
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3358
- }
3359
- const result = Reflect.apply(fn, this, parsedArgs.data);
3360
- const parsedReturns = me._def.returns.safeParse(result, params);
3361
- if (!parsedReturns.success) {
3362
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3363
- }
3364
- return parsedReturns.data;
3365
- });
3366
- }
3367
- }
3368
- parameters() {
3369
- return this._def.args;
3370
- }
3371
- returnType() {
3372
- return this._def.returns;
3373
- }
3374
- args(...items) {
3375
- return new _ZodFunction({
3376
- ...this._def,
3377
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3378
- });
3379
- }
3380
- returns(returnType) {
3381
- return new _ZodFunction({
3382
- ...this._def,
3383
- returns: returnType
3384
- });
3385
- }
3386
- implement(func) {
3387
- const validatedFunc = this.parse(func);
3388
- return validatedFunc;
3389
- }
3390
- strictImplement(func) {
3391
- const validatedFunc = this.parse(func);
3392
- return validatedFunc;
3393
- }
3394
- static create(args, returns, params) {
3395
- return new _ZodFunction({
3396
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3397
- returns: returns || ZodUnknown.create(),
3398
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3399
- ...processCreateParams(params)
3400
- });
3401
- }
3402
- };
3403
- var ZodLazy = class extends ZodType {
3404
- get schema() {
3405
- return this._def.getter();
3406
- }
3407
- _parse(input) {
3408
- const { ctx } = this._processInputParams(input);
3409
- const lazySchema = this._def.getter();
3410
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3411
- }
3412
- };
3413
- ZodLazy.create = (getter, params) => {
3414
- return new ZodLazy({
3415
- getter,
3416
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3417
- ...processCreateParams(params)
3418
- });
3419
- };
3420
- var ZodLiteral = class extends ZodType {
3421
- _parse(input) {
3422
- if (input.data !== this._def.value) {
3423
- const ctx = this._getOrReturnCtx(input);
3424
- addIssueToContext(ctx, {
3425
- received: ctx.data,
3426
- code: ZodIssueCode.invalid_literal,
3427
- expected: this._def.value
3428
- });
3429
- return INVALID;
3430
- }
3431
- return { status: "valid", value: input.data };
3432
- }
3433
- get value() {
3434
- return this._def.value;
3435
- }
3436
- };
3437
- ZodLiteral.create = (value, params) => {
3438
- return new ZodLiteral({
3439
- value,
3440
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3441
- ...processCreateParams(params)
3442
- });
3443
- };
3444
- function createZodEnum(values, params) {
3445
- return new ZodEnum({
3446
- values,
3447
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3448
- ...processCreateParams(params)
3449
- });
3450
- }
3451
- var ZodEnum = class _ZodEnum extends ZodType {
3452
- _parse(input) {
3453
- if (typeof input.data !== "string") {
3454
- const ctx = this._getOrReturnCtx(input);
3455
- const expectedValues = this._def.values;
3456
- addIssueToContext(ctx, {
3457
- expected: util.joinValues(expectedValues),
3458
- received: ctx.parsedType,
3459
- code: ZodIssueCode.invalid_type
3460
- });
3461
- return INVALID;
3462
- }
3463
- if (!this._cache) {
3464
- this._cache = new Set(this._def.values);
3465
- }
3466
- if (!this._cache.has(input.data)) {
3467
- const ctx = this._getOrReturnCtx(input);
3468
- const expectedValues = this._def.values;
3469
- addIssueToContext(ctx, {
3470
- received: ctx.data,
3471
- code: ZodIssueCode.invalid_enum_value,
3472
- options: expectedValues
3473
- });
3474
- return INVALID;
3475
- }
3476
- return OK(input.data);
3477
- }
3478
- get options() {
3479
- return this._def.values;
3480
- }
3481
- get enum() {
3482
- const enumValues = {};
3483
- for (const val of this._def.values) {
3484
- enumValues[val] = val;
3485
- }
3486
- return enumValues;
3487
- }
3488
- get Values() {
3489
- const enumValues = {};
3490
- for (const val of this._def.values) {
3491
- enumValues[val] = val;
3492
- }
3493
- return enumValues;
3494
- }
3495
- get Enum() {
3496
- const enumValues = {};
3497
- for (const val of this._def.values) {
3498
- enumValues[val] = val;
3499
- }
3500
- return enumValues;
3501
- }
3502
- extract(values, newDef = this._def) {
3503
- return _ZodEnum.create(values, {
3504
- ...this._def,
3505
- ...newDef
3506
- });
3507
- }
3508
- exclude(values, newDef = this._def) {
3509
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3510
- ...this._def,
3511
- ...newDef
3512
- });
3513
- }
3514
- };
3515
- ZodEnum.create = createZodEnum;
3516
- var ZodNativeEnum = class extends ZodType {
3517
- _parse(input) {
3518
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3519
- const ctx = this._getOrReturnCtx(input);
3520
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3521
- const expectedValues = util.objectValues(nativeEnumValues);
3522
- addIssueToContext(ctx, {
3523
- expected: util.joinValues(expectedValues),
3524
- received: ctx.parsedType,
3525
- code: ZodIssueCode.invalid_type
3526
- });
3527
- return INVALID;
3528
- }
3529
- if (!this._cache) {
3530
- this._cache = new Set(util.getValidEnumValues(this._def.values));
3531
- }
3532
- if (!this._cache.has(input.data)) {
3533
- const expectedValues = util.objectValues(nativeEnumValues);
3534
- addIssueToContext(ctx, {
3535
- received: ctx.data,
3536
- code: ZodIssueCode.invalid_enum_value,
3537
- options: expectedValues
3538
- });
3539
- return INVALID;
3540
- }
3541
- return OK(input.data);
3542
- }
3543
- get enum() {
3544
- return this._def.values;
3545
- }
3546
- };
3547
- ZodNativeEnum.create = (values, params) => {
3548
- return new ZodNativeEnum({
3549
- values,
3550
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3551
- ...processCreateParams(params)
3552
- });
3553
- };
3554
- var ZodPromise = class extends ZodType {
3555
- unwrap() {
3556
- return this._def.type;
3557
- }
3558
- _parse(input) {
3559
- const { ctx } = this._processInputParams(input);
3560
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3561
- addIssueToContext(ctx, {
3562
- code: ZodIssueCode.invalid_type,
3563
- expected: ZodParsedType.promise,
3564
- received: ctx.parsedType
3565
- });
3566
- return INVALID;
3567
- }
3568
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3569
- return OK(promisified.then((data) => {
3570
- return this._def.type.parseAsync(data, {
3571
- path: ctx.path,
3572
- errorMap: ctx.common.contextualErrorMap
3573
- });
3574
- }));
3575
- }
3576
- };
3577
- ZodPromise.create = (schema, params) => {
3578
- return new ZodPromise({
3579
- type: schema,
3580
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3581
- ...processCreateParams(params)
3582
- });
3583
- };
3584
- var ZodEffects = class extends ZodType {
3585
- innerType() {
3586
- return this._def.schema;
3587
- }
3588
- sourceType() {
3589
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3590
- }
3591
- _parse(input) {
3592
- const { status, ctx } = this._processInputParams(input);
3593
- const effect = this._def.effect || null;
3594
- const checkCtx = {
3595
- addIssue: (arg) => {
3596
- addIssueToContext(ctx, arg);
3597
- if (arg.fatal) {
3598
- status.abort();
3599
- } else {
3600
- status.dirty();
3601
- }
3602
- },
3603
- get path() {
3604
- return ctx.path;
3605
- }
3606
- };
3607
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3608
- if (effect.type === "preprocess") {
3609
- const processed = effect.transform(ctx.data, checkCtx);
3610
- if (ctx.common.async) {
3611
- return Promise.resolve(processed).then(async (processed2) => {
3612
- if (status.value === "aborted")
3613
- return INVALID;
3614
- const result = await this._def.schema._parseAsync({
3615
- data: processed2,
3616
- path: ctx.path,
3617
- parent: ctx
3618
- });
3619
- if (result.status === "aborted")
3620
- return INVALID;
3621
- if (result.status === "dirty")
3622
- return DIRTY(result.value);
3623
- if (status.value === "dirty")
3624
- return DIRTY(result.value);
3625
- return result;
3626
- });
3627
- } else {
3628
- if (status.value === "aborted")
3629
- return INVALID;
3630
- const result = this._def.schema._parseSync({
3631
- data: processed,
3632
- path: ctx.path,
3633
- parent: ctx
3634
- });
3635
- if (result.status === "aborted")
3636
- return INVALID;
3637
- if (result.status === "dirty")
3638
- return DIRTY(result.value);
3639
- if (status.value === "dirty")
3640
- return DIRTY(result.value);
3641
- return result;
3642
- }
3643
- }
3644
- if (effect.type === "refinement") {
3645
- const executeRefinement = (acc) => {
3646
- const result = effect.refinement(acc, checkCtx);
3647
- if (ctx.common.async) {
3648
- return Promise.resolve(result);
3649
- }
3650
- if (result instanceof Promise) {
3651
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3652
- }
3653
- return acc;
3654
- };
3655
- if (ctx.common.async === false) {
3656
- const inner = this._def.schema._parseSync({
3657
- data: ctx.data,
3658
- path: ctx.path,
3659
- parent: ctx
3660
- });
3661
- if (inner.status === "aborted")
3662
- return INVALID;
3663
- if (inner.status === "dirty")
3664
- status.dirty();
3665
- executeRefinement(inner.value);
3666
- return { status: status.value, value: inner.value };
3667
- } else {
3668
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3669
- if (inner.status === "aborted")
3670
- return INVALID;
3671
- if (inner.status === "dirty")
3672
- status.dirty();
3673
- return executeRefinement(inner.value).then(() => {
3674
- return { status: status.value, value: inner.value };
3675
- });
3676
- });
3677
- }
3678
- }
3679
- if (effect.type === "transform") {
3680
- if (ctx.common.async === false) {
3681
- const base = this._def.schema._parseSync({
3682
- data: ctx.data,
3683
- path: ctx.path,
3684
- parent: ctx
3685
- });
3686
- if (!isValid(base))
3687
- return INVALID;
3688
- const result = effect.transform(base.value, checkCtx);
3689
- if (result instanceof Promise) {
3690
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3691
- }
3692
- return { status: status.value, value: result };
3693
- } else {
3694
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3695
- if (!isValid(base))
3696
- return INVALID;
3697
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3698
- status: status.value,
3699
- value: result
3700
- }));
3701
- });
3702
- }
3703
- }
3704
- util.assertNever(effect);
3705
- }
3706
- };
3707
- ZodEffects.create = (schema, effect, params) => {
3708
- return new ZodEffects({
3709
- schema,
3710
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3711
- effect,
3712
- ...processCreateParams(params)
3713
- });
3714
- };
3715
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3716
- return new ZodEffects({
3717
- schema,
3718
- effect: { type: "preprocess", transform: preprocess },
3719
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3720
- ...processCreateParams(params)
3721
- });
3722
- };
3723
- var ZodOptional = class extends ZodType {
3724
- _parse(input) {
3725
- const parsedType = this._getType(input);
3726
- if (parsedType === ZodParsedType.undefined) {
3727
- return OK(void 0);
3728
- }
3729
- return this._def.innerType._parse(input);
3730
- }
3731
- unwrap() {
3732
- return this._def.innerType;
3733
- }
3734
- };
3735
- ZodOptional.create = (type, params) => {
3736
- return new ZodOptional({
3737
- innerType: type,
3738
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3739
- ...processCreateParams(params)
3740
- });
3741
- };
3742
- var ZodNullable = class extends ZodType {
3743
- _parse(input) {
3744
- const parsedType = this._getType(input);
3745
- if (parsedType === ZodParsedType.null) {
3746
- return OK(null);
3747
- }
3748
- return this._def.innerType._parse(input);
3749
- }
3750
- unwrap() {
3751
- return this._def.innerType;
3752
- }
3753
- };
3754
- ZodNullable.create = (type, params) => {
3755
- return new ZodNullable({
3756
- innerType: type,
3757
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3758
- ...processCreateParams(params)
3759
- });
3760
- };
3761
- var ZodDefault = class extends ZodType {
3762
- _parse(input) {
3763
- const { ctx } = this._processInputParams(input);
3764
- let data = ctx.data;
3765
- if (ctx.parsedType === ZodParsedType.undefined) {
3766
- data = this._def.defaultValue();
3767
- }
3768
- return this._def.innerType._parse({
3769
- data,
3770
- path: ctx.path,
3771
- parent: ctx
3772
- });
3773
- }
3774
- removeDefault() {
3775
- return this._def.innerType;
3776
- }
3777
- };
3778
- ZodDefault.create = (type, params) => {
3779
- return new ZodDefault({
3780
- innerType: type,
3781
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3782
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3783
- ...processCreateParams(params)
3784
- });
3785
- };
3786
- var ZodCatch = class extends ZodType {
3787
- _parse(input) {
3788
- const { ctx } = this._processInputParams(input);
3789
- const newCtx = {
3790
- ...ctx,
3791
- common: {
3792
- ...ctx.common,
3793
- issues: []
3794
- }
3795
- };
3796
- const result = this._def.innerType._parse({
3797
- data: newCtx.data,
3798
- path: newCtx.path,
3799
- parent: {
3800
- ...newCtx
3801
- }
3802
- });
3803
- if (isAsync(result)) {
3804
- return result.then((result2) => {
3805
- return {
3806
- status: "valid",
3807
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
3808
- get error() {
3809
- return new ZodError(newCtx.common.issues);
3810
- },
3811
- input: newCtx.data
3812
- })
3813
- };
3814
- });
3815
- } else {
3816
- return {
3817
- status: "valid",
3818
- value: result.status === "valid" ? result.value : this._def.catchValue({
3819
- get error() {
3820
- return new ZodError(newCtx.common.issues);
3821
- },
3822
- input: newCtx.data
3823
- })
3824
- };
3825
- }
3826
- }
3827
- removeCatch() {
3828
- return this._def.innerType;
3829
- }
3830
- };
3831
- ZodCatch.create = (type, params) => {
3832
- return new ZodCatch({
3833
- innerType: type,
3834
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3835
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3836
- ...processCreateParams(params)
3837
- });
3838
- };
3839
- var ZodNaN = class extends ZodType {
3840
- _parse(input) {
3841
- const parsedType = this._getType(input);
3842
- if (parsedType !== ZodParsedType.nan) {
3843
- const ctx = this._getOrReturnCtx(input);
3844
- addIssueToContext(ctx, {
3845
- code: ZodIssueCode.invalid_type,
3846
- expected: ZodParsedType.nan,
3847
- received: ctx.parsedType
3848
- });
3849
- return INVALID;
3850
- }
3851
- return { status: "valid", value: input.data };
3852
- }
3853
- };
3854
- ZodNaN.create = (params) => {
3855
- return new ZodNaN({
3856
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3857
- ...processCreateParams(params)
3858
- });
3859
- };
3860
- var BRAND = Symbol("zod_brand");
3861
- var ZodBranded = class extends ZodType {
3862
- _parse(input) {
3863
- const { ctx } = this._processInputParams(input);
3864
- const data = ctx.data;
3865
- return this._def.type._parse({
3866
- data,
3867
- path: ctx.path,
3868
- parent: ctx
3869
- });
3870
- }
3871
- unwrap() {
3872
- return this._def.type;
3873
- }
3874
- };
3875
- var ZodPipeline = class _ZodPipeline extends ZodType {
3876
- _parse(input) {
3877
- const { status, ctx } = this._processInputParams(input);
3878
- if (ctx.common.async) {
3879
- const handleAsync = async () => {
3880
- const inResult = await this._def.in._parseAsync({
3881
- data: ctx.data,
3882
- path: ctx.path,
3883
- parent: ctx
3884
- });
3885
- if (inResult.status === "aborted")
3886
- return INVALID;
3887
- if (inResult.status === "dirty") {
3888
- status.dirty();
3889
- return DIRTY(inResult.value);
3890
- } else {
3891
- return this._def.out._parseAsync({
3892
- data: inResult.value,
3893
- path: ctx.path,
3894
- parent: ctx
3895
- });
3896
- }
3897
- };
3898
- return handleAsync();
3899
- } else {
3900
- const inResult = this._def.in._parseSync({
3901
- data: ctx.data,
3902
- path: ctx.path,
3903
- parent: ctx
3904
- });
3905
- if (inResult.status === "aborted")
3906
- return INVALID;
3907
- if (inResult.status === "dirty") {
3908
- status.dirty();
3909
- return {
3910
- status: "dirty",
3911
- value: inResult.value
3912
- };
3913
- } else {
3914
- return this._def.out._parseSync({
3915
- data: inResult.value,
3916
- path: ctx.path,
3917
- parent: ctx
3918
- });
3919
- }
3920
- }
3921
- }
3922
- static create(a, b) {
3923
- return new _ZodPipeline({
3924
- in: a,
3925
- out: b,
3926
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3927
- });
3928
- }
3929
- };
3930
- var ZodReadonly = class extends ZodType {
3931
- _parse(input) {
3932
- const result = this._def.innerType._parse(input);
3933
- const freeze = (data) => {
3934
- if (isValid(data)) {
3935
- data.value = Object.freeze(data.value);
3936
- }
3937
- return data;
3938
- };
3939
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3940
- }
3941
- unwrap() {
3942
- return this._def.innerType;
3943
- }
3944
- };
3945
- ZodReadonly.create = (type, params) => {
3946
- return new ZodReadonly({
3947
- innerType: type,
3948
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3949
- ...processCreateParams(params)
3950
- });
3951
- };
3952
- function cleanParams(params, data) {
3953
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3954
- const p2 = typeof p === "string" ? { message: p } : p;
3955
- return p2;
3956
- }
3957
- function custom(check, _params = {}, fatal) {
3958
- if (check)
3959
- return ZodAny.create().superRefine((data, ctx) => {
3960
- const r = check(data);
3961
- if (r instanceof Promise) {
3962
- return r.then((r2) => {
3963
- if (!r2) {
3964
- const params = cleanParams(_params, data);
3965
- const _fatal = params.fatal ?? fatal ?? true;
3966
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3967
- }
3968
- });
3969
- }
3970
- if (!r) {
3971
- const params = cleanParams(_params, data);
3972
- const _fatal = params.fatal ?? fatal ?? true;
3973
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3974
- }
3975
- return;
3976
- });
3977
- return ZodAny.create();
3978
- }
3979
- var late = {
3980
- object: ZodObject.lazycreate
3981
- };
3982
- var ZodFirstPartyTypeKind;
3983
- (function(ZodFirstPartyTypeKind2) {
3984
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3985
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3986
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3987
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3988
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3989
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3990
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3991
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3992
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3993
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3994
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3995
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3996
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3997
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3998
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3999
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4000
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4001
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4002
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4003
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4004
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4005
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4006
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4007
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4008
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4009
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4010
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4011
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4012
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4013
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4014
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4015
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4016
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4017
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4018
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4019
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4020
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4021
- var instanceOfType = (cls, params = {
4022
- message: `Input not instance of ${cls.name}`
4023
- }) => custom((data) => data instanceof cls, params);
4024
- var stringType = ZodString.create;
4025
- var numberType = ZodNumber.create;
4026
- var nanType = ZodNaN.create;
4027
- var bigIntType = ZodBigInt.create;
4028
- var booleanType = ZodBoolean.create;
4029
- var dateType = ZodDate.create;
4030
- var symbolType = ZodSymbol.create;
4031
- var undefinedType = ZodUndefined.create;
4032
- var nullType = ZodNull.create;
4033
- var anyType = ZodAny.create;
4034
- var unknownType = ZodUnknown.create;
4035
- var neverType = ZodNever.create;
4036
- var voidType = ZodVoid.create;
4037
- var arrayType = ZodArray.create;
4038
- var objectType = ZodObject.create;
4039
- var strictObjectType = ZodObject.strictCreate;
4040
- var unionType = ZodUnion.create;
4041
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
4042
- var intersectionType = ZodIntersection.create;
4043
- var tupleType = ZodTuple.create;
4044
- var recordType = ZodRecord.create;
4045
- var mapType = ZodMap.create;
4046
- var setType = ZodSet.create;
4047
- var functionType = ZodFunction.create;
4048
- var lazyType = ZodLazy.create;
4049
- var literalType = ZodLiteral.create;
4050
- var enumType = ZodEnum.create;
4051
- var nativeEnumType = ZodNativeEnum.create;
4052
- var promiseType = ZodPromise.create;
4053
- var effectsType = ZodEffects.create;
4054
- var optionalType = ZodOptional.create;
4055
- var nullableType = ZodNullable.create;
4056
- var preprocessType = ZodEffects.createWithPreprocess;
4057
- var pipelineType = ZodPipeline.create;
4058
- var ostring = () => stringType().optional();
4059
- var onumber = () => numberType().optional();
4060
- var oboolean = () => booleanType().optional();
4061
- var coerce = {
4062
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4063
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4064
- boolean: ((arg) => ZodBoolean.create({
4065
- ...arg,
4066
- coerce: true
4067
- })),
4068
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4069
- date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4070
- };
4071
- var NEVER = INVALID;
4072
-
4073
44
  // src/client.ts
45
+ var import_zod = require("zod");
4074
46
  var RichError = class extends Error {
4075
47
  status;
4076
- // HTTP status code (e.g. 404, 500)
4077
48
  code;
4078
- // Application-level error code (e.g. "USER_NOT_FOUND")
4079
49
  title;
4080
- // Optional title or short summary
4081
50
  detail;
4082
- // Additional human-readable explanation
4083
51
  errors;
4084
- // Field-specific validation errors
4085
52
  constructor(error) {
4086
53
  super(error.message);
4087
54
  Object.assign(this, error);
4088
55
  }
4089
56
  };
57
+ var REQUEST_PART_KEYS = /* @__PURE__ */ new Set([
58
+ "path",
59
+ "query",
60
+ "body",
61
+ "headers",
62
+ "header"
63
+ ]);
4090
64
  var ApiClient = class {
4091
65
  constructor(config, contracts) {
4092
66
  this.config = config;
@@ -4095,28 +69,17 @@ var ApiClient = class {
4095
69
  this.mockDelay = config.mockDelay || { min: 100, max: 1e3 };
4096
70
  this.tokenProvider = config.tokenProvider;
4097
71
  }
72
+ config;
73
+ contracts;
4098
74
  middlewares = [];
4099
- // Registered middlewares
4100
75
  errorHandler;
4101
- // Global error handler
4102
76
  responseTransform = (d) => d;
4103
- // Post-parse data transformer
4104
77
  useMockData = false;
4105
- // Whether mock responses are enabled
4106
78
  mockDelay = { min: 100, max: 1e3 };
4107
- // Mock latency range (ms)
4108
79
  responseWrapper;
4109
- // Wrapper for APIs with envelope structures
4110
80
  tokenProvider;
4111
- // Optional async token supplier
4112
- // Configuration for retry behavior
4113
81
  retryConfig;
4114
- // Holds generated API endpoint methods
4115
82
  _modules;
4116
- /**
4117
- * Builds all API methods (`modules`) dynamically from the Zod contract definition.
4118
- * After `init()` is called, each endpoint can be invoked through `client.modules.moduleName.endpointName()`.
4119
- */
4120
83
  init() {
4121
84
  const modules = {};
4122
85
  for (const moduleName in this.contracts) {
@@ -4129,92 +92,83 @@ var ApiClient = class {
4129
92
  }
4130
93
  this._modules = modules;
4131
94
  }
4132
- /** Provides access to initialized modules after calling `init()`. */
4133
95
  get modules() {
4134
96
  return this._modules;
4135
97
  }
4136
- /** Registers a new middleware in the client’s pipeline. */
4137
98
  use(middleware, options) {
4138
99
  this.middlewares.push({ fn: middleware, options });
4139
100
  }
4140
- /** Sets a global error handler function to unify error behavior. */
4141
101
  onError(handler) {
4142
102
  this.errorHandler = handler;
4143
103
  }
4144
- /** Defines a global transform function applied to all validated responses. */
4145
104
  useResponseTransform(fn) {
4146
105
  this.responseTransform = fn;
4147
106
  }
4148
- /** Configures the retry logic (max attempts, backoff mode, etc.). */
4149
107
  setRetryConfig(config) {
4150
108
  this.retryConfig = config;
4151
109
  }
4152
- /** Provides a custom token provider that returns tokens dynamically. */
4153
110
  setTokenProvider(provider) {
4154
111
  this.tokenProvider = provider;
4155
112
  }
4156
- /** Enables mock responses instead of network requests. */
4157
113
  setMockMode(enabled, delay) {
4158
114
  this.useMockData = enabled;
4159
115
  if (delay) this.mockDelay = delay;
4160
116
  }
4161
- /** Registers a wrapper schema for APIs that nest response data (e.g. `{ data, success, message }`). */
4162
117
  setResponseWrapper(wrapper) {
4163
118
  this.responseWrapper = wrapper;
4164
119
  }
4165
- /** Retrieves the current auth token, using a provider if available. */
4166
120
  async getCurrentToken() {
4167
121
  if (this.tokenProvider) return await this.tokenProvider();
4168
122
  return this.config.token;
4169
123
  }
4170
- /**
4171
- * Core request entry point used by auto-generated endpoint methods.
4172
- * Handles caching, deduplication, and mock mode routing.
4173
- */
4174
124
  async request(endpoint, input, options) {
4175
125
  const parsedInput = endpoint.request.parse(input);
4176
126
  if (this.useMockData && endpoint.mockData) {
4177
127
  return this.handleMockRequest(endpoint);
4178
128
  }
4179
- const { url, body } = this.buildUrlAndBody(endpoint, parsedInput);
4180
- const requestKey = JSON.stringify({ method: endpoint.method, url, body });
4181
- const promise = this.performRequestLogic(
129
+ const built = this.buildUrlAndBody(endpoint, parsedInput);
130
+ return this.performRequestLogic(
4182
131
  endpoint,
4183
132
  parsedInput,
4184
- url,
4185
- body,
4186
- requestKey,
133
+ built.url,
134
+ built.body,
135
+ built.headers,
136
+ built.parts,
4187
137
  options
4188
138
  );
4189
- return promise;
4190
139
  }
4191
- /**
4192
- * Full HTTP request workflow:
4193
- * - Token injection
4194
- * - Timeout support
4195
- * - Middleware pipeline
4196
- * - Fetch + response handling
4197
- * - Zod parsing + transformation
4198
- * - Caching
4199
- */
4200
- async performRequestLogic(endpoint, parsedInput, url, body, key, options) {
140
+ async performRequestLogic(endpoint, parsedInput, url, body, requestHeaders, requestParts, options) {
4201
141
  const headers = {};
4202
- const token = await this.getCurrentToken();
4203
- if (endpoint.auth && !token) {
4204
- const error = this.createError({
4205
- message: `Missing token for ${endpoint.path}`,
4206
- status: 401,
4207
- code: "NO_TOKEN"
4208
- });
4209
- this.errorHandler?.(error);
4210
- throw error;
4211
- }
4212
- if (endpoint.auth && token) headers["Authorization"] = `Bearer ${token}`;
4213
- if (endpoint.bodyType !== "form-data")
142
+ if (endpoint.bodyType !== "form-data") {
4214
143
  headers["Content-Type"] = "application/json";
144
+ }
145
+ const endpointHeaders = typeof endpoint.headers === "function" ? endpoint.headers(parsedInput) : endpoint.headers;
146
+ Object.assign(
147
+ headers,
148
+ this.normalizeHeaders(endpointHeaders),
149
+ requestHeaders
150
+ );
151
+ if (endpoint.auth) {
152
+ const token = await this.getCurrentToken();
153
+ if (!token) {
154
+ const error = this.createError({
155
+ message: `Missing token for ${endpoint.path}`,
156
+ status: 401,
157
+ code: "NO_TOKEN"
158
+ });
159
+ this.errorHandler?.(error);
160
+ throw error;
161
+ }
162
+ headers["Authorization"] = `Bearer ${token}`;
163
+ }
4215
164
  const ctx = {
4216
165
  url,
4217
- init: { method: endpoint.method, headers, body }
166
+ init: { method: endpoint.method, headers, body },
167
+ endpoint,
168
+ request: {
169
+ ...requestParts,
170
+ rawInput: parsedInput
171
+ }
4218
172
  };
4219
173
  let controller;
4220
174
  let timeoutId;
@@ -4222,8 +176,9 @@ var ApiClient = class {
4222
176
  controller = new AbortController();
4223
177
  timeoutId = setTimeout(() => controller.abort(), options.timeout);
4224
178
  }
4225
- if (options?.signal || controller)
179
+ if (options?.signal || controller) {
4226
180
  ctx.init.signal = options?.signal || controller?.signal;
181
+ }
4227
182
  const runner = this.middlewares.reduceRight(
4228
183
  (next, mw) => () => mw.fn(ctx, next, mw.options),
4229
184
  () => fetch(ctx.url, ctx.init)
@@ -4237,9 +192,9 @@ var ApiClient = class {
4237
192
  const parsedWrapped = wrappedSchema.parse(json);
4238
193
  if (parsedWrapped.success === false) {
4239
194
  const error = this.createError({
4240
- message: parsedWrapped.message || "Request failed",
195
+ message: parsedWrapped.message || parsedWrapped.error || "Request failed",
4241
196
  status: parsedWrapped.code || res.status,
4242
- code: `API_ERROR_${parsedWrapped.code}`
197
+ code: parsedWrapped.code ? `API_ERROR_${parsedWrapped.code}` : "API_ERROR"
4243
198
  });
4244
199
  this.errorHandler?.(error);
4245
200
  throw error;
@@ -4259,8 +214,7 @@ var ApiClient = class {
4259
214
  throw error;
4260
215
  }
4261
216
  const parsed = endpoint.response.parse(responseData);
4262
- const result = this.responseTransform(parsed);
4263
- return result;
217
+ return this.responseTransform(parsed);
4264
218
  };
4265
219
  try {
4266
220
  const result = await this.executeWithRetry(execute);
@@ -4273,10 +227,6 @@ var ApiClient = class {
4273
227
  throw error;
4274
228
  }
4275
229
  }
4276
- // =========================================================
4277
- // 🔁 RETRY ENGINE
4278
- // =========================================================
4279
- /** Executes a function with retry logic and configurable backoff strategy. */
4280
230
  async executeWithRetry(fn) {
4281
231
  if (!this.retryConfig) return fn();
4282
232
  const { maxRetries, backoff, retryCondition } = this.retryConfig;
@@ -4294,7 +244,6 @@ var ApiClient = class {
4294
244
  }
4295
245
  }
4296
246
  }
4297
- /** Calculates retry delay intervals for various backoff strategies. */
4298
247
  getBackoffDelay(type, attempt) {
4299
248
  const base = 300;
4300
249
  switch (type) {
@@ -4306,37 +255,129 @@ var ApiClient = class {
4306
255
  return base * Math.pow(2, attempt - 1);
4307
256
  }
4308
257
  }
4309
- // =========================================================
4310
- // 🔧 UTILITIES
4311
- // =========================================================
4312
- /** Builds the final URL and request body from the endpoint definition and input payload. */
4313
258
  buildUrlAndBody(endpoint, input) {
259
+ const parts = this.extractRequestParts(input);
4314
260
  let url = this.config.baseUrl + endpoint.path;
261
+ url = this.applyPathParams(url, parts.path);
262
+ url = this.appendQueryParams(url, parts.query);
4315
263
  let body;
4316
- if (endpoint.method !== "GET") {
264
+ const payload = parts.isStructured ? parts.body : input;
265
+ if (endpoint.method !== "GET" && payload !== void 0) {
4317
266
  if (endpoint.bodyType === "form-data") {
4318
- const form = new FormData();
4319
- for (const [k, v] of Object.entries(input.body || {})) {
4320
- if (v != null) form.append(k, v);
267
+ if (typeof FormData !== "undefined" && payload instanceof FormData) {
268
+ body = payload;
269
+ } else {
270
+ const form = new FormData();
271
+ if (this.isObjectRecord(payload)) {
272
+ for (const [key, value] of Object.entries(payload)) {
273
+ this.appendFormValue(form, key, value);
274
+ }
275
+ } else if (payload != null) {
276
+ form.append("value", String(payload));
277
+ }
278
+ body = form;
4321
279
  }
4322
- body = form;
4323
280
  } else {
4324
- body = JSON.stringify(input.body ?? input);
281
+ body = JSON.stringify(payload);
282
+ }
283
+ }
284
+ return { url, body, headers: parts.headers, parts };
285
+ }
286
+ extractRequestParts(input) {
287
+ if (this.isStructuredRequestInput(input)) {
288
+ return {
289
+ path: this.isObjectRecord(input.path) ? input.path : void 0,
290
+ query: this.isObjectRecord(input.query) ? input.query : void 0,
291
+ body: input.body,
292
+ headers: this.normalizeHeaders(input.headers ?? input.header),
293
+ isStructured: true
294
+ };
295
+ }
296
+ return {
297
+ body: input,
298
+ headers: {},
299
+ isStructured: false
300
+ };
301
+ }
302
+ isStructuredRequestInput(input) {
303
+ if (!this.isObjectRecord(input)) return false;
304
+ const keys = Object.keys(input);
305
+ if (keys.length === 0) return false;
306
+ return keys.some((key) => REQUEST_PART_KEYS.has(key)) && keys.every((key) => REQUEST_PART_KEYS.has(key));
307
+ }
308
+ isObjectRecord(value) {
309
+ return typeof value === "object" && value !== null && !Array.isArray(value);
310
+ }
311
+ applyPathParams(url, pathParams) {
312
+ return url.replace(/:([A-Za-z0-9_]+)/g, (_, key) => {
313
+ const value = pathParams?.[key];
314
+ if (value === void 0 || value === null) {
315
+ throw this.createError({
316
+ message: `Missing path param "${key}"`,
317
+ code: "MISSING_PATH_PARAM"
318
+ });
4325
319
  }
320
+ return encodeURIComponent(String(value));
321
+ });
322
+ }
323
+ appendQueryParams(url, query) {
324
+ if (!query) return url;
325
+ const params = new URLSearchParams();
326
+ for (const [key, value] of Object.entries(query)) {
327
+ this.appendQueryValue(params, key, value);
328
+ }
329
+ const queryString = params.toString();
330
+ if (!queryString) return url;
331
+ return `${url}${url.includes("?") ? "&" : "?"}${queryString}`;
332
+ }
333
+ appendQueryValue(params, key, value) {
334
+ if (value === void 0 || value === null) return;
335
+ if (Array.isArray(value)) {
336
+ for (const item of value) this.appendQueryValue(params, key, item);
337
+ return;
338
+ }
339
+ if (value instanceof Date) {
340
+ params.append(key, value.toISOString());
341
+ return;
342
+ }
343
+ if (typeof value === "object") {
344
+ params.append(key, JSON.stringify(value));
345
+ return;
346
+ }
347
+ params.append(key, String(value));
348
+ }
349
+ appendFormValue(form, key, value) {
350
+ if (value === void 0 || value === null) return;
351
+ if (Array.isArray(value)) {
352
+ for (const item of value) this.appendFormValue(form, key, item);
353
+ return;
354
+ }
355
+ if (value instanceof Date) {
356
+ form.append(key, value.toISOString());
357
+ return;
358
+ }
359
+ const isBlob = typeof Blob !== "undefined" && value instanceof Blob;
360
+ if (typeof value === "object" && !isBlob) {
361
+ form.append(key, JSON.stringify(value));
362
+ return;
363
+ }
364
+ form.append(key, value);
365
+ }
366
+ normalizeHeaders(headers) {
367
+ if (!this.isObjectRecord(headers)) return {};
368
+ const normalized = {};
369
+ for (const [key, value] of Object.entries(headers)) {
370
+ if (value === void 0 || value === null) continue;
371
+ normalized[key] = String(value);
4326
372
  }
4327
- return { url, body };
373
+ return normalized;
4328
374
  }
4329
- /** Creates and returns a RichError from details. */
4330
375
  createError(error) {
4331
376
  return new RichError(error);
4332
377
  }
4333
- /**
4334
- * Converts any thrown error to a standardized RichError instance.
4335
- * Also flattens Zod validation errors into readable messages.
4336
- */
4337
378
  normalizeError(err) {
4338
379
  if (err instanceof RichError) return err;
4339
- if (err instanceof external_exports.ZodError) {
380
+ if (err instanceof import_zod.z.ZodError) {
4340
381
  return this.createError({
4341
382
  message: `Validation error: ${err.errors.map((e) => e.message).join(", ")}`,
4342
383
  code: "VALIDATION_ERROR"
@@ -4344,10 +385,6 @@ var ApiClient = class {
4344
385
  }
4345
386
  return this.createError({ message: err.message || "Unknown error" });
4346
387
  }
4347
- /**
4348
- * Handles mock-mode requests by simulating a delayed network call
4349
- * and returning validated mock data.
4350
- */
4351
388
  async handleMockRequest(endpoint) {
4352
389
  const delay = Math.floor(
4353
390
  Math.random() * (this.mockDelay.max - this.mockDelay.min + 1)
@@ -4430,12 +467,265 @@ var cacheMiddleware = (options = {}) => {
4430
467
  };
4431
468
  };
4432
469
 
470
+ // src/middlewares/encryption.ts
471
+ var import_crypto_js = __toESM(require("crypto-js"));
472
+ var import_node_forge = __toESM(require("node-forge"));
473
+ function safeJsonParse(value) {
474
+ try {
475
+ return JSON.parse(value);
476
+ } catch {
477
+ return value;
478
+ }
479
+ }
480
+ function isPlainObject(value) {
481
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
482
+ }
483
+ function hasKey(value, key) {
484
+ return isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, key);
485
+ }
486
+ function toMiddlewareError(message, error) {
487
+ const err = new Error(
488
+ `${message}: ${error instanceof Error ? error.message : "Unknown error"}`
489
+ );
490
+ err.cause = error;
491
+ return err;
492
+ }
493
+ function encryptWithAES(value, key) {
494
+ return import_crypto_js.default.AES.encrypt(value, key).toString();
495
+ }
496
+ function decryptWithAES(value, key) {
497
+ const bytes = import_crypto_js.default.AES.decrypt(value, key);
498
+ return bytes.toString(import_crypto_js.default.enc.Utf8);
499
+ }
500
+ function encryptWithDES(value, key) {
501
+ return import_crypto_js.default.DES.encrypt(value, key).toString();
502
+ }
503
+ function decryptWithDES(value, key) {
504
+ const bytes = import_crypto_js.default.DES.decrypt(value, key);
505
+ return bytes.toString(import_crypto_js.default.enc.Utf8);
506
+ }
507
+ function encodeWithBase64(value) {
508
+ return import_crypto_js.default.enc.Base64.stringify(import_crypto_js.default.enc.Utf8.parse(value));
509
+ }
510
+ function decodeWithBase64(value) {
511
+ return import_crypto_js.default.enc.Base64.parse(value).toString(import_crypto_js.default.enc.Utf8);
512
+ }
513
+ function encryptWithRSA(value, publicKey) {
514
+ const publicKeyObject = import_node_forge.default.pki.publicKeyFromPem(publicKey);
515
+ const encrypted = publicKeyObject.encrypt(
516
+ import_node_forge.default.util.encodeUtf8(value),
517
+ "RSA-OAEP"
518
+ );
519
+ return import_node_forge.default.util.encode64(encrypted);
520
+ }
521
+ function decryptWithRSA(value, privateKey) {
522
+ const privateKeyObject = import_node_forge.default.pki.privateKeyFromPem(privateKey);
523
+ const decrypted = privateKeyObject.decrypt(
524
+ import_node_forge.default.util.decode64(value),
525
+ "RSA-OAEP"
526
+ );
527
+ return import_node_forge.default.util.decodeUtf8(decrypted);
528
+ }
529
+ async function encryptValue(value, method, keyMaterial, customHandlers) {
530
+ switch (method) {
531
+ case "AES": {
532
+ if (keyMaterial.type !== "symmetric") {
533
+ throw new Error("AES encryption requires symmetric key material.");
534
+ }
535
+ return encryptWithAES(value, keyMaterial.key);
536
+ }
537
+ case "DES": {
538
+ if (keyMaterial.type !== "symmetric") {
539
+ throw new Error("DES encryption requires symmetric key material.");
540
+ }
541
+ return encryptWithDES(value, keyMaterial.key);
542
+ }
543
+ case "Base64": {
544
+ return encodeWithBase64(value);
545
+ }
546
+ case "RSA": {
547
+ if (keyMaterial.type !== "rsa") {
548
+ throw new Error("RSA encryption requires RSA key material.");
549
+ }
550
+ return encryptWithRSA(value, keyMaterial.publicKey);
551
+ }
552
+ case "Custom": {
553
+ if (!customHandlers) {
554
+ throw new Error("Custom encryption requires custom handlers.");
555
+ }
556
+ return await customHandlers.encrypt(value, keyMaterial);
557
+ }
558
+ default: {
559
+ const exhaustiveCheck = method;
560
+ throw new Error(`Unsupported encryption method: ${exhaustiveCheck}`);
561
+ }
562
+ }
563
+ }
564
+ async function decryptValue(value, method, keyMaterial, customHandlers) {
565
+ switch (method) {
566
+ case "AES": {
567
+ if (keyMaterial.type !== "symmetric") {
568
+ throw new Error("AES decryption requires symmetric key material.");
569
+ }
570
+ return decryptWithAES(value, keyMaterial.key);
571
+ }
572
+ case "DES": {
573
+ if (keyMaterial.type !== "symmetric") {
574
+ throw new Error("DES decryption requires symmetric key material.");
575
+ }
576
+ return decryptWithDES(value, keyMaterial.key);
577
+ }
578
+ case "Base64": {
579
+ return decodeWithBase64(value);
580
+ }
581
+ case "RSA": {
582
+ if (keyMaterial.type !== "rsa") {
583
+ throw new Error("RSA decryption requires RSA key material.");
584
+ }
585
+ return decryptWithRSA(value, keyMaterial.privateKey);
586
+ }
587
+ case "Custom": {
588
+ if (!customHandlers) {
589
+ throw new Error("Custom decryption requires custom handlers.");
590
+ }
591
+ return await customHandlers.decrypt(value, keyMaterial);
592
+ }
593
+ default: {
594
+ const exhaustiveCheck = method;
595
+ throw new Error(`Unsupported decryption method: ${exhaustiveCheck}`);
596
+ }
597
+ }
598
+ }
599
+ async function processDeep(data, map, defaultMethod, transform) {
600
+ if (data == null || map == null) return data;
601
+ if (typeof map === "string") return await transform(data, map);
602
+ if (typeof map === "boolean") {
603
+ return map ? await transform(data, defaultMethod) : data;
604
+ }
605
+ if (Array.isArray(data)) {
606
+ if (!Array.isArray(map)) {
607
+ return Promise.all(
608
+ data.map((item) => processDeep(item, map, defaultMethod, transform))
609
+ );
610
+ }
611
+ return Promise.all(
612
+ data.map(
613
+ (item, idx) => processDeep(item, map[idx] ?? map[0], defaultMethod, transform)
614
+ )
615
+ );
616
+ }
617
+ if (isPlainObject(data) && isPlainObject(map)) {
618
+ const result = { ...data };
619
+ for (const key of Object.keys(map)) {
620
+ const childMap = map[key];
621
+ if (childMap == null) continue;
622
+ const currentVal = result[key];
623
+ if (currentVal !== void 0) {
624
+ result[key] = await processDeep(
625
+ currentVal,
626
+ childMap,
627
+ defaultMethod,
628
+ transform
629
+ );
630
+ }
631
+ }
632
+ return result;
633
+ }
634
+ return data;
635
+ }
636
+ function getRequestBodyMap(map) {
637
+ if (hasKey(map, "body")) {
638
+ return map.body;
639
+ }
640
+ return map;
641
+ }
642
+ var encryptionMiddleware = async (ctx, next, options) => {
643
+ if (!options) {
644
+ throw new Error("Encryption middleware options were not provided.");
645
+ }
646
+ const { keyProvider, customHandlers } = options;
647
+ const failClosed = options.failClosed ?? true;
648
+ const encryption = ctx.endpoint.encryption;
649
+ if (!encryption || !encryption.request && !encryption.response) {
650
+ return next();
651
+ }
652
+ const requestMethod = typeof encryption.method === "string" ? encryption.method : encryption.method?.request ?? "AES";
653
+ const responseMethod = typeof encryption.method === "string" ? encryption.method : encryption.method?.response ?? "AES";
654
+ const keyMaterial = await keyProvider();
655
+ if (encryption.request && typeof ctx.init.body === "string" && ctx.init.body.length > 0) {
656
+ try {
657
+ const parsedBody = JSON.parse(ctx.init.body);
658
+ const bodyMap = getRequestBodyMap(encryption.request);
659
+ const encryptedBody = await processDeep(
660
+ parsedBody,
661
+ bodyMap,
662
+ requestMethod,
663
+ async (value, method) => {
664
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
665
+ return encryptValue(serialized, method, keyMaterial, customHandlers);
666
+ }
667
+ );
668
+ ctx.init.body = JSON.stringify(encryptedBody);
669
+ if (ctx.request) {
670
+ ctx.request.body = encryptedBody;
671
+ }
672
+ } catch (error) {
673
+ if (failClosed) {
674
+ throw toMiddlewareError(
675
+ "Encryption middleware request encryption failed",
676
+ error
677
+ );
678
+ }
679
+ console.error("Encryption middleware request encryption failed.", error);
680
+ }
681
+ }
682
+ const response = await next();
683
+ if (!encryption.response) {
684
+ return response;
685
+ }
686
+ try {
687
+ const text = await response.clone().text();
688
+ if (!text) return response;
689
+ const parsedResponse = JSON.parse(text);
690
+ const decryptedPayload = await processDeep(
691
+ parsedResponse,
692
+ encryption.response,
693
+ responseMethod,
694
+ async (value, method) => {
695
+ if (typeof value !== "string") return value;
696
+ const decrypted = await decryptValue(
697
+ value,
698
+ method,
699
+ keyMaterial,
700
+ customHandlers
701
+ );
702
+ return safeJsonParse(decrypted);
703
+ }
704
+ );
705
+ return new Response(JSON.stringify(decryptedPayload), {
706
+ status: response.status,
707
+ statusText: response.statusText,
708
+ headers: response.headers
709
+ });
710
+ } catch (error) {
711
+ if (failClosed) {
712
+ throw toMiddlewareError(
713
+ "Encryption middleware response decryption failed",
714
+ error
715
+ );
716
+ }
717
+ console.error("Encryption middleware response decryption failed.", error);
718
+ return response;
719
+ }
720
+ };
721
+
4433
722
  // src/utils/make-request-schema.ts
4434
- var makeRequestSchema = () => (defs) => external_exports.object({
4435
- path: (defs.path ?? external_exports.object({}))?.optional(),
4436
- query: (defs.query ?? external_exports.object({}))?.optional(),
4437
- body: defs.body ?? external_exports.undefined(),
4438
- headers: defs.headers ?? external_exports.record(external_exports.string()).optional()
723
+ var import_zod2 = require("zod");
724
+ var makeRequestSchema = () => (defs = {}) => import_zod2.z.object({
725
+ path: (defs.path ?? import_zod2.z.object({})).optional(),
726
+ query: (defs.query ?? import_zod2.z.object({})).optional(),
727
+ body: defs.body ?? import_zod2.z.undefined(),
728
+ headers: defs.headers ?? import_zod2.z.record(import_zod2.z.string()).optional()
4439
729
  });
4440
730
  // Annotate the CommonJS export names for ESM import in node:
4441
731
  0 && (module.exports = {
@@ -4443,8 +733,10 @@ var makeRequestSchema = () => (defs) => external_exports.object({
4443
733
  RichError,
4444
734
  authMiddleware,
4445
735
  cacheMiddleware,
736
+ encryptionMiddleware,
4446
737
  loggingMiddleware,
4447
738
  makeRequestSchema,
739
+ processDeep,
4448
740
  retryMiddleware
4449
741
  });
4450
742
  //# sourceMappingURL=index.js.map