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