@seed-design/mcp 0.0.2

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