@verdocs/web-sdk 2.1.2 → 2.2.0

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