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