@scout9/app 1.0.0-alpha.0.2.4 → 1.0.0-alpha.0.2.6

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